opencrabs 0.5.10

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Recommended: the 40MB prebuilt binary for macOS, Linux and Windows: https://github.com/opencrabs/opencrabs/releases
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
//! JSON-RPC 2.0 framing plus the ACP vocabulary the server speaks.
//!
//! ACP is JSON-RPC over NDJSON: one message per line on stdin/stdout. Three
//! message shapes arrive from the client — requests (`id` + `method`),
//! notifications (`method`, no `id`), and responses to OUR outbound requests
//! (`id` + `result`/`error`, no `method`) — so parsing is a classify step,
//! not a deserialize-into-one-struct step.

use serde_json::{Value, json};

/// Standard JSON-RPC error codes plus ACP's auth-required code.
pub const PARSE_ERROR: i64 = -32700;
pub const INVALID_REQUEST: i64 = -32600;
pub const METHOD_NOT_FOUND: i64 = -32601;
pub const INVALID_PARAMS: i64 = -32602;
pub const INTERNAL_ERROR: i64 = -32603;

// Inbound methods (client -> agent).
pub const INITIALIZE: &str = "initialize";
pub const SESSION_NEW: &str = "session/new";
pub const SESSION_LOAD: &str = "session/load";
/// Session lifecycle methods from the official v1 schema (#1815 F5). These are
/// unprefixed on purpose: they are spec names, not extensions, and v1 reserves
/// every unprefixed name for the protocol itself. `session/set_config_option`
/// is the official write half of the config-option picker F4 only displayed.
pub const SESSION_LIST: &str = "session/list";
pub const SESSION_RESUME: &str = "session/resume";
pub const SESSION_SET_CONFIG_OPTION: &str = "session/set_config_option";
pub const SESSION_CLOSE: &str = "session/close";
pub const SESSION_DELETE: &str = "session/delete";
pub const SESSION_PROMPT: &str = "session/prompt";
/// Custom model selection. Not a v1 or v2 method, and v1 reserves every
/// unprefixed name for future protocol versions, so the custom request carries
/// the `_opencrabs/` prefix (#1815 F3).
pub const SESSION_SET_MODEL: &str = "_opencrabs/set_model";
/// Pre-prefix spelling, accepted as an alias for one release.
pub const SESSION_SET_MODEL_LEGACY: &str = "session/set_model";
/// Runtime mode selection: `plan` denies mutations, `auto-accept-edits`
/// pre-approves edit-kind tools, `auto`/`full-access` pre-approve everything,
/// and `supervised` routes approvals to the client.
pub const SESSION_SET_MODE: &str = "session/set_mode";
pub const SESSION_CANCEL: &str = "session/cancel";
/// Custom manual-compaction request, prefixed for the same reason as
/// `SESSION_SET_MODEL` (#1815 F3).
pub const SESSION_COMPACT: &str = "_opencrabs/compact";
/// Pre-prefix spelling, accepted as an alias for one release.
pub const SESSION_COMPACT_LEGACY: &str = "session/compact";
pub const SESSION_STEER: &str = "_session/steer";
/// Pre-ext-prefix spelling, accepted as an alias for older adapters.
pub const SESSION_STEER_LEGACY: &str = "session/steer";

/// The custom methods this agent accepts, in canonical form. Advertised in the
/// `initialize` result under `_meta`, which is the one place the spec lets an
/// implementation say so without claiming a reserved name (#1815 F3). The
/// legacy spellings still dispatch but are deliberately not advertised: a new
/// client should not be pointed at a name we intend to retire.
pub const EXTENSION_METHODS: &[&str] = &[SESSION_SET_MODEL, SESSION_COMPACT, SESSION_STEER];

// Outbound frames (agent -> client).
pub const SESSION_UPDATE: &str = "session/update";
pub const SESSION_REQUEST_PERMISSION: &str = "session/request_permission";

/// A classified inbound JSON-RPC message.
#[derive(Debug)]
pub enum ClientMessage {
    /// `id` kept as a raw Value: JSON-RPC allows string or number ids and the
    /// response must echo it verbatim.
    Request {
        id: Value,
        method: String,
        params: Value,
    },
    Notification {
        method: String,
        params: Value,
    },
    /// Response to a server-initiated request. Only numeric ids are ours.
    Response {
        id: u64,
        result: Result<Value, RpcError>,
    },
}

/// A JSON-RPC error object.
#[derive(Debug, Clone)]
pub struct RpcError {
    pub code: i64,
    pub message: String,
}

/// Parse one NDJSON line into a classified message.
///
/// Classification rule: presence of `method` decides request vs notification
/// (by presence of `id`); absence of `method` with an `id` is a response.
/// Anything else is an invalid-request error the caller reports.
pub fn parse_line(line: &str) -> Result<ClientMessage, (Value, RpcError)> {
    let value: Value = serde_json::from_str(line).map_err(|e| {
        (
            Value::Null,
            RpcError {
                code: PARSE_ERROR,
                message: format!("invalid JSON: {e}"),
            },
        )
    })?;

    let method = value.get("method").and_then(Value::as_str);
    let id = value.get("id").cloned();

    match (method, id) {
        (Some(m), Some(id)) => Ok(ClientMessage::Request {
            id,
            method: m.to_string(),
            params: value.get("params").cloned().unwrap_or(Value::Null),
        }),
        (Some(m), None) => Ok(ClientMessage::Notification {
            method: m.to_string(),
            params: value.get("params").cloned().unwrap_or(Value::Null),
        }),
        (None, Some(id)) => {
            let Some(n) = id.as_u64() else {
                // Not one of ours — outbound ids are always u64.
                return Err((
                    id,
                    RpcError {
                        code: INVALID_REQUEST,
                        message: "response id is not a server-issued id".into(),
                    },
                ));
            };
            let result = if let Some(err) = value.get("error") {
                Err(RpcError {
                    code: err
                        .get("code")
                        .and_then(Value::as_i64)
                        .unwrap_or(INTERNAL_ERROR),
                    message: err
                        .get("message")
                        .and_then(Value::as_str)
                        .unwrap_or("unknown error")
                        .to_string(),
                })
            } else {
                Ok(value.get("result").cloned().unwrap_or(Value::Null))
            };
            Ok(ClientMessage::Response { id: n, result })
        }
        (None, None) => Err((
            Value::Null,
            RpcError {
                code: INVALID_REQUEST,
                message: "message has neither method nor id".into(),
            },
        )),
    }
}

/// A successful response frame.
pub fn result_response(id: Value, result: Value) -> Value {
    json!({ "jsonrpc": "2.0", "id": id, "result": result })
}

/// An error response frame.
pub fn error_response(id: Value, code: i64, message: impl Into<String>) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": code, "message": message.into() },
    })
}

/// A notification frame (no id).
pub fn notification(method: &str, params: Value) -> Value {
    json!({ "jsonrpc": "2.0", "method": method, "params": params })
}

/// A server-initiated request frame.
pub fn request_frame(id: u64, method: &str, params: Value) -> Value {
    json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })
}

/// The `session/update` notification for one session.
pub fn session_update(session_id: &str, update: Value) -> Value {
    notification(
        SESSION_UPDATE,
        json!({ "sessionId": session_id, "update": update }),
    )
}

/// The result for `session/new` and `session/load`.
///
/// `echo_session_id` is what separates them: `NewSessionResponse` requires
/// `sessionId`, while `LoadSessionResponse` defines only `modes`,
/// `configOptions` and `_meta`, and an implementation MUST NOT add a root field
/// to a type the spec owns. Answering a load with the id the client just sent
/// us is exactly that (#1815 F4).
///
/// `models` is passed through untouched and remains a non-schema field. It is
/// kept on purpose: MonoCode builds its picker from it, so the field is a
/// documented wart rather than something to drop without warning (#1815 F4).
pub fn session_response(
    session_id: &str,
    models: Value,
    modes: Value,
    config_options: Value,
    echo_session_id: bool,
) -> Value {
    let mut response = json!({
        "models": models,
        "modes": modes,
        "configOptions": config_options,
    });
    if echo_session_id {
        response["sessionId"] = Value::from(session_id);
    }
    response
}

/// `plan` session update (`Plan`): the client replaces the ENTIRE plan with
/// every update, so this is always a complete snapshot and never a delta
/// (#1815 F6).
///
/// `entries` is the only required field; an empty array is legal and means "no
/// plan", which is how a discarded plan clears the client's card instead of
/// leaving a stale one on screen.
pub fn plan_update(entries: Vec<Value>) -> Value {
    json!({
        "sessionUpdate": "plan",
        "entries": entries,
    })
}

/// `session/list` result: a `ListSessionsResponse`. `sessions` is the only
/// required field; `nextCursor` is present exactly when more pages exist
/// (#1815 F5).
pub fn list_sessions_payload(sessions: Vec<Value>, next_cursor: Option<String>) -> Value {
    let mut response = json!({ "sessions": sessions });
    if let Some(cursor) = next_cursor {
        response["nextCursor"] = Value::from(cursor);
    }
    response
}

/// One `SessionInfo` entry: `sessionId` and `cwd` are required by v1, `title`
/// and `updatedAt` are optional and omitted rather than sent as null.
pub fn session_info(
    session_id: &str,
    cwd: &str,
    title: Option<&str>,
    updated_at: Option<&str>,
) -> Value {
    let mut info = json!({ "sessionId": session_id, "cwd": cwd });
    if let Some(title) = title {
        info["title"] = Value::from(title);
    }
    if let Some(updated_at) = updated_at {
        info["updatedAt"] = Value::from(updated_at);
    }
    info
}

/// `session/set_config_option` result: `SetSessionConfigOptionResponse`, whose
/// only required field is the full `configOptions` set with current values.
pub fn config_options_response(config_options: Value) -> Value {
    json!({ "configOptions": config_options })
}

/// A text `agent_message_chunk` / `agent_thought_chunk` update body.
pub fn text_chunk(kind: &str, text: &str) -> Value {
    json!({
        "sessionUpdate": kind,
        "content": { "type": "text", "text": text },
    })
}

/// `usage_update` body: the context meter.
///
/// The shape is pinned to the official v1 schema (`SessionUpdate.oneOf` in
/// `schema/v1/schema.json`, fetched 2026-10-02, 247168 bytes): the tag is
/// `usage_update`, and `UsageUpdate` is folded in with `allOf`, so `used` and
/// `size` are FLAT siblings of `sessionUpdate`, both required, both `uint64`
/// with `minimum: 0`. The frame this replaced,
/// `{"sessionUpdate":"usage","usage":{...}}`, exists in no schema version: a
/// client generated from the schema sees an unknown tagged variant and drops
/// the notification, which means the meter never moves (#1815 F1).
///
/// `cost` is optional upstream and this path has no per-session money total,
/// so it stays absent rather than being guessed at.
pub fn usage_update(used: u64, size: u64) -> Value {
    json!({
        "sessionUpdate": "usage_update",
        "used": used,
        "size": size,
    })
}

/// Transcript replay for `session/load`: an agent advertising `loadSession`
/// re-sends the stored conversation as session/update notifications before
/// answering the load. Rows map to live-turn chunk shapes: user →
/// user_message_chunk; assistant → thought chunks (persisted `thinking` and
/// inline reasoning segments via the TUI splitter) plus message chunks.
pub fn replay_updates(messages: &[crate::db::models::Message]) -> Vec<Value> {
    use crate::tui::app::reasoning_split::{BLOCKED_LABEL, Segment, split_segments};
    let mut out = Vec::new();
    for m in messages {
        match m.role.as_str() {
            "user" => {
                if !m.content.trim().is_empty() {
                    out.push(text_chunk("user_message_chunk", &m.content));
                }
            }
            "assistant" => {
                if let Some(thinking) = &m.thinking
                    && !thinking.trim().is_empty()
                {
                    out.push(text_chunk("agent_thought_chunk", thinking));
                }
                for segment in split_segments(&m.content) {
                    match segment {
                        Segment::Reasoning(t) => {
                            out.push(text_chunk("agent_thought_chunk", &t));
                        }
                        Segment::Blocked(b) => out.push(text_chunk(
                            "agent_thought_chunk",
                            &format!("{BLOCKED_LABEL}\n\n{b}"),
                        )),
                        Segment::Text(t) => out.push(text_chunk("agent_message_chunk", &t)),
                    }
                }
            }
            _ => {}
        }
    }
    out
}

/// Context usage to restore on `session/load`: the provider's own
/// measurement (`input_tokens`) from the last assistant row — the doc on
/// that column calls it "the authoritative last known context size", so the
/// meter shows a real number, never a tokenized estimate. `None` when the
/// session predates usage persistence; the caller decides the fallback.
pub fn replay_usage(messages: &[crate::db::models::Message]) -> Option<i64> {
    messages
        .iter()
        .rev()
        .find(|m| m.role == "assistant")
        .and_then(|m| m.input_tokens)
}

/// `initialize` result: protocol version plus the capabilities we honor.
/// fs/terminal are false — MonoCode's adapter declares them false too, so
/// file ops stay on the agent side where the tool loop already has them.
pub fn initialize_result() -> Value {
    json!({
        "protocolVersion": 1,
        "authMethods": [],
        "agentCapabilities": {
            // Honest capability: session/load binds an existing session AND
            // replays the stored transcript as session/update notifications
            // before answering, so clients without their own transcript
            // store (Zed et al.) render history on resume.
            "loadSession": true,
            // #1815 F5: the four lifecycle capabilities v1 gates behind
            // `sessionCapabilities`. Each is an empty object meaning "supported"
            // (`{}` is the whole advertisement; there are no fields to set).
            // `additionalDirectories` is deliberately absent: this server accepts
            // and ignores the field on new/load/resume, so advertising it would
            // promise a workspace behavior we do not implement.
            //
            // `session/set_config_option` has no capability bit at all -- it is
            // implied by sending `configOptions` in the session/new response,
            // which F4 already does.
            "sessionCapabilities": {
                "list": {},
                "resume": {},
                "close": {},
                "delete": {},
            },
            // #1856: image prompt blocks decode to `<<IMG:path>>` attachments on
            // disk (decode_image_block), so the advertisement is honest and
            // clients (MonoCode, Zed custom agents) can ship images.
            "promptCapabilities": { "text": true, "image": true, "embeddedContext": false },
        },
        "agentInfo": {
            "name": "opencrabs",
            "version": env!("CARGO_PKG_VERSION"),
        },
        // Custom methods live in `_meta`, never in reserved root names: the
        // extensibility rule is that a custom request must start with an
        // underscore, and implementations MUST NOT add custom fields at the
        // root of a spec type (#1815 F3).
        "_meta": {
            "extensions": EXTENSION_METHODS,
        },
    })
}

/// Extract the text of a `session/prompt` (or `session/steer`) prompt block
/// list. Text blocks pass through; resource/resource_link blocks contribute
/// their uri as a readable reference so attachments survive as paths. Image
/// blocks are decoded to files under the attachments dir and surfaced as
/// `<<IMG:path>>` markers, the same shape every channel already speaks.
pub fn prompt_text(params: &Value) -> Option<String> {
    let blocks = params.get("prompt")?.as_array()?;
    let mut parts = Vec::new();
    let mut images = 0usize;
    for block in blocks {
        match block.get("type").and_then(Value::as_str) {
            Some("text") => {
                if let Some(t) = block.get("text").and_then(Value::as_str) {
                    parts.push(t.to_string());
                }
            }
            Some("image") => {
                if let Some(path) = decode_image_block(block) {
                    parts.push(format!("<<IMG:{path}>>"));
                    images += 1;
                }
            }
            Some("resource_link") => {
                if let Some(uri) = block.get("uri").and_then(Value::as_str) {
                    parts.push(format!("Attached file (read from disk): {uri:?}"));
                }
            }
            Some("resource") => {
                if let Some(uri) = block
                    .get("resource")
                    .and_then(|r| r.get("uri"))
                    .and_then(Value::as_str)
                {
                    parts.push(format!("Attached file (read from disk): {uri:?}"));
                }
            }
            _ => {}
        }
    }
    if images > 0 {
        parts.push(
            "IMPORTANT: Image attachment(s) present. Call analyze_image for EACH <<IMG:path>> marker separately. Do not skip any image."
                .to_string(),
        );
    }
    let text = parts.join("\n");
    if text.trim().is_empty() {
        None
    } else {
        Some(text)
    }
}

/// Decode one ACP image block to a file under the attachments dir and return
/// its path. MonoCode sends the flat wire shape (`{data, mimeType}`); the
/// nested `source.data` variant is accepted as a fallback so both forms work.
fn decode_image_block(block: &Value) -> Option<String> {
    use base64::Engine as _;
    let data = block
        .get("data")
        .or_else(|| block.get("source").and_then(|s| s.get("data")))
        .and_then(Value::as_str)?;
    let mime = block
        .get("mimeType")
        .or_else(|| block.get("source").and_then(|s| s.get("mimeType")))
        .and_then(Value::as_str)
        .unwrap_or("image/png");
    let ext = match mime {
        "image/jpeg" | "image/jpg" => "jpg",
        "image/gif" => "gif",
        "image/webp" => "webp",
        _ => "png",
    };
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(data.trim())
        .ok()?;
    let dir = crate::channels::channel_attachments_dir().join("acp");
    std::fs::create_dir_all(&dir).ok()?;
    let name = format!(
        "acp-img-{}.{ext}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .ok()?
            .as_nanos()
    );
    let path = dir.join(name);
    std::fs::write(&path, bytes).ok()?;
    Some(path.to_string_lossy().into_owned())
}

/// Map an opencrabs tool name to an ACP tool-call `kind`. The client uses
/// the kind for icons and for plan-mode read-only gating (read/search pass,
/// everything else asks).
pub fn tool_kind(tool_name: &str) -> &'static str {
    match tool_name {
        "read_file" | "load_brain_file" => "read",
        "edit_file" | "write_file" | "hashline_edit" | "write_opencrabs_file" => "edit",
        "grep" | "glob" | "memory_search" | "kb_search" | "web_search" | "exa_search"
        | "brave_search" | "session_search" | "channel_search" => "search",
        "bash" | "execute_code" | "slash_command" => "execute",
        "http_request" | "web_scrape" => "fetch",
        "plan" | "bankai_task" | "bankai_prime" | "session_context" => "think",
        _ => "other",
    }
}

/// Permission modes advertised in `session/new` and accepted by
/// `session/set_mode`. The ids mirror MonoCode's runtime modes so the client
/// mapping is identity; `plan` is the read-only intent.
///
/// The mode moves the approval policy server-side: the turn's approval
/// callback consults it before deciding whether a gated tool call is
/// forwarded to the client, auto-approved, or denied outright.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AcpMode {
    /// Every approval-gated tool asks the client (default).
    #[default]
    Supervised,
    /// Edit-kind tools auto-approve; anything else still asks.
    AutoAcceptEdits,
    /// Approval-gated tools auto-approve without asking.
    Auto,
    /// Same gate as `auto` here — the distinction is client-side UI scope.
    FullAccess,
    /// Read-only intent: approval-gated (mutating) tools are denied before
    /// the client is asked, and the denial tells the agent why.
    Plan,
}

impl AcpMode {
    pub fn parse(id: &str) -> Option<Self> {
        match id {
            "supervised" => Some(Self::Supervised),
            "auto-accept-edits" => Some(Self::AutoAcceptEdits),
            "auto" => Some(Self::Auto),
            "full-access" => Some(Self::FullAccess),
            "plan" => Some(Self::Plan),
            _ => None,
        }
    }

    pub fn id(self) -> &'static str {
        match self {
            Self::Supervised => "supervised",
            Self::AutoAcceptEdits => "auto-accept-edits",
            Self::Auto => "auto",
            Self::FullAccess => "full-access",
            Self::Plan => "plan",
        }
    }
}

/// `modes` payload for `session/new`/`session/load` responses.
pub fn modes_payload(current: AcpMode) -> Value {
    json!({
        "availableModes": [
            { "id": "supervised", "name": "Supervised" },
            { "id": "auto-accept-edits", "name": "Auto-accept edits" },
            { "id": "auto", "name": "Auto" },
            { "id": "full-access", "name": "Full access" },
            { "id": "plan", "name": "Plan (read-only)" },
        ],
        "currentModeId": current.id(),
    })
}

/// The option list sent with every `session/request_permission`. Ids match
/// the adapter's preference order (`allow-once`, `allow-always`, `reject-once`).
pub fn permission_options() -> Value {
    json!([
        { "optionId": "allow-once", "name": "Allow once", "kind": "allow_once" },
        { "optionId": "allow-always", "name": "Always allow", "kind": "allow_always" },
        { "optionId": "reject-once", "name": "Reject", "kind": "reject_once" },
    ])
}

/// Map a permission response onto the loop's `(approved, always)` pair.
/// `cancelled` outcomes and unknown option ids deny — a confused client must
/// never become an approval.
pub fn permission_outcome(result: &Value) -> (bool, bool) {
    let outcome = result.get("outcome").unwrap_or(result);
    let selected = outcome.get("outcome").and_then(Value::as_str);
    if selected != Some("selected") {
        return (false, false);
    }
    match outcome.get("optionId").and_then(Value::as_str) {
        Some("allow-always") | Some("allow_always") => (true, true),
        Some("allow-once") | Some("allow_once") | Some("allow") => (true, false),
        _ => (false, false),
    }
}

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

    /// Smallest valid 1x1 PNG, base64-encoded.
    const PNG_1PX: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";

    #[test]
    fn image_blocks_become_markers_on_disk() {
        let params = json!({
            "prompt": [
                { "type": "text", "text": "lihat ini" },
                { "type": "image", "data": PNG_1PX, "mimeType": "image/png" }
            ]
        });
        let text = prompt_text(&params).expect("turn with image keeps text");
        assert!(text.contains("lihat ini"));
        let start = text.find("<<IMG:").expect("IMG marker present");
        let end = text[start..].find(">>").expect("marker closed") + start;
        let path = &text[start + 6..end];
        assert!(
            std::path::Path::new(path).exists(),
            "decoded image written to {path}"
        );
        assert!(
            text.contains("analyze_image"),
            "analysis instruction present"
        );
    }

    #[test]
    fn nested_source_image_shape_also_decodes() {
        let params = json!({
            "prompt": [
                { "type": "image", "source": { "data": PNG_1PX, "mimeType": "image/png" } }
            ]
        });
        let text = prompt_text(&params).expect("image-only turn yields marker text");
        assert!(text.contains("<<IMG:"));
    }

    #[test]
    fn text_only_prompts_get_no_image_instruction() {
        let params = json!({ "prompt": [{ "type": "text", "text": "halo" }] });
        let text = prompt_text(&params).expect("plain text");
        assert!(!text.contains("<<IMG:"));
        assert!(!text.contains("analyze_image"));
    }
}