gemini-cli-sdk 0.1.0

Rust SDK wrapping Google's Gemini CLI as a subprocess via JSON-RPC 2.0
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
//! Method name constants and request/response structs for every Gemini CLI
//! JSON-RPC method.
//!
//! Only methods that Gemini CLI actually implements are included here.
//! All structs derive `Default` where the empty form is semantically meaningful,
//! and use `#[serde(flatten)]` to tolerate unknown fields for forward-compat.

use serde::{Deserialize, Serialize};
use serde_json::Value;

// ── Method name constants ─────────────────────────────────────────────────────

/// Strongly-typed method name constants.
///
/// Using `&'static str` constants (rather than an enum) keeps serialization
/// trivial and avoids an extra match arm every time a method name is compared.
pub(crate) mod method {
    pub const INITIALIZE: &str = "initialize";
    #[allow(dead_code)]
    pub const AUTHENTICATE: &str = "authenticate";
    pub const SESSION_NEW: &str = "session/new";
    pub const SESSION_LOAD: &str = "session/load";
    pub const SESSION_PROMPT: &str = "session/prompt";
    pub const SESSION_CANCEL: &str = "session/cancel";
    pub const SESSION_UPDATE: &str = "session/update";
    #[allow(dead_code)]
    pub const REQUEST_PERMISSION: &str = "session/request_permission";
}

// ── initialize ────────────────────────────────────────────────────────────────

/// Parameters for the `initialize` request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct InitializeParams {
    /// Numeric protocol version the client speaks (e.g. `1`).
    pub protocol_version: u32,
    /// Capabilities this client advertises to the agent.
    #[serde(default)]
    pub client_capabilities: super::capabilities::ClientCapabilities,
    /// Human-readable client identification.
    #[serde(default)]
    pub client_info: ClientInfo,
}

/// Human-readable identification included in `initialize`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ClientInfo {
    /// Short product name (e.g. `"pom-desktop"`).
    #[serde(default)]
    pub name: String,
    /// SemVer string (e.g. `"0.1.0"`).
    #[serde(default)]
    pub version: String,
}

/// An authentication method advertised by the agent in the `initialize` response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct WireAuthMethod {
    /// Machine-readable identifier (e.g. `"oauth-personal"`, `"gemini-api-key"`).
    pub id: String,
    /// Human-readable label (e.g. `"Log in with Google"`).
    #[serde(default)]
    pub name: String,
    /// Optional description of the auth method.
    #[serde(default)]
    pub description: Option<String>,
}

/// Result returned by the agent for the `initialize` request.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct InitializeResult {
    /// Protocol version the agent speaks.
    #[serde(default)]
    pub protocol_version: u32,
    /// Capabilities the agent reports.
    #[serde(default)]
    pub agent_capabilities: super::capabilities::AgentCapabilities,
    /// Authentication methods supported by the agent.
    ///
    /// The Gemini CLI returns structured objects with `id`, `name`, and
    /// optional `description`. Older versions returned plain strings.
    #[serde(default)]
    pub auth_methods: Vec<WireAuthMethod>,
    /// Unknown/future keys from the agent are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

// ── authenticate ──────────────────────────────────────────────────────────────

/// Parameters for the `authenticate` request.
#[allow(dead_code)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AuthenticateParams {
    /// Chosen auth method from `InitializeResult::auth_methods`.
    pub auth_method: String,
}

/// Result returned by the agent for the `authenticate` request.
#[allow(dead_code)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct AuthenticateResult {
    /// `true` when authentication succeeded.
    #[serde(default)]
    pub success: bool,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

// ── session/new ───────────────────────────────────────────────────────────────

/// Parameters for the `session/new` request.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SessionNewParams {
    /// Working directory the agent session should start in.
    #[serde(default)]
    pub cwd: String,
    /// MCP server configurations to connect during the session.
    #[serde(default)]
    pub mcp_servers: Vec<Value>,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

/// Result returned by the agent for the `session/new` request.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SessionNewResult {
    /// Opaque session identifier — required for all subsequent session calls.
    #[serde(default)]
    pub session_id: String,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

// ── session/load ──────────────────────────────────────────────────────────────

/// Parameters for the `session/load` request (resume a prior session).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SessionLoadParams {
    /// ID of the session to resume.
    pub session_id: String,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

/// Result returned by the agent for the `session/load` request.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SessionLoadResult {
    /// Confirmed session ID (may differ if the agent remapped it).
    #[serde(default)]
    pub session_id: String,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

// ── session/prompt ────────────────────────────────────────────────────────────

/// Parameters for the `session/prompt` request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SessionPromptParams {
    /// Target session.
    pub session_id: String,
    /// Ordered list of content blocks forming the user's prompt.
    pub prompt: Vec<super::content::WireContentBlock>,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

/// Result returned by the agent when a `session/prompt` turn completes.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SessionPromptResult {
    /// Why the turn ended: `"end_turn"`, `"max_tokens"`, `"stop_sequence"`, etc.
    #[serde(default)]
    pub stop_reason: String,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

// ── session/cancel ────────────────────────────────────────────────────────────

/// Parameters for the `session/cancel` request (interrupt an in-flight prompt).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SessionCancelParams {
    /// ID of the session whose prompt should be cancelled.
    pub session_id: String,
}

// ── session/request_permission ────────────────────────────────────────────────

/// Parameters for the `session/request_permission` **reverse request** — the
/// agent asks the client whether it may perform a tool call.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RequestPermissionParams {
    /// Session that triggered the permission check.
    pub session_id: String,
    /// Description of the tool call that requires authorization.
    pub tool_call: PermissionToolCall,
    /// Choices the user can make (e.g. Allow once / Allow always / Deny).
    #[serde(default)]
    pub options: Vec<PermissionOption>,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

/// Describes a specific tool invocation for which permission is being requested.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PermissionToolCall {
    /// Stable ID that ties this permission request to a later `tool_call` update.
    pub tool_call_id: String,
    /// Human-readable title shown in the approval UI.
    #[serde(default)]
    pub title: String,
    /// Tool category/kind (e.g. `"shell"`, `"read_file"`).
    #[serde(default)]
    pub kind: String,
    /// Raw input the tool will receive — shown in the approval UI.
    #[serde(default)]
    pub raw_input: Value,
    /// Source locations relevant to the tool call (e.g. files being modified).
    #[serde(default)]
    pub locations: Vec<ToolLocation>,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

/// A source location associated with a tool call or permission request.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ToolLocation {
    /// File URI (e.g. `"file:///home/user/project/main.rs"`).
    #[serde(default)]
    pub uri: String,
    /// Optional line/column range within the file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub range: Option<Value>,
}

/// A single selectable option in a permission dialog.
///
/// The Gemini CLI currently sends `optionId`, `name`, and `kind` for each
/// option. We accept both the original field names (`id`, `label`) and the
/// CLI's actual names via `serde(alias)`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PermissionOption {
    /// Opaque ID sent back in `RequestPermissionResponse`.
    ///
    /// The CLI sends this as `optionId` rather than `id`.
    #[serde(alias = "optionId")]
    pub id: String,
    /// Short button label shown in the UI.
    ///
    /// The CLI sends this as `name` rather than `label`.
    #[serde(default, alias = "name")]
    pub label: String,
    /// Longer description shown as a tooltip or sub-label.
    #[serde(default)]
    pub description: String,
    /// Unknown/future keys are preserved.
    #[serde(flatten)]
    pub extra: Value,
}

/// The client's response to a `session/request_permission` reverse request.
///
/// Per the ACP spec, the result wraps an `outcome` object that is a
/// discriminated union on the `outcome` field:
/// ```json
/// { "outcome": { "outcome": "selected", "optionId": "proceed_once" } }
/// { "outcome": { "outcome": "cancelled" } }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RequestPermissionResponse {
    /// The user's decision, nested as the ACP `RequestPermissionOutcome`.
    pub outcome: RequestPermissionOutcome,
}

/// Discriminated union for the permission decision.
///
/// - `selected` + `optionId`: the user chose a specific option.
/// - `cancelled`: the user dismissed / denied.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RequestPermissionOutcome {
    /// `"selected"` or `"cancelled"`.
    pub outcome: String,
    /// The `PermissionOption::id` that was selected. Absent when cancelled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub option_id: Option<String>,
    /// Modified tool input from the permission callback (e.g., sanitized command).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_input: Option<Value>,
    /// When `true`, signals that the session should be interrupted after denial.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interrupt: Option<bool>,
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_initialize_params_roundtrip() {
        let raw = json!({
            "protocolVersion": 1,
            "clientCapabilities": {},
            "clientInfo": {
                "name": "pom-desktop",
                "version": "0.1.0"
            }
        });
        let params: InitializeParams =
            serde_json::from_value(raw.clone()).expect("deserialize InitializeParams");

        assert_eq!(params.protocol_version, 1);
        assert_eq!(params.client_info.name, "pom-desktop");
        assert_eq!(params.client_info.version, "0.1.0");

        let back = serde_json::to_value(&params).expect("re-serialize InitializeParams");
        assert_eq!(back["protocolVersion"], 1);
        assert_eq!(back["clientInfo"]["name"], "pom-desktop");
        assert_eq!(back["clientInfo"]["version"], "0.1.0");
    }

    #[test]
    fn test_initialize_result_extra_fields_preserved() {
        let raw = json!({
            "protocolVersion": 1,
            "agentCapabilities": { "streaming": true },
            "authMethods": [
                { "id": "oauth-personal", "name": "Log in with Google", "description": null },
                { "id": "gemini-api-key", "name": "Use Gemini API key" }
            ],
            "serverName": "gemini-cli/1.0.0"
        });
        let result: InitializeResult =
            serde_json::from_value(raw.clone()).expect("deserialize InitializeResult");
        assert_eq!(result.protocol_version, 1);
        assert_eq!(result.auth_methods.len(), 2);
        assert_eq!(result.auth_methods[0].id, "oauth-personal");
        assert_eq!(result.auth_methods[1].id, "gemini-api-key");
        assert_eq!(result.auth_methods[1].description, None);

        let back = serde_json::to_value(&result).expect("re-serialize InitializeResult");
        assert_eq!(back["serverName"], "gemini-cli/1.0.0", "extra field must survive roundtrip");
    }

    #[test]
    fn test_permission_request_roundtrip() {
        let raw = json!({
            "sessionId": "sess-abc",
            "toolCall": {
                "toolCallId": "tc-001",
                "title": "Run shell command",
                "kind": "shell",
                "rawInput": { "command": "ls -la" },
                "locations": [{ "uri": "file:///home/user/project" }]
            },
            "options": [
                { "id": "allow_once", "label": "Allow once", "description": "" },
                { "id": "deny",       "label": "Deny",       "description": "" }
            ]
        });

        let params: RequestPermissionParams =
            serde_json::from_value(raw.clone()).expect("deserialize RequestPermissionParams");

        assert_eq!(params.session_id, "sess-abc");
        assert_eq!(params.tool_call.tool_call_id, "tc-001");
        assert_eq!(params.tool_call.kind, "shell");
        assert_eq!(params.options.len(), 2);
        assert_eq!(params.options[0].id, "allow_once");
        assert_eq!(params.options[1].id, "deny");
        assert_eq!(params.tool_call.locations[0].uri, "file:///home/user/project");

        // Re-serialize and validate key fields survive.
        let back = serde_json::to_value(&params).expect("re-serialize RequestPermissionParams");
        assert_eq!(back["sessionId"], "sess-abc");
        assert_eq!(back["toolCall"]["toolCallId"], "tc-001");
    }

    #[test]
    fn test_permission_response_selected() {
        let resp = RequestPermissionResponse {
            outcome: RequestPermissionOutcome {
                outcome: "selected".to_string(),
                option_id: Some("allow_once".to_string()),
                updated_input: None,
                interrupt: None,
            },
        };
        let v = serde_json::to_value(&resp).expect("serialize");
        let outcome = &v["outcome"];
        assert_eq!(outcome["outcome"], "selected");
        assert_eq!(outcome["optionId"], "allow_once");
        assert!(outcome.get("interrupt").is_none(), "interrupt must be absent when None");
    }

    #[test]
    fn test_permission_response_cancelled_omits_option_id() {
        let resp = RequestPermissionResponse {
            outcome: RequestPermissionOutcome {
                outcome: "cancelled".to_string(),
                option_id: None,
                updated_input: None,
                interrupt: None,
            },
        };
        let v = serde_json::to_value(&resp).expect("serialize");
        let outcome = &v["outcome"];
        assert_eq!(outcome["outcome"], "cancelled");
        assert!(outcome.get("optionId").is_none(), "optionId must be absent when cancelled");
        assert!(outcome.get("interrupt").is_none(), "interrupt must be absent when None");
    }

    #[test]
    fn test_permission_response_interrupt_true_serialized() {
        let resp = RequestPermissionResponse {
            outcome: RequestPermissionOutcome {
                outcome: "cancelled".to_string(),
                option_id: None,
                updated_input: None,
                interrupt: Some(true),
            },
        };
        let v = serde_json::to_value(&resp).expect("serialize");
        let outcome = &v["outcome"];
        assert_eq!(outcome["outcome"], "cancelled");
        assert_eq!(outcome["interrupt"], true, "interrupt: Some(true) must serialize as true");
    }

    #[test]
    fn test_permission_response_interrupt_none_omitted() {
        let resp = RequestPermissionResponse {
            outcome: RequestPermissionOutcome {
                outcome: "cancelled".to_string(),
                option_id: None,
                updated_input: None,
                interrupt: None,
            },
        };
        let v = serde_json::to_value(&resp).expect("serialize");
        let outcome = &v["outcome"];
        assert!(outcome.get("interrupt").is_none(), "interrupt: None must be omitted from JSON");
    }

    #[test]
    fn test_session_prompt_params_roundtrip() {
        let raw = json!({
            "sessionId": "sess-xyz",
            "prompt": [
                { "type": "text", "text": "Hello" }
            ]
        });
        let params: SessionPromptParams =
            serde_json::from_value(raw).expect("deserialize SessionPromptParams");
        assert_eq!(params.session_id, "sess-xyz");
        assert_eq!(params.prompt.len(), 1);
        assert_eq!(params.prompt[0].content_type, "text");
        assert_eq!(params.prompt[0].text.as_deref(), Some("Hello"));
    }
}