langshell-core 0.2.1

Core session, capability, diagnostics, and snapshot contracts for LangShell.
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
use std::{collections::BTreeMap, fmt, future::Future, pin::Pin, sync::Arc};

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha3::{Digest, Sha3_256};

pub const SNAPSHOT_VERSION: u32 = 2;

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SessionId(pub String);

impl SessionId {
    pub fn new(id: impl Into<String>) -> Result<Self, ErrorObject> {
        let id = id.into();
        if is_valid_session_id(&id) {
            Ok(Self(id))
        } else {
            Err(ErrorObject::new(
                "INVALID_SESSION_ID",
                "Session id must match ^[a-zA-Z0-9_\\-]{1,64}$.",
            ))
        }
    }
}

impl Default for SessionId {
    fn default() -> Self {
        Self("default".to_owned())
    }
}

impl fmt::Display for SessionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

fn is_valid_session_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 64
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum Language {
    #[default]
    Python,
    TypeScript,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionLimits {
    pub memory_mb: u32,
    pub cpu_ms: u32,
    pub wall_ms: u32,
    pub max_stdout_bytes: u32,
    pub max_external_calls: u32,
    pub max_stack_depth: u16,
}

impl Default for SessionLimits {
    fn default() -> Self {
        Self {
            memory_mb: 64,
            cpu_ms: 2_000,
            wall_ms: 5_000,
            max_stdout_bytes: 65_536,
            max_external_calls: 32,
            max_stack_depth: 256,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMeta {
    pub id: SessionId,
    pub created_at: u64,
    pub last_used_at: u64,
    pub language: Language,
    pub limits: SessionLimits,
    pub snapshot_version: u32,
}

impl Default for SessionMeta {
    fn default() -> Self {
        Self {
            id: SessionId::default(),
            created_at: 0,
            last_used_at: 0,
            language: Language::Python,
            limits: SessionLimits::default(),
            snapshot_version: SNAPSHOT_VERSION,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum SideEffect {
    #[default]
    None,
    Read,
    Write,
    Network,
    Database,
    ExternalSystem,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapabilityLimits {
    pub timeout_ms: u32,
    pub max_request_bytes: u32,
    pub max_response_bytes: u32,
    pub concurrency: u32,
    pub rate_per_min: Option<u32>,
}

impl Default for CapabilityLimits {
    fn default() -> Self {
        Self {
            timeout_ms: 5_000,
            max_request_bytes: 1_048_576,
            max_response_bytes: 1_048_576,
            concurrency: 16,
            rate_per_min: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum ApprovalPolicy {
    #[default]
    None,
    Auto {
        rule: String,
    },
    Manual,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Capability {
    pub name: String,
    pub description: String,
    pub input_schema: Value,
    pub output_schema: Value,
    pub side_effect: SideEffect,
    pub limits: CapabilityLimits,
    pub approval_policy: ApprovalPolicy,
    pub idempotent: bool,
}

impl Capability {
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        side_effect: SideEffect,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            input_schema: json!({"type": "array"}),
            output_schema: json!({}),
            side_effect,
            limits: CapabilityLimits::default(),
            approval_policy: ApprovalPolicy::None,
            idempotent: true,
        }
    }

    pub fn with_input_schema(mut self, schema: Value) -> Self {
        self.input_schema = schema;
        self
    }

    pub fn with_output_schema(mut self, schema: Value) -> Self {
        self.output_schema = schema;
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RunRequest {
    pub session_id: SessionId,
    pub language: Language,
    pub code: String,
    pub inputs: Map<String, Value>,
    pub timeout_ms: Option<u32>,
    pub limits: Option<SessionLimits>,
    pub return_snapshot: bool,
    pub validate_only: bool,
}

impl RunRequest {
    pub fn new(
        session_id: impl Into<String>,
        code: impl Into<String>,
    ) -> Result<Self, ErrorObject> {
        Ok(Self {
            session_id: SessionId::new(session_id)?,
            code: code.into(),
            ..Self::default()
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum RunStatus {
    #[default]
    Ok,
    ValidationError,
    RuntimeError,
    Timeout,
    Cancelled,
    ResourceExhausted,
    PermissionDenied,
    WaitingForApproval,
    Interrupted,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum Severity {
    Error,
    Warning,
    #[default]
    Info,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Span {
    pub line: u32,
    pub column: u32,
    pub end_line: Option<u32>,
    pub end_column: Option<u32>,
}

impl Default for Span {
    fn default() -> Self {
        Self {
            line: 1,
            column: 1,
            end_line: None,
            end_column: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Diagnostic {
    pub severity: Severity,
    pub code: String,
    pub message: String,
    pub hint: Option<String>,
    pub span: Option<Span>,
}

impl Diagnostic {
    pub fn error(error: &ErrorObject) -> Self {
        Self {
            severity: Severity::Error,
            code: error.code.clone(),
            message: error.message.clone(),
            hint: error.hint.clone(),
            span: error.span,
        }
    }

    pub fn warning(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            severity: Severity::Warning,
            code: code.into(),
            message: message.into(),
            hint: None,
            span: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum CallStatus {
    #[default]
    Ok,
    Error,
    Timeout,
    Denied,
    ApprovalPending,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorObject {
    pub code: String,
    pub message: String,
    pub hint: Option<String>,
    pub span: Option<Span>,
}

impl ErrorObject {
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            hint: None,
            span: None,
        }
    }

    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    pub fn with_span(mut self, span: Span) -> Self {
        self.span = Some(span);
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExternalCallRecord {
    pub name: String,
    pub side_effect: SideEffect,
    pub duration_ms: u32,
    pub status: CallStatus,
    pub request_digest: String,
    pub response_digest: Option<String>,
    pub error: Option<ErrorObject>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Metrics {
    pub duration_ms: u32,
    pub memory_peak_bytes: u64,
    pub instructions: u64,
    pub external_calls_count: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunResult {
    pub status: RunStatus,
    pub result: Option<Value>,
    pub stdout: String,
    pub stderr: String,
    pub diagnostics: Vec<Diagnostic>,
    pub external_calls: Vec<ExternalCallRecord>,
    pub snapshot_id: Option<String>,
    pub metrics: Metrics,
    pub error: Option<ErrorObject>,
}

impl RunResult {
    pub fn ok(result: Option<Value>, stdout: String, metrics: Metrics) -> Self {
        Self {
            status: RunStatus::Ok,
            result,
            stdout,
            stderr: String::new(),
            diagnostics: Vec::new(),
            external_calls: Vec::new(),
            snapshot_id: None,
            metrics,
            error: None,
        }
    }

    pub fn error(status: RunStatus, error: ErrorObject, stdout: String, metrics: Metrics) -> Self {
        Self {
            status,
            result: None,
            stdout,
            stderr: String::new(),
            diagnostics: vec![Diagnostic::error(&error)],
            external_calls: Vec::new(),
            snapshot_id: None,
            metrics,
            error: Some(error),
        }
    }
}

impl Default for RunResult {
    fn default() -> Self {
        Self::ok(None, String::new(), Metrics::default())
    }
}

#[derive(Debug, Clone)]
pub struct ToolCallContext {
    pub name: String,
    pub args: Vec<Value>,
    pub kwargs: Map<String, Value>,
}

#[derive(Debug, Clone)]
pub struct ToolError {
    pub code: String,
    pub message: String,
}

impl ToolError {
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }
}

pub type ToolResult = Result<Value, ToolError>;
pub type RuntimeFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

pub trait LanguageRuntime: fmt::Debug + Send + Sync {
    fn language(&self) -> Language;

    fn create_session(
        &self,
        session_id: SessionId,
        limits: Option<SessionLimits>,
    ) -> RuntimeFuture<'_, Result<(), ErrorObject>>;

    fn run(&self, request: RunRequest) -> RuntimeFuture<'_, RunResult>;

    fn destroy_session(
        &self,
        session_id: SessionId,
    ) -> RuntimeFuture<'_, Result<bool, ErrorObject>>;

    fn list_sessions(&self) -> RuntimeFuture<'_, Result<Vec<SessionId>, ErrorObject>>;

    fn snapshot_session(
        &self,
        session_id: SessionId,
    ) -> RuntimeFuture<'_, Result<Vec<u8>, ErrorObject>>;

    fn restore_session(
        &self,
        snapshot: Vec<u8>,
        session_id: Option<SessionId>,
    ) -> RuntimeFuture<'_, Result<SessionId, ErrorObject>>;

    fn can_restore_snapshot(&self, snapshot: &[u8]) -> bool;
}
pub type ToolFuture = Pin<Box<dyn Future<Output = ToolResult> + Send + 'static>>;
pub type ToolFn = dyn Fn(ToolCallContext) -> ToolFuture + Send + Sync + 'static;

#[derive(Clone)]
pub struct RegisteredTool {
    pub capability: Capability,
    pub async_mode: bool,
    handler: Arc<ToolFn>,
}

impl fmt::Debug for RegisteredTool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RegisteredTool")
            .field("capability", &self.capability)
            .field("async_mode", &self.async_mode)
            .finish_non_exhaustive()
    }
}

impl RegisteredTool {
    pub fn sync(
        capability: Capability,
        handler: impl Fn(ToolCallContext) -> ToolResult + Send + Sync + 'static,
    ) -> Self {
        let handler = Arc::new(move |ctx| {
            let result = handler(ctx);
            Box::pin(async move { result }) as ToolFuture
        });
        Self {
            capability,
            async_mode: false,
            handler,
        }
    }

    pub fn asynchronous(
        capability: Capability,
        handler: impl Fn(ToolCallContext) -> ToolFuture + Send + Sync + 'static,
    ) -> Self {
        Self {
            capability,
            async_mode: true,
            handler: Arc::new(handler),
        }
    }

    pub fn call(&self, ctx: ToolCallContext) -> ToolFuture {
        (self.handler)(ctx)
    }
}

#[derive(Debug, Clone, Default)]
pub struct ToolRegistry {
    tools: BTreeMap<String, RegisteredTool>,
}

impl ToolRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register(&mut self, tool: RegisteredTool) -> Result<(), ErrorObject> {
        if !is_python_identifier(&tool.capability.name) {
            return Err(ErrorObject::new(
                "INVALID_TOOL_NAME",
                format!(
                    "Capability name '{}' is not a valid Python identifier.",
                    tool.capability.name
                ),
            ));
        }
        self.tools.insert(tool.capability.name.clone(), tool);
        Ok(())
    }

    pub fn get(&self, name: &str) -> Option<&RegisteredTool> {
        self.tools.get(name)
    }

    pub fn contains(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    pub fn capabilities(&self) -> Vec<Capability> {
        self.tools
            .values()
            .map(|tool| tool.capability.clone())
            .collect()
    }

    pub fn names(&self) -> Vec<String> {
        self.tools.keys().cloned().collect()
    }
}

pub fn is_python_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first == '_' || first.is_ascii_alphabetic())
        && chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
}

pub fn digest_json(value: &Value) -> String {
    let bytes = serde_json::to_vec(value).unwrap_or_default();
    let digest = Sha3_256::digest(bytes);
    to_hex(&digest)
}

pub fn digest_bytes(bytes: &[u8]) -> String {
    let digest = Sha3_256::digest(bytes);
    to_hex(&digest)
}

fn to_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for &byte in bytes {
        output.push(HEX[(byte >> 4) as usize] as char);
        output.push(HEX[(byte & 0x0f) as usize] as char);
    }
    output
}

pub fn now_unix_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
        .unwrap_or(0)
}

/// Truncate `text` so that its UTF-8 encoded length is at most `max_bytes`,
/// always keeping the result on a valid UTF-8 character boundary.
///
/// Returns `true` when truncation occurred.
pub fn truncate_utf8(text: &mut String, max_bytes: usize) -> bool {
    if text.len() <= max_bytes {
        return false;
    }
    let mut boundary = max_bytes;
    while boundary > 0 && !text.is_char_boundary(boundary) {
        boundary -= 1;
    }
    text.truncate(boundary);
    true
}

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

    #[test]
    fn validates_session_ids() {
        assert!(SessionId::new("agent-123_ok").is_ok());
        assert!(SessionId::new("bad/slash").is_err());
        assert!(SessionId::new("").is_err());
    }

    #[test]
    fn validates_python_identifiers() {
        assert!(is_python_identifier("fetch_json"));
        assert!(!is_python_identifier("1_fetch"));
        assert!(!is_python_identifier("fetch-json"));
    }

    #[test]
    fn truncates_on_utf8_boundary() {
        let mut text = "héllo".to_owned();
        // 'é' is 2 bytes; cutting at byte 2 lands inside it.
        let truncated = truncate_utf8(&mut text, 2);
        assert!(truncated);
        assert_eq!(text, "h");

        let mut keep = "abc".to_owned();
        assert!(!truncate_utf8(&mut keep, 10));
        assert_eq!(keep, "abc");
    }
}