supercode-harness 0.4.3

The optional native Supercode agent and tool harness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Versioned public SDK contract shared by every Supercode surface.
//!
//! This module names the operations, capabilities, events, and errors that
//! transports project. CLI, JSON-RPC, HTTP, MCP, ACP, and language clients
//! may add correlation ids or wire metadata, but they must not define a
//! second execution contract or place those envelope fields in a session.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::Path;
use std::sync::Arc;

use crate::{
    Agent, Config, DiscoveryPage, DiscoveryQuery, Fidelity, HarnessCatalog, Result as CoreResult,
    Session, SessionDescriptor, SessionLocator,
};

/// Renderable prompt source configured on an SDK emulation component.
///
/// MCP implements this seam, but the SDK does not depend on MCP transport or
/// client types, so removing the MCP adapter leaves runtime semantics intact.
#[async_trait]
pub trait SdkPromptSource: Send + Sync {
    /// Render one prompt with its named arguments.
    async fn render(&self, args: std::collections::BTreeMap<String, String>) -> CoreResult<String>;
    /// Declared argument names in stable source order.
    fn arg_names(&self) -> &[String];
}

/// Current language-neutral SDK schema.
pub const SDK_SCHEMA_VERSION: &str = "supercode.sdk.v1";

/// Discover persisted sessions through the canonical SDK catalog owner.
pub fn discover_sessions(query: &DiscoveryQuery) -> CoreResult<Vec<SessionDescriptor>> {
    Ok(HarnessCatalog::new().discover(query)?)
}

/// Discover one persisted-session page with its opaque successor cursor.
pub fn discover_session_page(query: &DiscoveryQuery) -> CoreResult<DiscoveryPage> {
    Ok(HarnessCatalog::new().discover_page(query)?)
}

/// Load one durable locator through the canonical SDK catalog owner.
pub fn load_session(locator: &SessionLocator) -> CoreResult<Session> {
    Ok(HarnessCatalog::new().load(locator)?)
}

/// [`load_session`] at a declared fidelity.
///
/// Read-only surfaces pass [`Fidelity::Semantic`] so a transcript whose record
/// graph cannot be reconstructed exactly still renders, with the degradation
/// named in [`Session::load_residue`]. Continuation, transfer and export
/// callers keep the strict default of [`load_session`].
pub fn load_session_with_fidelity(
    locator: &SessionLocator,
    fidelity: Fidelity,
) -> CoreResult<Session> {
    Ok(HarnessCatalog::new().load_with_fidelity(locator, fidelity)?)
}

/// Load an explicit transcript/store path through the SDK import boundary.
/// An OpenCode selector is accepted only for its SQLite store.
pub fn load_session_path(path: &Path, opencode_session: Option<&str>) -> CoreResult<Session> {
    if opencode_session.is_some() {
        return Ok(Session::from_opencode_sqlite(path, opencode_session)?);
    }
    if let Some(session) = load_native_store_family(path)? {
        return Ok(session);
    }
    Ok(Session::load(path)?)
}

pub(crate) fn load_native_store_family(path: &Path) -> CoreResult<Option<Session>> {
    Ok(supercode_interchange::load_native_store_family(path)?)
}

/// SDK-owned emulation runtime component.
///
/// The wrapper makes ownership transfer explicit: public adapters receive an
/// SDK component, and [`crate::server::RpcEngine`] consumes that component as
/// the sole live-loop owner. It intentionally does not implement `Deref`:
/// model/tool-loop entry points stay unreachable outside the SDK/runtime
/// implementation boundary.
pub struct SdkAgent(Agent);

impl SdkAgent {
    pub(crate) fn from_agent(agent: Agent) -> Self {
        Self(agent)
    }

    pub(crate) fn inner(&self) -> &Agent {
        &self.0
    }

    pub(crate) fn inner_mut(&mut self) -> &mut Agent {
        &mut self.0
    }

    /// Read the resolved runtime configuration without acquiring loop ownership.
    pub fn config(&self) -> &Config {
        self.0.config()
    }

    /// Install the full-fidelity sidecar writer used by SDK persistence.
    pub fn set_recorder(&mut self, writer: crate::sidecar::SidecarWriter) {
        self.0.set_recorder(writer);
    }

    /// Install the reversible provider-view reduction policy.
    pub fn set_reduction_policy(&mut self, policy: crate::reduce::ReductionPolicy) {
        self.0.set_reduction_policy(policy);
    }

    /// Inspect the current provider-view reduction policy.
    pub fn reduction_policy(&self) -> Option<&crate::reduce::ReductionPolicy> {
        self.0.reduction_policy()
    }

    /// Replace the reversible reduction log after an SDK-owned projection.
    pub fn set_reduction_log(&mut self, log: crate::reduce::ReductionLog) {
        self.0.set_reduction_log(log);
    }

    /// Inspect the reversible reduction log.
    pub fn reduction_log(&self) -> &crate::reduce::ReductionLog {
        self.0.reduction_log()
    }

    /// Prepare optional cleared-turn summary metadata without sending a turn.
    pub fn prepare_cleared_turns_summary(
        &self,
        messages: &[crate::ChatMessage],
        policy: &crate::reduce::ReductionPolicy,
        prior: &crate::reduce::ReductionLog,
    ) -> Option<crate::reduce::PreparedClearSummary> {
        self.0
            .prepare_cleared_turns_summary(messages, policy, prior)
    }

    /// Install a reduction span summarizer.
    pub fn set_span_summarizer(
        &mut self,
        summarizer: impl crate::reduce::summarize::SpanSummarizer + Send + Sync + 'static,
    ) {
        self.0.set_span_summarizer(summarizer);
    }

    /// Install the optional persisted-session title generator.
    pub fn set_session_titler(
        &mut self,
        titler: impl crate::session_title::SessionTitler + Send + Sync + 'static,
    ) {
        self.0.set_session_titler(titler);
    }

    /// Generate a title from canonical history when configured.
    pub fn auto_title(&self) -> Option<String> {
        self.0.auto_title()
    }

    /// Attach a session store for SDK-owned subagent persistence.
    pub fn set_subagent_store(
        &mut self,
        store: std::sync::Arc<crate::SessionStore>,
        session_name: impl Into<String>,
    ) {
        self.0.set_subagent_store(store, session_name);
    }

    /// Install restored Claude runtime state without activating a timer.
    pub fn set_claude_runtime_manifest(
        &mut self,
        manifest: crate::claude_runtime_state::ClaudeRuntimeManifest,
    ) {
        self.0.set_claude_runtime_manifest(manifest);
    }

    /// Inspect restored Claude runtime state.
    pub fn claude_runtime_manifest(
        &self,
    ) -> Option<&crate::claude_runtime_state::ClaudeRuntimeManifest> {
        self.0.claude_runtime_manifest()
    }

    /// Mutate Claude runtime state from the SDK scheduler/persistence driver.
    pub fn claude_runtime_manifest_mut(
        &mut self,
    ) -> Option<&mut crate::claude_runtime_state::ClaudeRuntimeManifest> {
        self.0.claude_runtime_manifest_mut()
    }

    /// Restore project-scoped Claude agent definitions after disk reload.
    pub fn restore_claude_project_agents(&mut self) -> CoreResult<usize> {
        self.0.restore_claude_project_agents()
    }

    /// Replace canonical history with a loaded normalized session.
    pub fn load_session(&mut self, session: Session) {
        self.0.load_session(session);
    }

    /// Load a Supercode transcript through the SDK component.
    pub fn load_transcript(&mut self, path: impl AsRef<Path>) -> CoreResult<()> {
        self.0.load_transcript(path)
    }

    /// Save the canonical transcript through the SDK component.
    pub fn save_transcript(&self, path: impl AsRef<Path>) -> CoreResult<()> {
        self.0.save_transcript(path)
    }

    /// Read canonical history at a quiescent boundary.
    pub fn history(&self) -> &[crate::ChatMessage] {
        self.0.history()
    }

    /// Rewind canonical history to a prior message boundary.
    pub fn rewind_to(&mut self, checkpoint: usize) {
        self.0.rewind_to(checkpoint);
    }

    /// Append an SDK-assembled system note.
    pub fn append_system_note(&mut self, text: &str) {
        self.0.append_system_note(text);
    }

    /// Register one configured tool before transferring live-loop ownership.
    pub fn register_tool(&mut self, tool: impl crate::Tool + 'static) {
        self.0.register_tool(tool);
    }

    /// Register one MCP prompt source before transferring loop ownership.
    pub fn register_mcp_prompt(
        &mut self,
        command_name: impl Into<String>,
        source: impl SdkPromptSource + 'static,
    ) {
        self.0.register_mcp_prompt(command_name, source);
    }

    /// Inspect the exact next-request tool schemas for preflight measurement.
    pub fn tool_schemas(&self) -> Vec<crate::ToolSchema> {
        self.0.tool_schemas()
    }

    /// Arm the per-request context limit guard.
    pub fn set_context_limit(&mut self, limit: u64) {
        self.0.set_context_limit(limit);
    }

    /// Inspect the armed context limit.
    pub fn context_limit(&self) -> Option<u64> {
        self.0.context_limit()
    }

    /// Switch the next-request model at a quiescent boundary.
    pub fn set_model(&mut self, model: impl Into<String>) {
        self.0.set_model(model);
    }

    /// Whether a provider request has actually been issued.
    pub fn request_issued(&self) -> bool {
        self.0.request_issued()
    }

    /// Configured durable session name.
    pub fn session_name(&self) -> Option<&str> {
        self.0.session_name()
    }

    /// Whether persistence is enabled for this component.
    pub fn session_persist(&self) -> bool {
        self.0.session_persist()
    }

    /// Captured git provenance.
    pub fn git_metadata(&self) -> Option<&crate::git_metadata::GitMetadataRecord> {
        self.0.git_metadata()
    }

    /// Save captured git provenance.
    pub fn save_git_metadata(&self, store: &crate::SessionStore, name: &str) -> CoreResult<()> {
        self.0.save_git_metadata(store, name)
    }

    /// Number of non-system canonical messages.
    pub fn turn_count(&self) -> usize {
        self.0.turn_count()
    }

    /// Cumulative provider-reported output tokens.
    pub fn total_output_tokens(&self) -> u64 {
        self.0.total_output_tokens()
    }
}

impl From<Agent> for SdkAgent {
    fn from(agent: Agent) -> Self {
        Self::from_agent(agent)
    }
}

/// Construct the emulation component inside the SDK ownership boundary.
pub fn create_agent(config: Config) -> CoreResult<SdkAgent> {
    Agent::new(config).map(SdkAgent::from_agent)
}

/// Resume canonical history inside a fresh SDK-owned emulation component.
pub fn resume_agent(config: Config, session: Session) -> CoreResult<SdkAgent> {
    Agent::resume(config, session).map(SdkAgent::from_agent)
}

/// Submit one text turn through the SDK-owned emulation loop.
pub async fn submit_agent(agent: &mut SdkAgent, prompt: &str) -> CoreResult<String> {
    agent.0.send(prompt).await
}

/// Submit one multimodal turn through the SDK-owned emulation loop.
pub async fn submit_agent_with_images(
    agent: &mut SdkAgent,
    prompt: &str,
    image_urls: &[String],
) -> CoreResult<String> {
    agent.0.send_with_images(prompt, image_urls).await
}

/// One operation owned by the SDK facade.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SdkOperation {
    /// Discover persisted sessions.
    Discover,
    /// Load one persisted session without modifying it.
    Load,
    /// Start a harness-native runtime.
    Start,
    /// Resume a harness-native persisted runtime.
    Resume,
    /// Send input to an SDK-owned runtime connection.
    Input,
    /// Poll canonical runtime events.
    Events,
    /// Interrupt the active turn.
    Interrupt,
    /// Queue guidance at the next model-loop boundary.
    Steer,
    /// Answer a typed runtime request.
    Respond,
    /// Export a loaded session through a native serializer.
    Export,
    /// Close an SDK-owned runtime connection.
    Close,
}

impl SdkOperation {
    /// Complete v1 operation inventory in stable declaration order.
    pub const ALL: [Self; 11] = [
        Self::Discover,
        Self::Load,
        Self::Start,
        Self::Resume,
        Self::Input,
        Self::Events,
        Self::Interrupt,
        Self::Steer,
        Self::Respond,
        Self::Export,
        Self::Close,
    ];

    /// Canonical `harness.v1` method used by JSON transports, when the
    /// operation is request/response rather than a subscription poll.
    pub const fn method(self) -> Option<&'static str> {
        match self {
            Self::Discover => Some("harness.v1.sessions.discover"),
            Self::Load => Some("harness.v1.sessions.load"),
            Self::Start => Some("harness.v1.runtimes.start"),
            Self::Resume => Some("harness.v1.runtimes.resume"),
            Self::Input => Some("harness.v1.runtimes.send_input"),
            Self::Events => None,
            Self::Interrupt => Some("harness.v1.runtimes.interrupt"),
            Self::Steer => Some("harness.v1.runtimes.steer"),
            Self::Respond => Some("harness.v1.runtimes.respond"),
            Self::Export => Some("harness.v1.sessions.export"),
            Self::Close => Some("harness.v1.runtimes.close"),
        }
    }

    /// Resolve one canonical method without accepting transport aliases.
    pub fn from_method(method: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|operation| operation.method() == Some(method))
    }

    /// Stable action spelling used by capability and error projections.
    pub const fn action_name(self) -> &'static str {
        match self {
            Self::Discover => "discover",
            Self::Load => "load",
            Self::Start => "start",
            Self::Resume => "resume",
            Self::Input => "input",
            Self::Events => "events",
            Self::Interrupt => "interrupt",
            Self::Steer => "steer",
            Self::Respond => "respond",
            Self::Export => "export",
            Self::Close => "close",
        }
    }

    /// Resolve a stable action spelling.
    pub fn from_action_name(action: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|operation| operation.action_name() == action)
    }
}

/// One typed SDK request before a transport adds its envelope.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SdkRequest {
    /// Requested SDK operation.
    pub operation: SdkOperation,
    /// Operation-specific language-neutral parameters.
    #[serde(default)]
    pub params: Value,
}

/// Stable machine-readable SDK failure categories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SdkErrorCode {
    /// No authenticated client context was supplied.
    Unauthenticated,
    /// The authenticated client lacks a required capability.
    Unauthorized,
    /// Another client owns control or no controller lease was claimed.
    ControllerRequired,
    /// The caller's controller lease expired before the mutation.
    LeaseExpired,
    /// Input did not satisfy the operation contract.
    InvalidArgument,
    /// The requested session, runtime, or request was not found.
    NotFound,
    /// A turn already owns the runtime.
    Busy,
    /// The selected adapter honestly does not implement the operation.
    UnsupportedAction,
    /// A runtime or provider operation failed.
    Execution,
    /// The transport closed or returned an invalid envelope.
    Transport,
}

/// Typed turn failure shared by local, HTTP, ACP, CLI, and language adapters.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RuntimeSubmitError {
    /// Another turn already owns the runtime.
    #[error("a turn is already in progress")]
    Busy,
    /// The active turn was cancelled through the SDK runtime handle.
    #[error("turn interrupted")]
    Interrupted,
    /// The model/provider/tool loop failed.
    #[error("{0}")]
    Agent(String),
}

/// Typed failure returned by every SDK adapter and compatibility projection.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SdkError {
    /// A runtime operation was attempted without authenticated client state.
    #[error("SDK runtime authentication required")]
    Unauthenticated,
    /// The authenticated client lacks a required runtime permission.
    #[error("SDK runtime permission `{permission}` is required")]
    Unauthorized {
        /// Stable permission spelling.
        permission: String,
    },
    /// Mutation requires the controller lease. When another client owns it,
    /// its opaque identity and deadline are included for deterministic retry.
    #[error("controller lease required")]
    ControllerRequired {
        /// Current controller, when known.
        holder: Option<String>,
        /// Current controller deadline, when known.
        expires_at_ms: Option<u64>,
    },
    /// This client previously controlled the runtime but its lease expired.
    #[error("controller lease expired")]
    LeaseExpired,
    /// Input did not satisfy an operation contract.
    #[error("invalid SDK argument for {operation:?}: {message}")]
    InvalidArgument {
        /// Operation being decoded.
        operation: SdkOperation,
        /// Validation detail.
        message: String,
    },
    /// A stable identity was not found.
    #[error("SDK target for {operation:?} was not found: {message}")]
    NotFound {
        /// Operation being executed.
        operation: SdkOperation,
        /// Lookup detail.
        message: String,
    },
    /// The active adapter does not implement the requested action.
    #[error("SDK action `{0}` is not supported by this runtime")]
    UnsupportedAction(&'static str),
    /// The requested catalog operation is absent or has no typed route.
    #[error("SDK operation `{0}` is not supported by this runtime")]
    UnsupportedOperation(String),
    /// A slow consumer fell behind the bounded live-event channel.
    #[error("SDK event stream lost {0} event(s); reattach for a fresh snapshot")]
    ReplayGap(u64),
    /// The runtime closed its event stream.
    #[error("SDK runtime event stream closed")]
    Closed,
    /// An authenticated remote transport failed or returned an invalid value.
    #[error("SDK transport failed: {0}")]
    Transport(String),
    /// No live request exists for the supplied response id.
    #[error("SDK request {0} is not pending")]
    UnknownRequest(u64),
    /// The response kind or value does not match the pending request.
    #[error("invalid SDK response: {0}")]
    InvalidResponse(String),
    /// The canonical runtime rejected or failed a turn.
    #[error(transparent)]
    Submit(#[from] RuntimeSubmitError),
    /// A session/runtime implementation failed after validation.
    #[error("SDK execution failed for {operation:?}: {message}")]
    Execution {
        /// Operation being executed.
        operation: SdkOperation,
        /// Implementation detail.
        message: String,
    },
}

impl SdkError {
    /// Construct a typed failure for an SDK operation.
    pub fn new(code: SdkErrorCode, operation: SdkOperation, message: impl Into<String>) -> Self {
        let message = message.into();
        match code {
            SdkErrorCode::Unauthenticated => Self::Unauthenticated,
            SdkErrorCode::Unauthorized => Self::Unauthorized {
                permission: message,
            },
            SdkErrorCode::ControllerRequired => Self::ControllerRequired {
                holder: None,
                expires_at_ms: None,
            },
            SdkErrorCode::LeaseExpired => Self::LeaseExpired,
            SdkErrorCode::InvalidArgument => Self::InvalidArgument { operation, message },
            SdkErrorCode::NotFound => Self::NotFound { operation, message },
            SdkErrorCode::Busy => Self::Submit(RuntimeSubmitError::Busy),
            SdkErrorCode::UnsupportedAction => Self::unsupported(operation),
            SdkErrorCode::Execution => Self::Execution { operation, message },
            SdkErrorCode::Transport => Self::Transport(message),
        }
    }

    /// Construct a named unsupported-action failure.
    pub fn unsupported(operation: SdkOperation) -> Self {
        Self::UnsupportedAction(operation.action_name())
    }

    /// Stable machine-readable category.
    pub fn code(&self) -> SdkErrorCode {
        match self {
            Self::Unauthenticated => SdkErrorCode::Unauthenticated,
            Self::Unauthorized { .. } => SdkErrorCode::Unauthorized,
            Self::ControllerRequired { .. } => SdkErrorCode::ControllerRequired,
            Self::LeaseExpired => SdkErrorCode::LeaseExpired,
            Self::InvalidArgument { .. } | Self::InvalidResponse(_) => {
                SdkErrorCode::InvalidArgument
            }
            Self::NotFound { .. } | Self::UnknownRequest(_) => SdkErrorCode::NotFound,
            Self::Submit(RuntimeSubmitError::Busy) => SdkErrorCode::Busy,
            Self::UnsupportedAction(_) | Self::UnsupportedOperation(_) => {
                SdkErrorCode::UnsupportedAction
            }
            Self::Transport(_) | Self::ReplayGap(_) | Self::Closed => SdkErrorCode::Transport,
            Self::Submit(_) | Self::Execution { .. } => SdkErrorCode::Execution,
        }
    }

    /// Operation associated with this failure when it is unambiguous.
    pub fn operation(&self) -> Option<SdkOperation> {
        match self {
            Self::InvalidArgument { operation, .. }
            | Self::NotFound { operation, .. }
            | Self::Execution { operation, .. } => Some(*operation),
            Self::UnsupportedAction(action) => SdkOperation::from_action_name(action),
            Self::Unauthenticated
            | Self::Unauthorized { .. }
            | Self::ControllerRequired { .. }
            | Self::LeaseExpired => None,
            Self::UnknownRequest(_) | Self::InvalidResponse(_) => Some(SdkOperation::Respond),
            Self::Submit(_) => Some(SdkOperation::Input),
            Self::UnsupportedOperation(_)
            | Self::ReplayGap(_)
            | Self::Closed
            | Self::Transport(_) => None,
        }
    }
}

/// Capability inventory for the complete v1 SDK, independent of transport.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SdkCapabilities {
    /// Schema identifier governing this descriptor.
    pub schema_version: String,
    /// Operations understood by the facade. A concrete runtime may still
    /// return `unsupported_action` for a mechanically unavailable action.
    pub operations: Vec<SdkOperation>,
    /// Stable error categories clients must preserve by name.
    pub error_codes: Vec<SdkErrorCode>,
    /// Whether events preserve unknown native payloads losslessly.
    pub opaque_events: bool,
}

impl Default for SdkCapabilities {
    fn default() -> Self {
        Self {
            schema_version: SDK_SCHEMA_VERSION.into(),
            operations: SdkOperation::ALL.to_vec(),
            error_codes: vec![
                SdkErrorCode::Unauthenticated,
                SdkErrorCode::Unauthorized,
                SdkErrorCode::ControllerRequired,
                SdkErrorCode::LeaseExpired,
                SdkErrorCode::InvalidArgument,
                SdkErrorCode::NotFound,
                SdkErrorCode::Busy,
                SdkErrorCode::UnsupportedAction,
                SdkErrorCode::Execution,
                SdkErrorCode::Transport,
            ],
            opaque_events: true,
        }
    }
}

/// Canonical event before a wire transport adds subscription metadata.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SdkEvent {
    /// Monotonic sequence scoped to the SDK runtime.
    pub sequence: u64,
    /// Normalized or native event kind.
    pub kind: String,
    /// Complete payload, including unknown fields.
    pub payload: Value,
}

impl SdkEvent {
    pub(crate) fn new(sequence: u64, payload: Value) -> Self {
        let kind = payload
            .get("type")
            .or_else(|| payload.get("method"))
            .and_then(Value::as_str)
            .unwrap_or("unknown")
            .to_string();
        Self {
            sequence,
            kind,
            payload,
        }
    }
}

/// One runtime event paired with its durable SDK identity.
///
/// A transport may add a connection or subscription id around this value,
/// but those routing fields never become part of [`SdkEvent`] or a session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SdkRuntimeEvent {
    /// Stable SDK session identity, never a transport-local connection id.
    pub session_id: String,
    /// Canonical event shared by local and remote runtime adapters.
    pub event: SdkEvent,
}

/// Canonical live-runtime contract owned by the SDK.
///
/// Frontend modules are projections of this trait. They may render events or
/// add transport envelopes, but they do not own a second model loop.
#[async_trait]
pub trait SdkRuntime: Send + Sync {
    /// Describe runtime identity, modules, commands, actions, and state.
    async fn describe(&self) -> Result<crate::frontend::FrontendRuntimeDescriptor, SdkError>;
    /// Atomically attach at the canonical history/live-event boundary.
    async fn attach(
        &self,
        history_limit: usize,
    ) -> Result<crate::frontend::FrontendAttachment, SdkError>;
    /// Atomically accept a new user turn and return once ownership is claimed.
    ///
    /// Exactly one simultaneous caller succeeds. The accepted turn continues
    /// on the SDK-owned runtime and publishes its result through the canonical
    /// event stream; a competing caller receives [`SdkErrorCode::Busy`]
    /// synchronously from this operation.
    async fn send_input(self: Arc<Self>, prompt: String) -> Result<(), SdkError>;
    /// Atomically accept a multimodal user turn and return once ownership is
    /// claimed. Implementations must preserve images natively or reject the
    /// action; silently folding them into text is never allowed.
    async fn send_input_with_images(
        self: Arc<Self>,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<(), SdkError> {
        if image_urls.is_empty() {
            self.send_input(prompt).await
        } else {
            Err(SdkError::UnsupportedAction("send_input_attachments"))
        }
    }
    /// Submit a new user turn.
    async fn submit(&self, prompt: String) -> Result<String, SdkError>;
    /// Submit a new user turn with canonical multimodal image inputs.
    ///
    /// Frontends must pass only runtime-resolved URLs or data URIs here; the
    /// SDK runtime, not a remote display client, owns input interpretation.
    async fn submit_with_images(
        &self,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<String, SdkError> {
        if image_urls.is_empty() {
            self.submit(prompt).await
        } else {
            Err(SdkError::UnsupportedAction("submit_attachments"))
        }
    }
    /// Interrupt an active turn.
    async fn interrupt(&self) -> Result<bool, SdkError>;
    /// Queue a steering instruction when supported.
    async fn steer(&self, prompt: String) -> Result<(), SdkError>;
    /// Answer a typed runtime request when supported.
    async fn respond(&self, response: crate::frontend::FrontendResponse) -> Result<(), SdkError>;
    /// Invoke one operation from the descriptor's explicit catalog.
    async fn invoke(
        &self,
        operation: crate::frontend::FrontendOperationInvocation,
    ) -> Result<crate::frontend::FrontendOperationResult, SdkError> {
        Err(SdkError::UnsupportedOperation(
            operation.operation_id().to_string(),
        ))
    }
    /// Read the one-controller/many-observer ownership state.
    async fn lease_snapshot(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation("runtime.lease".into()))
    }
    /// Explicitly acquire the controller lease from another interactive
    /// client. Ordinary mutations never perform an implicit takeover.
    async fn take_control(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation(
            "runtime.take_control".into(),
        ))
    }
    /// Refresh observer activity and a controller lease owned by this client.
    async fn heartbeat(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation("runtime.heartbeat".into()))
    }
    /// Release this client's observer/controller state without stopping the
    /// runtime.
    async fn detach(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation("runtime.detach".into()))
    }
    /// Explicitly close the SDK-owned runtime when the negotiated descriptor
    /// grants that owner-level action. Dropping an attachment is always a
    /// detach and never calls this operation implicitly.
    async fn close(&self) -> Result<(), SdkError> {
        Err(SdkError::unsupported(SdkOperation::Close))
    }
}

/// Stateful SDK facade consumed by public transport adapters.
#[async_trait]
pub trait SdkService: Send {
    /// Describe the versioned contract without invoking a runtime.
    fn capabilities(&self) -> SdkCapabilities {
        SdkCapabilities::default()
    }

    /// Execute one typed request. Transport correlation fields are not part
    /// of this API and therefore cannot contaminate canonical state.
    async fn execute(&mut self, request: SdkRequest) -> Result<Value, SdkError>;

    /// Poll canonical runtime events without a transport envelope.
    async fn events(&mut self) -> Result<Vec<SdkRuntimeEvent>, SdkError>;
}