Skip to main content

cpa_plugin/
api.rs

1//! `sdk/pluginapi` request and response schemas, field for field. Wire names are the Go
2//! field names unless Go declares a json tag. Host-only members (`HTTPClient`, handler
3//! interfaces) are not part of the wire format and are left out.
4
5use std::collections::BTreeMap;
6
7use bytes::Bytes;
8
9use crate::go_struct;
10use crate::gojson::{GoJson, GoTime, Header, Metadata, Node, NonNil, NonNilBytes, RawJson, StringMap};
11
12go_struct! {
13    pub struct ConfigField("pluginapi.ConfigField") {
14        "Name" => name: String,
15        "Type" => field_type: String,
16        "EnumValues" => enum_values: Vec<String>,
17        "Description" => description: String,
18    }
19}
20
21go_struct! {
22    /// `pluginapi.Metadata`.
23    pub struct PluginMetadata("pluginapi.Metadata") {
24        "Name" => name: String,
25        "Version" => version: String,
26        "Author" => author: String,
27        "GitHubRepository" => github_repository: String,
28        "Logo" => logo: String,
29        // A plugin's empty list stays `[]` (Go decodes it into a non-nil slice).
30        "ConfigFields" => config_fields: Option<NonNil<Vec<ConfigField>>>,
31    }
32}
33
34impl PluginMetadata {
35    /// The declared configuration fields (none for nil or empty).
36    pub fn config_field_list(&self) -> &[ConfigField] {
37        self.config_fields.as_ref().map_or(&[], |fields| &fields.0)
38    }
39}
40
41go_struct! {
42    pub struct ThinkingSupport("pluginapi.ThinkingSupport") {
43        "Min" => min: i64,
44        "Max" => max: i64,
45        "ZeroAllowed" => zero_allowed: bool,
46        "DynamicAllowed" => dynamic_allowed: bool,
47        /// The Claude `thinking.type` that turns thinking off; empty means `disabled`.
48        "DisableType" => disable_type: String,
49        "Levels" => levels: Vec<String>,
50    }
51}
52
53go_struct! {
54    pub struct ModelInfo("pluginapi.ModelInfo") {
55        "ID" => id: String,
56        "Object" => object: String,
57        "Created" => created: i64,
58        "OwnedBy" => owned_by: String,
59        "Type" => model_type: String,
60        "DisplayName" => display_name: String,
61        "Name" => name: String,
62        "Version" => version: String,
63        "Description" => description: String,
64        "InputTokenLimit" => input_token_limit: i64,
65        "OutputTokenLimit" => output_token_limit: i64,
66        "SupportedGenerationMethods" => supported_generation_methods: Vec<String>,
67        "ContextLength" => context_length: i64,
68        "MaxCompletionTokens" => max_completion_tokens: i64,
69        "SupportedParameters" => supported_parameters: Vec<String>,
70        "SupportedInputModalities" => supported_input_modalities: Vec<String>,
71        "SupportedOutputModalities" => supported_output_modalities: Vec<String>,
72        "Thinking" => thinking: Option<ThinkingSupport>,
73        "UserDefined" => user_defined: bool,
74    }
75}
76
77go_struct! {
78    pub struct ModelAlias("pluginapi.ModelAlias") {
79        "Name" => name: String,
80        "Alias" => alias: String,
81    }
82}
83
84go_struct! {
85    pub struct HostConfigSummary("pluginapi.HostConfigSummary") {
86        "AuthDir" => auth_dir: String,
87        "ProxyURL" => proxy_url: String,
88        "ForceModelPrefix" => force_model_prefix: bool,
89        "OAuthModelAlias" => oauth_model_alias: BTreeMap<String, Vec<ModelAlias>>,
90        "ExcludedModels" => excluded_models: BTreeMap<String, Vec<String>>,
91    }
92}
93
94go_struct! {
95    pub struct AuthData("pluginapi.AuthData") {
96        "Provider" => provider: String,
97        "ID" => id: String,
98        "FileName" => file_name: String,
99        "Label" => label: String,
100        "Prefix" => prefix: String,
101        "ProxyURL" => proxy_url: String,
102        "Disabled" => disabled: bool,
103        "StorageJSON" => storage_json: Bytes,
104        "Metadata" => metadata: Metadata,
105        "Attributes" => attributes: StringMap,
106        "NextRefreshAfter" => next_refresh_after: GoTime,
107    }
108}
109
110go_struct! {
111    pub struct AuthParseRequest("pluginapi.AuthParseRequest") {
112        "Provider" => provider: String,
113        "Path" => path: String,
114        "FileName" => file_name: String,
115        "RawJSON" => raw_json: Bytes,
116        "Host" => host: HostConfigSummary,
117    }
118}
119
120go_struct! {
121    pub struct AuthParseResponse("pluginapi.AuthParseResponse") {
122        "Handled" => handled: bool,
123        "Auth" => auth: AuthData,
124        "Auths" => auths: Vec<AuthData>,
125    }
126}
127
128go_struct! {
129    pub struct AuthLoginStartRequest("pluginapi.AuthLoginStartRequest") {
130        "Provider" => provider: String,
131        "BaseURL" => base_url: String,
132        "Host" => host: HostConfigSummary,
133        "Metadata" => metadata: Metadata,
134    }
135}
136
137go_struct! {
138    pub struct AuthLoginStartResponse("pluginapi.AuthLoginStartResponse") {
139        "Provider" => provider: String,
140        "URL" => url: String,
141        "State" => state: String,
142        "ExpiresAt" => expires_at: GoTime,
143        "Metadata" => metadata: Metadata,
144    }
145}
146
147go_struct! {
148    pub struct AuthLoginPollRequest("pluginapi.AuthLoginPollRequest") {
149        "Provider" => provider: String,
150        "State" => state: String,
151        "Host" => host: HostConfigSummary,
152        "Metadata" => metadata: Metadata,
153    }
154}
155
156pub const AUTH_LOGIN_PENDING: &str = "pending";
157pub const AUTH_LOGIN_SUCCESS: &str = "success";
158pub const AUTH_LOGIN_ERROR: &str = "error";
159
160go_struct! {
161    pub struct AuthLoginPollResponse("pluginapi.AuthLoginPollResponse") {
162        "Status" => status: String,
163        "Message" => message: String,
164        "Auth" => auth: AuthData,
165        "Auths" => auths: Vec<AuthData>,
166    }
167}
168
169go_struct! {
170    pub struct AuthRefreshRequest("pluginapi.AuthRefreshRequest") {
171        "AuthID" => auth_id: String,
172        "AuthProvider" => auth_provider: String,
173        "StorageJSON" => storage_json: Bytes,
174        "Metadata" => metadata: Metadata,
175        "Attributes" => attributes: StringMap,
176        "Host" => host: HostConfigSummary,
177    }
178}
179
180go_struct! {
181    pub struct AuthRefreshResponse("pluginapi.AuthRefreshResponse") {
182        "Auth" => auth: AuthData,
183        "NextRefreshAfter" => next_refresh_after: GoTime,
184    }
185}
186
187go_struct! {
188    pub struct ModelRegistrationRequest("pluginapi.ModelRegistrationRequest") {
189        "Plugin" => plugin: PluginMetadata,
190    }
191}
192
193go_struct! {
194    pub struct ModelRegistrationResponse("pluginapi.ModelRegistrationResponse") {
195        "Provider" => provider: String,
196        "Models" => models: Vec<ModelInfo>,
197    }
198}
199
200go_struct! {
201    pub struct StaticModelRequest("pluginapi.StaticModelRequest") {
202        "Plugin" => plugin: PluginMetadata,
203        "Host" => host: HostConfigSummary,
204    }
205}
206
207go_struct! {
208    pub struct AuthModelRequest("pluginapi.AuthModelRequest") {
209        "Plugin" => plugin: PluginMetadata,
210        "AuthID" => auth_id: String,
211        "AuthProvider" => auth_provider: String,
212        "StorageJSON" => storage_json: Bytes,
213        "Metadata" => metadata: Metadata,
214        "Attributes" => attributes: StringMap,
215        "Host" => host: HostConfigSummary,
216    }
217}
218
219go_struct! {
220    pub struct ModelResponse("pluginapi.ModelResponse") {
221        "Provider" => provider: String,
222        "Models" => models: Vec<ModelInfo>,
223        "AuthUpdate" => auth_update: AuthData,
224    }
225}
226
227go_struct! {
228    pub struct FrontendAuthRequest("pluginapi.FrontendAuthRequest") {
229        "Method" => method: String,
230        "Path" => path: String,
231        "Headers" => headers: Header,
232        "Query" => query: Header,
233        /// Read with `io.ReadAll`, so never nil.
234        "Body" => body: NonNilBytes,
235    }
236}
237
238go_struct! {
239    pub struct FrontendAuthResponse("pluginapi.FrontendAuthResponse") {
240        "Authenticated" => authenticated: bool,
241        "Principal" => principal: String,
242        "Metadata" => metadata: StringMap,
243    }
244}
245
246pub const SCHEDULER_BUILTIN_ROUND_ROBIN: &str = "round-robin";
247pub const SCHEDULER_BUILTIN_FILL_FIRST: &str = "fill-first";
248
249go_struct! {
250    pub struct SchedulerOptions("pluginapi.SchedulerOptions") {
251        "Headers" => headers: Header,
252        "Metadata" => metadata: Metadata,
253    }
254}
255
256go_struct! {
257    pub struct SchedulerAuthCandidate("pluginapi.SchedulerAuthCandidate") {
258        "ID" => id: String,
259        "Provider" => provider: String,
260        "Priority" => priority: i64,
261        "Status" => status: String,
262        "Attributes" => attributes: StringMap,
263        "Metadata" => metadata: Metadata,
264    }
265}
266
267go_struct! {
268    pub struct SchedulerPickRequest("pluginapi.SchedulerPickRequest") {
269        "Plugin" => plugin: PluginMetadata,
270        "Provider" => provider: String,
271        "Providers" => providers: Vec<String>,
272        "Model" => model: String,
273        "Stream" => stream: bool,
274        "Options" => options: SchedulerOptions,
275        "Candidates" => candidates: Vec<SchedulerAuthCandidate>,
276    }
277}
278
279/// `pluginapi.SchedulerPickResponse`. Its custom `UnmarshalJSON` accepts the Go names
280/// and snake_case alternatives; a present Go name wins.
281#[derive(Debug, Clone, Default, PartialEq, Eq)]
282pub struct SchedulerPickResponse {
283    pub auth_id: String,
284    pub delegate_builtin: String,
285    pub handled: bool,
286    pub reject: bool,
287    pub reject_reason: String,
288    pub reject_code: String,
289}
290
291go_struct! {
292    pub struct SchedulerPickRaw("pluginapi.rawResponse") {
293        "AuthID" => auth_id: Option<String>,
294        "auth_id" => alt_auth_id: Option<String>,
295        "DelegateBuiltin" => delegate: Option<String>,
296        "delegate_builtin" => alt_delegate: Option<String>,
297        "Handled" => handled: Option<bool>,
298        "handled" => alt_handled: Option<bool>,
299        "Reject" => reject: Option<bool>,
300        "reject" => alt_reject: Option<bool>,
301        "RejectReason" => reject_reason: Option<String>,
302        "reject_reason" => alt_reject_reason: Option<String>,
303        "RejectCode" => reject_code: Option<String>,
304        "reject_code" => alt_reject_code: Option<String>,
305    }
306}
307
308impl GoJson for SchedulerPickResponse {
309    const GO_TYPE: &'static str = "pluginapi.SchedulerPickResponse";
310    fn encode(&self, out: &mut Vec<u8>) {
311        let mut w = crate::gojson::ObjWriter::begin(out);
312        w.field("AuthID", &self.auth_id, false);
313        w.field("DelegateBuiltin", &self.delegate_builtin, false);
314        w.field("Handled", &self.handled, false);
315        w.field("Reject", &self.reject, false);
316        w.field("RejectReason", &self.reject_reason, false);
317        w.field("RejectCode", &self.reject_code, false);
318        w.end();
319    }
320    fn decode_value(v: &crate::gojson::Node) -> Result<Self, crate::gojson::DecodeError> {
321        let raw: SchedulerPickRaw = crate::gojson::decode_struct(v)?;
322        Ok(Self {
323            auth_id: raw.auth_id.or(raw.alt_auth_id).unwrap_or_default(),
324            delegate_builtin: raw.delegate.or(raw.alt_delegate).unwrap_or_default(),
325            handled: raw.handled.or(raw.alt_handled).unwrap_or_default(),
326            reject: raw.reject.or(raw.alt_reject).unwrap_or_default(),
327            reject_reason: raw.reject_reason.or(raw.alt_reject_reason).unwrap_or_default(),
328            reject_code: raw.reject_code.or(raw.alt_reject_code).unwrap_or_default(),
329        })
330    }
331    fn is_empty(&self) -> bool {
332        false
333    }
334}
335
336go_struct! {
337    pub struct ModelRouteRequest("pluginapi.ModelRouteRequest") {
338        "Plugin" => plugin: PluginMetadata,
339        "PluginID" => plugin_id: String,
340        "SourceFormat" => source_format: String,
341        "RequestedModel" => requested_model: String,
342        "Stream" => stream: bool,
343        "Headers" => headers: Header,
344        "Query" => query: Header,
345        "Body" => body: Bytes,
346        "Metadata" => metadata: Metadata,
347        "AvailableProviders" => available_providers: Vec<String>,
348    }
349}
350
351pub const ROUTE_TARGET_SELF: &str = "self";
352pub const ROUTE_TARGET_EXECUTOR: &str = "executor";
353pub const ROUTE_TARGET_PROVIDER: &str = "provider";
354
355go_struct! {
356    pub struct ModelRouteResponse("pluginapi.ModelRouteResponse") {
357        "Handled" => handled: bool,
358        "TargetKind" => target_kind: String,
359        "Target" => target: String,
360        "TargetModel" => target_model: String,
361        "Reason" => reason: String,
362    }
363}
364
365go_struct! {
366    pub struct HostModelExecutionRequest("pluginapi.HostModelExecutionRequest") {
367        "entry_protocol" => entry_protocol: String,
368        "exit_protocol" => exit_protocol: String,
369        "model" => model: String,
370        "stream" => stream: bool,
371        "body" => body: Bytes,
372        "headers" => headers: Header,
373        "query" => query: Header,
374        "alt" => alt: String,
375        "forced_provider" omitempty => forced_provider: String,
376        "auth_id" omitempty => auth_id: String,
377        "proxy_url" omitempty => proxy_url: String,
378        "path" omitempty => path: String,
379    }
380}
381
382go_struct! {
383    pub struct HostModelExecutionResponse("pluginapi.HostModelExecutionResponse") {
384        "status_code" => status_code: i64,
385        "headers" => headers: Header,
386        "body" => body: Bytes,
387    }
388}
389
390go_struct! {
391    pub struct HostModelStreamResponse("pluginapi.HostModelStreamResponse") {
392        "status_code" => status_code: i64,
393        "headers" => headers: Header,
394        "stream_id" => stream_id: String,
395    }
396}
397
398go_struct! {
399    pub struct HostModelStreamReadRequest("pluginapi.HostModelStreamReadRequest") {
400        "stream_id" => stream_id: String,
401    }
402}
403
404go_struct! {
405    pub struct HostModelStreamReadResponse("pluginapi.HostModelStreamReadResponse") {
406        "payload" => payload: Bytes,
407        "error" => error: String,
408        "done" => done: bool,
409    }
410}
411
412go_struct! {
413    pub struct HostModelStreamCloseRequest("pluginapi.HostModelStreamCloseRequest") {
414        "stream_id" => stream_id: String,
415    }
416}
417
418go_struct! {
419    pub struct HostRecentRequestEntry("pluginapi.HostRecentRequestEntry") {
420        "time" => time: String,
421        "success" => success: i64,
422        "failed" => failed: i64,
423    }
424}
425
426go_struct! {
427    pub struct HostAuthFileEntry("pluginapi.HostAuthFileEntry") {
428        "id" omitempty => id: String,
429        "auth_index" omitempty => auth_index: String,
430        "name" => name: String,
431        "type" omitempty => auth_type: String,
432        "provider" omitempty => provider: String,
433        "label" omitempty => label: String,
434        "status" omitempty => status: String,
435        "status_message" omitempty => status_message: String,
436        "disabled" omitempty => disabled: bool,
437        "unavailable" omitempty => unavailable: bool,
438        "runtime_only" omitempty => runtime_only: bool,
439        "source" omitempty => source: String,
440        "path" omitempty => path: String,
441        "size" omitempty => size: i64,
442        "modtime" omitempty => mod_time: GoTime,
443        "updated_at" omitempty => updated_at: GoTime,
444        "created_at" omitempty => created_at: GoTime,
445        "last_refresh" omitempty => last_refresh: GoTime,
446        "next_retry_after" omitempty => next_retry_after: GoTime,
447        "email" omitempty => email: String,
448        "project_id" omitempty => project_id: String,
449        "account_type" omitempty => account_type: String,
450        "account" omitempty => account: String,
451        "priority" omitempty => priority: i64,
452        "note" omitempty => note: String,
453        "base_url" omitempty => base_url: String,
454        "websockets" omitempty => websockets: bool,
455        "success" omitempty => success: i64,
456        "failed" omitempty => failed: i64,
457        "recent_requests" omitempty => recent_requests: Vec<HostRecentRequestEntry>,
458    }
459}
460
461go_struct! {
462    pub struct HostAuthGetRequest("pluginapi.HostAuthGetRequest") {
463        "auth_index" => auth_index: String,
464    }
465}
466
467go_struct! {
468    pub struct HostAuthGetResponse("pluginapi.HostAuthGetResponse") {
469        "auth_index" => auth_index: String,
470        "name" omitempty => name: String,
471        "path" omitempty => path: String,
472        "json" => json: RawJson,
473    }
474}
475
476go_struct! {
477    pub struct HostAuthGetRuntimeResponse("pluginapi.HostAuthGetRuntimeResponse") {
478        "auth" => auth: HostAuthFileEntry,
479    }
480}
481
482go_struct! {
483    pub struct HostAuthSaveRequest("pluginapi.HostAuthSaveRequest") {
484        "name" => name: String,
485        "json" => json: RawJson,
486    }
487}
488
489go_struct! {
490    pub struct HostAuthSaveResponse("pluginapi.HostAuthSaveResponse") {
491        "name" => name: String,
492        "path" => path: String,
493    }
494}
495
496pub const AFFINITY_BOUND: &str = "bound";
497pub const AFFINITY_UNBOUND: &str = "unbound";
498pub const AFFINITY_AMBIGUOUS: &str = "ambiguous";
499pub const AFFINITY_UNSUPPORTED: &str = "unsupported";
500
501go_struct! {
502    pub struct HostAffinityLookupRequest("pluginapi.HostAffinityLookupRequest") {
503        "provider" => provider: String,
504        "model" => model: String,
505        "session_id" => session_id: String,
506    }
507}
508
509go_struct! {
510    pub struct HostAffinityLookupResponse("pluginapi.HostAffinityLookupResponse") {
511        "status" => status: String,
512        "auth_index" omitempty => auth_index: String,
513        "observed_at" omitempty => observed_at: GoTime,
514        "disabled" omitempty => disabled: bool,
515        "unavailable" omitempty => unavailable: bool,
516    }
517}
518
519go_struct! {
520    pub struct HttpWireProfile("pluginapi.HTTPWireProfile") {
521        "http1_only" omitempty => http1_only: bool,
522        "disable_auto_compression" omitempty => disable_auto_compression: bool,
523        "header_profile" omitempty => header_profile: Vec<String>,
524    }
525}
526
527go_struct! {
528    pub struct HttpRequest("pluginapi.HTTPRequest") {
529        "Method" => method: String,
530        "URL" => url: String,
531        "Headers" => headers: Header,
532        "Body" => body: Bytes,
533        "wire_profile" omitempty => wire_profile: Option<HttpWireProfile>,
534    }
535}
536
537go_struct! {
538    pub struct HttpResponse("pluginapi.HTTPResponse") {
539        "StatusCode" => status_code: i64,
540        "Headers" => headers: Header,
541        "Body" => body: Bytes,
542    }
543}
544
545go_struct! {
546    /// `pluginapi.HTTPStreamChunk`. `Err` is a Go `error` interface: it encodes as `{}`
547    /// or `null` and never decodes back, so only the payload crosses the wire.
548    pub struct HttpStreamChunk("pluginapi.HTTPStreamChunk") {
549        "Payload" => payload: Bytes,
550    }
551}
552
553go_struct! {
554    pub struct ExecutorHttpRequest("pluginapi.ExecutorHTTPRequest") {
555        "AuthID" => auth_id: String,
556        "AuthProvider" => auth_provider: String,
557        "Method" => method: String,
558        "URL" => url: String,
559        "Headers" => headers: Header,
560        "Body" => body: Bytes,
561        "StorageJSON" => storage_json: Bytes,
562        "Metadata" => metadata: Metadata,
563        "Attributes" => attributes: StringMap,
564    }
565}
566
567go_struct! {
568    pub struct ExecutorHttpResponse("pluginapi.ExecutorHTTPResponse") {
569        "StatusCode" => status_code: i64,
570        "Headers" => headers: Header,
571        "Body" => body: Bytes,
572    }
573}
574
575go_struct! {
576    pub struct ExecutorRequest("pluginapi.ExecutorRequest") {
577        "AuthID" => auth_id: String,
578        "AuthProvider" => auth_provider: String,
579        "Model" => model: String,
580        "Format" => format: String,
581        "Stream" => stream: bool,
582        "Alt" => alt: String,
583        "Headers" => headers: Header,
584        "Query" => query: Header,
585        "OriginalRequest" => original_request: Bytes,
586        "SourceFormat" => source_format: String,
587        "Payload" => payload: Bytes,
588        "Metadata" => metadata: Metadata,
589        "StorageJSON" => storage_json: Bytes,
590        "AuthMetadata" => auth_metadata: Metadata,
591        "AuthAttributes" => auth_attributes: StringMap,
592    }
593}
594
595go_struct! {
596    pub struct ExecutorResponse("pluginapi.ExecutorResponse") {
597        "Payload" => payload: Bytes,
598        "Headers" => headers: Header,
599        "Metadata" => metadata: Metadata,
600    }
601}
602
603go_struct! {
604    /// `pluginapi.ExecutorStreamChunk`; see [`HttpStreamChunk`] for `Err`.
605    pub struct ExecutorStreamChunk("pluginapi.ExecutorStreamChunk") {
606        "Payload" => payload: Bytes,
607    }
608}
609
610go_struct! {
611    pub struct RequestTransformRequest("pluginapi.RequestTransformRequest") {
612        "FromFormat" => from_format: String,
613        "ToFormat" => to_format: String,
614        "Model" => model: String,
615        "Stream" => stream: bool,
616        "Body" => body: Bytes,
617    }
618}
619
620go_struct! {
621    pub struct ResponseTransformRequest("pluginapi.ResponseTransformRequest") {
622        "FromFormat" => from_format: String,
623        "ToFormat" => to_format: String,
624        "Model" => model: String,
625        "Stream" => stream: bool,
626        "OriginalRequest" => original_request: Bytes,
627        "TranslatedRequest" => translated_request: Bytes,
628        "Body" => body: Bytes,
629    }
630}
631
632go_struct! {
633    pub struct RequestInterceptRequest("pluginapi.RequestInterceptRequest") {
634        "RequestID" => request_id: String,
635        "TraceID" => trace_id: String,
636        "SourceFormat" => source_format: String,
637        "ToFormat" => to_format: String,
638        "Model" => model: String,
639        "RequestedModel" => requested_model: String,
640        "Stream" => stream: bool,
641        "Headers" => headers: Header,
642        "Body" => body: Bytes,
643        "Metadata" => metadata: Metadata,
644    }
645}
646
647go_struct! {
648    pub struct RequestInterceptResponse("pluginapi.RequestInterceptResponse") {
649        "path" omitempty => path: String,
650        "Headers" => headers: Header,
651        "Body" => body: Bytes,
652        "ClearHeaders" => clear_headers: Vec<String>,
653        "Terminate" => terminate: bool,
654        "StatusCode" => status_code: i64,
655        "ResponseHeaders" => response_headers: Header,
656        "ResponseBody" => response_body: Bytes,
657    }
658}
659
660pub const COMPLETION_SUCCEEDED: &str = "succeeded";
661pub const COMPLETION_FAILED: &str = "failed";
662pub const COMPLETION_REJECTED: &str = "rejected";
663pub const COMPLETION_CANCELED: &str = "canceled";
664
665go_struct! {
666    pub struct RequestCompletion("pluginapi.RequestCompletion") {
667        "RequestID" => request_id: String,
668        "TraceID" => trace_id: String,
669        "SourceFormat" => source_format: String,
670        "Model" => model: String,
671        "RequestedModel" => requested_model: String,
672        "Stream" => stream: bool,
673        "Outcome" => outcome: String,
674        "StatusCode" => status_code: i64,
675        "Error" => error: String,
676        "StartedAt" => started_at: GoTime,
677        "CompletedAt" => completed_at: GoTime,
678        "Metadata" => metadata: Metadata,
679    }
680}
681
682go_struct! {
683    pub struct ResponseInterceptRequest("pluginapi.ResponseInterceptRequest") {
684        "RequestID" => request_id: String,
685        "SourceFormat" => source_format: String,
686        "Model" => model: String,
687        "RequestedModel" => requested_model: String,
688        "Stream" => stream: bool,
689        "RequestHeaders" => request_headers: Header,
690        "ResponseHeaders" => response_headers: Header,
691        "OriginalRequest" => original_request: Bytes,
692        "RequestBody" => request_body: Bytes,
693        "Body" => body: Bytes,
694        "StatusCode" => status_code: i64,
695        "Metadata" => metadata: Metadata,
696    }
697}
698
699go_struct! {
700    pub struct ResponseInterceptResponse("pluginapi.ResponseInterceptResponse") {
701        "Headers" => headers: Header,
702        "Body" => body: Bytes,
703        "ClearHeaders" => clear_headers: Vec<String>,
704    }
705}
706
707/// `pluginapi.StreamChunkHeaderInitIndex`.
708pub const STREAM_CHUNK_HEADER_INIT_INDEX: i64 = -1;
709
710go_struct! {
711    pub struct StreamChunkInterceptRequest("pluginapi.StreamChunkInterceptRequest") {
712        "RequestID" => request_id: String,
713        "SourceFormat" => source_format: String,
714        "Model" => model: String,
715        "RequestedModel" => requested_model: String,
716        "RequestHeaders" => request_headers: Header,
717        "ResponseHeaders" => response_headers: Header,
718        "OriginalRequest" => original_request: Bytes,
719        "RequestBody" => request_body: Bytes,
720        "Body" => body: Bytes,
721        "HistoryChunks" => history_chunks: Vec<Bytes>,
722        "ChunkIndex" => chunk_index: i64,
723        "Metadata" => metadata: Metadata,
724    }
725}
726
727go_struct! {
728    pub struct StreamChunkInterceptResponse("pluginapi.StreamChunkInterceptResponse") {
729        "Headers" => headers: Header,
730        "Body" => body: Bytes,
731        "ClearHeaders" => clear_headers: Vec<String>,
732        "DropChunk" => drop_chunk: bool,
733    }
734}
735
736go_struct! {
737    pub struct WebSocketResponseEvent("pluginapi.WebSocketResponseEvent") {
738        "RequestID" => request_id: String,
739        "TraceID" => trace_id: String,
740        "SourceFormat" => source_format: String,
741        "Model" => model: String,
742        "RequestedModel" => requested_model: String,
743        "Provider" => provider: String,
744        "AuthID" => auth_id: String,
745        "AuthLabel" => auth_label: String,
746        "AuthType" => auth_type: String,
747        "EventType" => event_type: String,
748        "Payload" => payload: Bytes,
749        "Metadata" => metadata: Metadata,
750    }
751}
752
753go_struct! {
754    pub struct PayloadResponse("pluginapi.PayloadResponse") {
755        "Body" => body: Bytes,
756    }
757}
758
759go_struct! {
760    pub struct ThinkingConfig("pluginapi.ThinkingConfig") {
761        "Mode" => mode: String,
762        "Budget" => budget: i64,
763        "Level" => level: String,
764    }
765}
766
767go_struct! {
768    pub struct ThinkingApplyRequest("pluginapi.ThinkingApplyRequest") {
769        "Provider" => provider: String,
770        "Model" => model: ModelInfo,
771        "Config" => config: ThinkingConfig,
772        "Body" => body: Bytes,
773    }
774}
775
776go_struct! {
777    pub struct CommandLineRegistrationRequest("pluginapi.CommandLineRegistrationRequest") {
778        "Plugin" => plugin: PluginMetadata,
779    }
780}
781
782go_struct! {
783    pub struct CommandLineFlag("pluginapi.CommandLineFlag") {
784        "Name" => name: String,
785        "Usage" => usage: String,
786        "Type" => flag_type: String,
787        "DefaultValue" => default_value: String,
788    }
789}
790
791go_struct! {
792    pub struct CommandLineRegistrationResponse("pluginapi.CommandLineRegistrationResponse") {
793        "Flags" => flags: Vec<CommandLineFlag>,
794    }
795}
796
797go_struct! {
798    pub struct CommandLineFlagValue("pluginapi.CommandLineFlagValue") {
799        "Name" => name: String,
800        "Type" => flag_type: String,
801        "Value" => value: String,
802        "Set" => set: bool,
803    }
804}
805
806go_struct! {
807    pub struct CommandLineExecutionRequest("pluginapi.CommandLineExecutionRequest") {
808        "Plugin" => plugin: PluginMetadata,
809        "Program" => program: String,
810        "Args" => args: Vec<String>,
811        "ConfigPath" => config_path: String,
812        "Host" => host: HostConfigSummary,
813        "Flags" => flags: BTreeMap<String, CommandLineFlagValue>,
814        "TriggeredFlags" => triggered_flags: BTreeMap<String, CommandLineFlagValue>,
815    }
816}
817
818go_struct! {
819    pub struct CommandLineExecutionResponse("pluginapi.CommandLineExecutionResponse") {
820        "Stdout" => stdout: Bytes,
821        "Stderr" => stderr: Bytes,
822        "Auths" => auths: Vec<AuthData>,
823        "ExitCode" => exit_code: i64,
824    }
825}
826
827go_struct! {
828    pub struct ManagementRegistrationRequest("pluginapi.ManagementRegistrationRequest") {
829        "Plugin" => plugin: PluginMetadata,
830        "BasePath" => base_path: String,
831        "ResourceBasePath" => resource_base_path: String,
832    }
833}
834
835go_struct! {
836    /// `pluginapi.ManagementRoute` without its host-side `Handler`.
837    pub struct ManagementRoute("pluginapi.ManagementRoute") {
838        "Method" => method: String,
839        "Path" => path: String,
840        "Menu" => menu: String,
841        "Description" => description: String,
842    }
843}
844
845go_struct! {
846    /// `pluginapi.ResourceRoute` without its host-side `Handler`.
847    pub struct ResourceRoute("pluginapi.ResourceRoute") {
848        "Path" => path: String,
849        "Menu" => menu: String,
850        "Description" => description: String,
851    }
852}
853
854go_struct! {
855    /// The `management.register` result (`rpcManagementRegistrationResponse`).
856    pub struct ManagementRegistrationResponse("pluginhost.rpcManagementRegistrationResponse") {
857        "routes" omitempty => routes: Vec<ManagementRoute>,
858        "resources" omitempty => resources: Vec<ResourceRoute>,
859    }
860}
861
862go_struct! {
863    pub struct ManagementRequest("pluginapi.ManagementRequest") {
864        "Method" => method: String,
865        "Path" => path: String,
866        "Headers" => headers: Header,
867        "Query" => query: Header,
868        "Body" => body: Bytes,
869    }
870}
871
872go_struct! {
873    pub struct ManagementResponse("pluginapi.ManagementResponse") {
874        "StatusCode" => status_code: i64,
875        "Headers" => headers: Header,
876        "Body" => body: Bytes,
877    }
878}
879
880go_struct! {
881    pub struct UsageFailure("pluginapi.UsageFailure") {
882        "StatusCode" => status_code: i64,
883        "Body" => body: String,
884    }
885}
886
887go_struct! {
888    pub struct UsageDetail("pluginapi.UsageDetail") {
889        "InputTokens" => input_tokens: i64,
890        "OutputTokens" => output_tokens: i64,
891        "ReasoningTokens" => reasoning_tokens: i64,
892        "CachedTokens" => cached_tokens: i64,
893        "CacheReadTokens" => cache_read_tokens: i64,
894        "CacheCreationTokens" => cache_creation_tokens: i64,
895        "TotalTokens" => total_tokens: i64,
896    }
897}
898
899go_struct! {
900    pub struct UsageRecord("pluginapi.UsageRecord") {
901        "RequestID" => request_id: String,
902        "TraceID" => trace_id: String,
903        "Provider" => provider: String,
904        "BaseURL" => base_url: String,
905        "ExecutorType" => executor_type: String,
906        "Model" => model: String,
907        "Alias" => alias: String,
908        "APIKey" => api_key: String,
909        "IsNativeKey" => is_native_key: bool,
910        "AccessProvider" => access_provider: String,
911        "SessionID" => session_id: String,
912        "ParentSessionID" => parent_session_id: String,
913        "AuthID" => auth_id: String,
914        "AuthIndex" => auth_index: String,
915        "AuthType" => auth_type: String,
916        "Source" => source: String,
917        "ReasoningEffort" => reasoning_effort: String,
918        "ServiceTier" => service_tier: String,
919        "ResponseServiceTier" => response_service_tier: String,
920        "ResponseModel" => response_model: String,
921        "Generate" => generate: bool,
922        "Stream" => stream: bool,
923        "RequestedAt" => requested_at: GoTime,
924        /// `time.Duration` in nanoseconds.
925        "Latency" => latency_ns: i64,
926        /// `time.Duration` in nanoseconds.
927        "TTFT" => ttft_ns: i64,
928        "Failed" => failed: bool,
929        "Failure" => failure: UsageFailure,
930        "Detail" => detail: UsageDetail,
931        "ResponseHeaders" => response_headers: Header,
932    }
933}
934
935go_struct! {
936    pub struct QuotaDescribeRequest("pluginapi.QuotaDescribeRequest") {
937        "plugin" omitempty => plugin: PluginMetadata,
938    }
939}
940
941go_struct! {
942    pub struct QuotaDescribeResponse("pluginapi.QuotaDescribeResponse") {
943        "supported_providers" omitempty => supported_providers: Vec<String>,
944        "display_name" omitempty => display_name: String,
945        "supports_reset" omitempty => supports_reset: bool,
946    }
947}
948
949go_struct! {
950    pub struct QuotaFetchRequest("pluginapi.QuotaFetchRequest") {
951        "auth_index" => auth_index: String,
952        "auth_id" => auth_id: String,
953        "provider" => provider: String,
954        "storage_json" omitempty => storage_json: Bytes,
955        "metadata" omitempty => metadata: Metadata,
956        "attributes" omitempty => attributes: StringMap,
957        "host" omitempty => host: HostConfigSummary,
958    }
959}
960
961go_struct! {
962    pub struct QuotaResetRequest("pluginapi.QuotaResetRequest") {
963        "auth_index" => auth_index: String,
964        "auth_id" => auth_id: String,
965        "provider" => provider: String,
966        "storage_json" omitempty => storage_json: Bytes,
967        "metadata" omitempty => metadata: Metadata,
968        "attributes" omitempty => attributes: StringMap,
969        "host" omitempty => host: HostConfigSummary,
970    }
971}
972
973go_struct! {
974    pub struct QuotaResetResponse("pluginapi.QuotaResetResponse") {
975        "success" => success: bool,
976        "message" omitempty => message: String,
977    }
978}
979
980go_struct! {
981    pub struct QuotaMetric("pluginapi.QuotaMetric") {
982        "key" => key: String,
983        "label" => label: String,
984        "value" => value: f64,
985        "unit" omitempty => unit: String,
986        "format" omitempty => format: String,
987        "currency" omitempty => currency: String,
988    }
989}
990
991// Quota responses carry custom `UnmarshalJSON` methods that also accept snake_case keys.
992// Go keeps the camelCase value unless it is the zero value and the snake_case one is not.
993
994fn alt<T: PartialEq + Default>(camel: T, snake: Option<T>) -> T {
995    match snake {
996        Some(snake) if camel == T::default() && snake != T::default() => snake,
997        _ => camel,
998    }
999}
1000
1001go_struct! {
1002    pub struct QuotaSubscription("pluginapi.QuotaSubscription") {
1003        "plan" omitempty => plan: String,
1004        "tierName" omitempty => tier_name: String,
1005        "tierId" omitempty => tier_id: String,
1006    }
1007}
1008
1009go_struct! {
1010    pub struct QuotaSubscriptionAlt("pluginapi.QuotaSubscription") {
1011        "tier_name" => tier_name: Option<String>,
1012        "tier_id" => tier_id: Option<String>,
1013    }
1014}
1015
1016go_struct! {
1017    pub struct QuotaBucket("pluginapi.QuotaBucket") {
1018        "window" omitempty => window: String,
1019        "remainingFraction" => remaining_fraction: f64,
1020        "resetTime" omitempty => reset_time: String,
1021        "description" omitempty => description: String,
1022    }
1023}
1024
1025go_struct! {
1026    pub struct QuotaBucketAlt("pluginapi.QuotaBucket") {
1027        "remainingFraction" => remaining_fraction: Option<f64>,
1028        "remaining_fraction" => alt_remaining_fraction: Option<f64>,
1029        "reset_time" => reset_time: Option<String>,
1030    }
1031}
1032
1033go_struct! {
1034    pub struct QuotaGroup("pluginapi.QuotaGroup") {
1035        "displayName" omitempty => display_name: String,
1036        "buckets" omitempty => buckets: Vec<QuotaBucket>,
1037    }
1038}
1039
1040go_struct! {
1041    pub struct QuotaGroupAlt("pluginapi.QuotaGroup") {
1042        "display_name" => display_name: Option<String>,
1043    }
1044}
1045
1046go_struct! {
1047    pub struct QuotaFetchResponse("pluginapi.QuotaFetchResponse") {
1048        "subscription" omitempty => subscription: Option<QuotaSubscription>,
1049        "summary" omitempty => summary: Vec<QuotaMetric>,
1050        "serverTimeOffsetMs" omitempty => server_time_offset_ms: i64,
1051        "groups" omitempty => groups: Vec<QuotaGroup>,
1052    }
1053}
1054
1055go_struct! {
1056    pub struct QuotaFetchResponseAlt("pluginapi.QuotaFetchResponse") {
1057        "server_time_offset_ms" => server_time_offset_ms: Option<i64>,
1058    }
1059}
1060
1061/// Applies the snake_case fallbacks of the quota `UnmarshalJSON` methods to a decoded
1062/// `quota.fetch` result. `raw` is the result object the plugin returned.
1063pub fn quota_fetch_from_value(raw: &Node) -> Result<QuotaFetchResponse, crate::gojson::DecodeError> {
1064    let mut out = QuotaFetchResponse::decode(raw)?;
1065    let top: QuotaFetchResponseAlt = crate::gojson::decode_struct(raw)?;
1066    out.server_time_offset_ms = alt(out.server_time_offset_ms, top.server_time_offset_ms);
1067    if let (Some(sub), Some(raw_sub)) = (out.subscription.as_mut(), raw.member("subscription")) {
1068        let a: QuotaSubscriptionAlt = crate::gojson::decode_struct(raw_sub)?;
1069        sub.tier_name = alt(std::mem::take(&mut sub.tier_name), a.tier_name);
1070        sub.tier_id = alt(std::mem::take(&mut sub.tier_id), a.tier_id);
1071    }
1072    if let Some(Node::Array(groups)) = raw.member("groups") {
1073        for (group, raw_group) in out.groups.iter_mut().zip(groups.iter()) {
1074            let a: QuotaGroupAlt = crate::gojson::decode_struct(raw_group)?;
1075            group.display_name = alt(std::mem::take(&mut group.display_name), a.display_name);
1076            if let Some(Node::Array(buckets)) = raw_group.member("buckets") {
1077                for (bucket, raw_bucket) in group.buckets.iter_mut().zip(buckets.iter()) {
1078                    let a: QuotaBucketAlt = crate::gojson::decode_struct(raw_bucket)?;
1079                    // A present camelCase pointer wins even when zero.
1080                    bucket.remaining_fraction = a.remaining_fraction.or(a.alt_remaining_fraction).unwrap_or_default();
1081                    bucket.reset_time = alt(std::mem::take(&mut bucket.reset_time), a.reset_time);
1082                }
1083            }
1084        }
1085    }
1086    Ok(out)
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092    use crate::gojson::{from_slice, to_vec};
1093
1094    #[test]
1095    fn scheduler_pick_accepts_both_spellings() {
1096        let r: SchedulerPickResponse =
1097            from_slice(br#"{"auth_id":"snake","AuthID":"go","handled":true,"reject_code":"x"}"#).unwrap();
1098        assert_eq!(r.auth_id, "go");
1099        assert!(r.handled);
1100        assert_eq!(r.reject_code, "x");
1101    }
1102
1103    #[test]
1104    fn quota_fetch_accepts_snake_case() {
1105        let raw = crate::gojson::parse(
1106            br#"{"subscription": {"tier_name": "Pro", "tierId": "t1"}, "server_time_offset_ms": 5,
1107            "groups": [{"display_name": "G", "buckets": [{"remaining_fraction": 0.25, "reset_time": "soon"},
1108            {"remainingFraction": 0, "remaining_fraction": 0.5}]}]}"#,
1109        )
1110        .unwrap();
1111        let r = quota_fetch_from_value(&raw).unwrap();
1112        assert_eq!(r.server_time_offset_ms, 5);
1113        let sub = r.subscription.unwrap();
1114        assert_eq!((sub.tier_name.as_str(), sub.tier_id.as_str()), ("Pro", "t1"));
1115        assert_eq!(r.groups[0].display_name, "G");
1116        assert_eq!(r.groups[0].buckets[0].remaining_fraction, 0.25);
1117        assert_eq!(r.groups[0].buckets[0].reset_time, "soon");
1118        assert_eq!(
1119            r.groups[0].buckets[1].remaining_fraction, 0.0,
1120            "a present camelCase pointer wins"
1121        );
1122    }
1123
1124    #[test]
1125    fn model_info_round_trips_go_field_names() {
1126        let m = ModelInfo {
1127            id: "m".into(),
1128            thinking: Some(ThinkingSupport {
1129                levels: vec!["low".into()],
1130                ..Default::default()
1131            }),
1132            ..Default::default()
1133        };
1134        let raw = to_vec(&m);
1135        assert!(raw.starts_with(br#"{"ID":"m","Object":"","Created":0,"#));
1136        assert_eq!(from_slice::<ModelInfo>(&raw).unwrap(), m);
1137    }
1138
1139    /// Go TestPluginThinkingSupportDisableTypeJSONCompatibility: `DisableType` sits
1140    /// between `DynamicAllowed` and `Levels`, and an older plugin's payload without it
1141    /// still decodes.
1142    #[test]
1143    fn thinking_support_carries_disable_type() {
1144        let t = ThinkingSupport {
1145            levels: vec!["low".into()],
1146            disable_type: "between_tools".into(),
1147            ..Default::default()
1148        };
1149        let raw = to_vec(&t);
1150        assert_eq!(
1151            raw,
1152            br#"{"Min":0,"Max":0,"ZeroAllowed":false,"DynamicAllowed":false,"DisableType":"between_tools","Levels":["low"]}"#
1153        );
1154        assert_eq!(from_slice::<ThinkingSupport>(&raw).unwrap(), t);
1155        let old = from_slice::<ThinkingSupport>(br#"{"Levels":["low"],"ZeroAllowed":true}"#).unwrap();
1156        assert_eq!((old.disable_type.as_str(), old.zero_allowed), ("", true));
1157    }
1158}