parecode 0.1.1

A terminal coding agent built for token efficiency and local model reliability
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
use anyhow::{anyhow, Result};
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::Value;

// ── Wire types ────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub role: String,
    pub content: MessageContent,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContent {
    Text(String),
    Parts(Vec<ContentPart>),
}

impl From<&str> for MessageContent {
    fn from(s: &str) -> Self {
        MessageContent::Text(s.to_string())
    }
}

impl From<String> for MessageContent {
    fn from(s: String) -> Self {
        MessageContent::Text(s)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    Text { text: String },
    ToolResult { tool_use_id: String, content: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tool {
    pub name: String,
    pub description: String,
    pub parameters: Value,
}

// ── Completed tool call (after accumulating deltas) ───────────────────────────

#[derive(Debug, Clone)]
pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub arguments: String,
}

// ── Model response after streaming completes ──────────────────────────────────

#[derive(Debug)]
pub struct ModelResponse {
    pub text: String,
    pub tool_calls: Vec<ToolCall>,
    pub input_tokens: u32,
    pub output_tokens: u32,
}

// ── SSE delta types for accumulation ─────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct StreamChunk {
    choices: Option<Vec<StreamChoice>>,
    usage: Option<UsageStats>,
}

#[derive(Debug, Deserialize)]
struct StreamChoice {
    delta: Option<Delta>,
    _finish_reason: Option<String>,
}

#[derive(Debug, Deserialize)]
struct Delta {
    content: Option<String>,
    /// Reasoning/thinking tokens from models that return them as a separate field
    /// (DeepSeek-R1, Qwen3 with thinking enabled, etc.)
    reasoning_content: Option<String>,
    tool_calls: Option<Vec<ToolCallDelta>>,
}

#[derive(Debug, Deserialize)]
struct ToolCallDelta {
    index: usize,
    id: Option<String>,
    function: Option<FunctionDelta>,
}

#[derive(Debug, Deserialize)]
struct FunctionDelta {
    name: Option<String>,
    arguments: Option<String>,
}

#[derive(Debug, Deserialize)]
struct UsageStats {
    prompt_tokens: Option<u32>,
    completion_tokens: Option<u32>,
}

// ── In-progress tool call accumulator ────────────────────────────────────────

#[derive(Default)]
struct PendingToolCall {
    id: String,
    name: String,
    arguments: String,
}

// ── Client ────────────────────────────────────────────────────────────────────

pub struct Client {
    http: reqwest::Client,
    pub endpoint: String,
    pub model: String,
    api_key: Option<String>,
}

impl Client {
    pub fn new(endpoint: String, model: String) -> Self {
        Self {
            http: reqwest::Client::new(),
            endpoint,
            model,
            api_key: None,
        }
    }

    pub fn set_api_key(&mut self, key: String) {
        self.api_key = Some(key);
    }

    /// Stream a chat completion. Calls `on_text` for each text chunk as it arrives.
    /// Returns the complete response once streaming finishes.
    pub async fn chat(
        &self,
        system: &str,
        messages: &[Message],
        tools: &[Tool],
        on_text: impl Fn(&str),
    ) -> Result<ModelResponse> {
        let mut body = serde_json::json!({
            "model": self.model,
            "stream": true,
            "stream_options": {"include_usage": true},
            "messages": build_messages(system, messages),
        });

        if !tools.is_empty() {
            body["tools"] = serde_json::json!(
                tools.iter().map(|t| serde_json::json!({
                    "type": "function",
                    "function": {
                        "name": t.name,
                        "description": t.description,
                        "parameters": t.parameters,
                    }
                })).collect::<Vec<_>>()
            );
            body["tool_choice"] = serde_json::json!("auto");
        }

        let url = format!("{}/v1/chat/completions", self.endpoint.trim_end_matches('/'));

        let mut req = self
            .http
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&body);

        if let Some(key) = &self.api_key {
            req = req.header("Authorization", format!("Bearer {key}"));
        }

        let resp = req.send().await?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            return Err(anyhow!("API error {}: {}", status, text));
        }

        let mut stream = resp.bytes_stream();

        let mut text_buf = String::new();
        // Index → accumulator
        let mut pending: Vec<PendingToolCall> = Vec::new();
        let mut input_tokens = 0u32;
        let mut output_tokens = 0u32;
        let mut leftover = String::new();
        // Track whether we're mid-reasoning-block (for models that use reasoning_content field)
        let mut reasoning_open = false;

        // Debug log — raw stream to /tmp/parecode-stream.log for diagnosing model output
        let mut debug_log: Option<std::fs::File> = std::fs::OpenOptions::new()
            .create(true).append(true)
            .open("/tmp/parecode-stream.log")
            .ok();

        while let Some(chunk) = stream.next().await {
            let bytes = chunk?;
            let raw = std::str::from_utf8(&bytes).unwrap_or("");

            // SSE may split across chunks; prepend any leftover from last iteration
            let combined = format!("{}{}", leftover, raw);
            leftover.clear();

            for line in combined.lines() {
                let line = line.trim();
                if line.is_empty() || line == "data: [DONE]" {
                    continue;
                }
                let json_str = match line.strip_prefix("data: ") {
                    Some(s) => s,
                    None => continue,
                };

                // If JSON is incomplete (split mid-chunk), save for next iteration
                let chunk_val: StreamChunk = match serde_json::from_str(json_str) {
                    Ok(v) => v,
                    Err(_) => {
                        leftover = line.to_string();
                        continue;
                    }
                };

                if let Some(usage) = chunk_val.usage {
                    input_tokens = usage.prompt_tokens.unwrap_or(0);
                    output_tokens = usage.completion_tokens.unwrap_or(0);
                }

                for choice in chunk_val.choices.unwrap_or_default() {
                    if let Some(delta) = choice.delta {
                        // Debug log: write raw delta JSON so we can see what the model emits
                        if let Some(f) = &mut debug_log {
                            use std::io::Write as _;
                            let _ = writeln!(f, "{json_str}");
                        }

                        // reasoning_content field (DeepSeek-R1, Qwen3 thinking mode, etc.)
                        // Wrap in <think> tags so the agent's splitter routes it correctly
                        if let Some(rc) = delta.reasoning_content {
                            if !rc.is_empty() {
                                if !reasoning_open {
                                    on_text("<think>");
                                    reasoning_open = true;
                                }
                                on_text(&rc);
                            }
                        } else if reasoning_open {
                            // reasoning_content stopped arriving — close the tag
                            on_text("</think>");
                            reasoning_open = false;
                        }

                        // Accumulate text
                        if let Some(text) = delta.content {
                            if reasoning_open {
                                // Some models send content="" alongside last reasoning chunk
                                if !text.is_empty() {
                                    on_text("</think>");
                                    reasoning_open = false;
                                    on_text(&text);
                                    text_buf.push_str(&text);
                                }
                            } else {
                                on_text(&text);
                                text_buf.push_str(&text);
                            }
                        }

                        // Accumulate tool call deltas
                        for tc_delta in delta.tool_calls.unwrap_or_default() {
                            let idx = tc_delta.index;
                            // Grow pending vec if needed
                            while pending.len() <= idx {
                                pending.push(PendingToolCall::default());
                            }
                            let entry = &mut pending[idx];
                            if let Some(id) = tc_delta.id {
                                entry.id = id;
                            }
                            if let Some(func) = tc_delta.function {
                                if let Some(name) = func.name {
                                    entry.name.push_str(&name);
                                }
                                if let Some(args) = func.arguments {
                                    entry.arguments.push_str(&args);
                                }
                            }
                        }
                    }
                }
            }
        }

        // Close any still-open reasoning block
        if reasoning_open {
            on_text("</think>");
        }

        // Write separator to debug log
        if let Some(f) = &mut debug_log {
            use std::io::Write as _;
            let _ = writeln!(f, "---END---");
        }

        let tool_calls = pending
            .into_iter()
            .filter(|p| !p.name.is_empty())
            .map(|p| ToolCall {
                id: p.id,
                name: p.name,
                arguments: p.arguments,
            })
            .collect();

        Ok(ModelResponse {
            text: text_buf,
            tool_calls,
            input_tokens,
            output_tokens,
        })
    }
}

// ── Build the messages array for the API ──────────────────────────────────────

fn build_messages(system: &str, messages: &[Message]) -> Vec<Value> {
    let mut out = Vec::new();

    if !system.is_empty() {
        out.push(serde_json::json!({
            "role": "system",
            "content": system
        }));
    }

    for msg in messages {
        match &msg.content {
            MessageContent::Text(text) => {
                out.push(serde_json::json!({
                    "role": msg.role,
                    "content": text
                }));
            }
            MessageContent::Parts(parts) => {
                // Flatten parts for OpenAI-compat: tool results become individual messages
                for part in parts {
                    match part {
                        ContentPart::ToolResult { tool_use_id, content } => {
                            out.push(serde_json::json!({
                                "role": "tool",
                                "tool_call_id": tool_use_id,
                                "content": content
                            }));
                        }
                        ContentPart::Text { text } => {
                            out.push(serde_json::json!({
                                "role": msg.role,
                                "content": text
                            }));
                        }
                    }
                }
            }
        }
    }

    out
}

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

    #[test]
    fn test_content_part_serialize() {
        let part = ContentPart::Text { text: "hello".to_string() };
        let json = serde_json::to_string(&part).unwrap();
        assert!(json.contains("\"type\":\"text\""));
    }

    #[test]
    fn test_model_response() {
        let response = ModelResponse {
            text: "test response".to_string(),
            tool_calls: vec![],
            input_tokens: 100,
            output_tokens: 200,
        };
        assert_eq!(response.text, "test response");
        assert_eq!(response.input_tokens, 100);
        assert_eq!(response.output_tokens, 200);
    }

    #[test]
    fn test_pending_tool_call_default() {
        let pending = PendingToolCall::default();
        assert!(pending.id.is_empty());
        assert!(pending.name.is_empty());
        assert!(pending.arguments.is_empty());
    }
}