glass-browser 0.2.3

Local, revision-safe Chrome automation runtime for agents, with semantic observation, verified workflows, MCP, CLI, TUI, and Rust APIs
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
//! Transport-neutral Glass request and response envelopes.
//!
//! MCP keeps its JSON-RPC framing, but daemon clients and embedded callers use
//! these envelopes for the operation payload. The envelope is intentionally
//! small: transport-specific framing, streaming, and authentication remain
//! outside this contract.

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

/// Version of the canonical Glass operation envelope.
pub const GLASS_PROTOCOL_VERSION: u32 = 1;
const MAX_ID_BYTES: usize = 128;
const MAX_OPERATION_BYTES: usize = 96;
const MAX_ERROR_CODE_BYTES: usize = 64;
const MAX_MESSAGE_BYTES: usize = 512;
const MAX_DEADLINE_MS: u64 = 15 * 60 * 1_000;

/// Canonical transport operation for browser-free Task Protocol compilation.
pub const TASK_COMPILE_OPERATION: &str = "task.compile";

/// Typed payload carried by a `task.compile` request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TaskCompilePayload {
    pub task: crate::task_protocol::GlassTask,
}

impl TaskCompilePayload {
    /// Validate the authored task before compiler dispatch.
    pub fn validate(&self) -> Result<(), ProtocolError> {
        self.task
            .validate()
            .map_err(|error| ProtocolError::InvalidField(error.to_string()))
    }
}

/// Typed successful result for a `task.compile` operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TaskCompileResult {
    pub plan: crate::task_compiler::TaskExecutionPlan,
}

/// Typed successful result for browser-free Task Protocol validation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TaskValidationResult {
    pub valid: bool,
    pub schema_version: u32,
    pub task: crate::task_protocol::TaskKind,
}

impl TaskCompileResult {
    /// Validate the embedded deterministic execution plan.
    pub fn validate(&self) -> Result<(), ProtocolError> {
        self.plan
            .validate()
            .map_err(|error| ProtocolError::InvalidField(error.to_string()))
    }
}

/// A request-independent mutation lease reference.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MutationLeaseRef {
    pub session_id: String,
    pub token: String,
}

/// Canonical operation request shared by supported transports.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GlassRequest {
    pub protocol_version: u32,
    pub request_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correlation_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mutation_lease: Option<MutationLeaseRef>,
    pub operation: String,
    pub payload: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deadline_ms: Option<u64>,
}

impl GlassRequest {
    /// Validate protocol version, identifiers, operation bounds, and deadline.
    pub fn validate(&self) -> Result<(), ProtocolError> {
        if self.protocol_version != GLASS_PROTOCOL_VERSION {
            return Err(ProtocolError::UnsupportedVersion(self.protocol_version));
        }
        validate_identifier(&self.request_id, "requestId")?;
        if let Some(correlation_id) = &self.correlation_id {
            validate_identifier(correlation_id, "correlationId")?;
        }
        if let Some(session_id) = &self.session_id {
            validate_identifier(session_id, "sessionId")?;
        }
        if let Some(lease) = &self.mutation_lease {
            validate_identifier(&lease.session_id, "mutationLease.sessionId")?;
            validate_identifier(&lease.token, "mutationLease.token")?;
        }
        if self.operation.is_empty() || self.operation.len() > MAX_OPERATION_BYTES {
            return Err(ProtocolError::InvalidField(
                "operation must be a bounded non-empty string".into(),
            ));
        }
        if self.operation.chars().any(char::is_whitespace) {
            return Err(ProtocolError::InvalidField(
                "operation must not contain whitespace".into(),
            ));
        }
        if let Some(deadline_ms) = self.deadline_ms
            && !(1..=MAX_DEADLINE_MS).contains(&deadline_ms)
        {
            return Err(ProtocolError::InvalidField(format!(
                "deadlineMs must be 1..={MAX_DEADLINE_MS}"
            )));
        }
        Ok(())
    }

    /// Decode and validate a typed `task.compile` payload.
    pub fn decode_task_compile(&self) -> Result<TaskCompilePayload, ProtocolError> {
        self.validate()?;
        if self.operation != TASK_COMPILE_OPERATION {
            return Err(ProtocolError::InvalidField(format!(
                "expected operation {TASK_COMPILE_OPERATION}"
            )));
        }
        let payload: TaskCompilePayload =
            serde_json::from_value(self.payload.clone()).map_err(|error| {
                ProtocolError::InvalidField(format!("task.compile payload: {error}"))
            })?;
        payload.validate()?;
        Ok(payload)
    }
}

/// Decode and compile a `task.compile` request without browser access.
pub fn compile_task_request(
    request: &GlassRequest,
) -> Result<crate::task_compiler::TaskExecutionPlan, ProtocolError> {
    let payload = request.decode_task_compile()?;
    crate::task_compiler::compile_task(&payload.task)
        .map_err(|error| ProtocolError::InvalidField(error.to_string()))
}

/// Decode and compile a `task.compile` request into a typed response payload.
pub fn compile_task_result(request: &GlassRequest) -> Result<TaskCompileResult, ProtocolError> {
    Ok(TaskCompileResult {
        plan: compile_task_request(request)?,
    })
}

/// Canonical operation response shared by supported transports.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GlassResponse {
    pub protocol_version: u32,
    pub request_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correlation_id: Option<String>,
    pub ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<GlassError>,
}

impl GlassResponse {
    /// Validate envelope identity and the mutually exclusive result/error form.
    pub fn validate(&self) -> Result<(), ProtocolError> {
        if self.protocol_version != GLASS_PROTOCOL_VERSION {
            return Err(ProtocolError::UnsupportedVersion(self.protocol_version));
        }
        validate_identifier(&self.request_id, "requestId")?;
        if let Some(correlation_id) = &self.correlation_id {
            validate_identifier(correlation_id, "correlationId")?;
        }
        match (self.ok, self.result.is_some(), self.error.is_some()) {
            (true, true, false) | (false, false, true) => Ok(()),
            _ => Err(ProtocolError::InvalidField(
                "ok responses require result and error responses require error".into(),
            )),
        }
    }

    /// Decode and validate a successful typed `task.compile` result.
    pub fn decode_task_compile_result(&self) -> Result<TaskCompileResult, ProtocolError> {
        self.validate()?;
        if !self.ok {
            return Err(ProtocolError::InvalidField(
                "task.compile result requires a successful response".into(),
            ));
        }
        let value = self
            .result
            .clone()
            .ok_or_else(|| ProtocolError::InvalidField("task.compile result is missing".into()))?;
        let result: TaskCompileResult = serde_json::from_value(value).map_err(|error| {
            ProtocolError::InvalidField(format!("task.compile result: {error}"))
        })?;
        result.validate()?;
        Ok(result)
    }
}

/// Phase in which a public operation stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum ErrorPhase {
    #[default]
    Preflight,
    Dispatch,
    PostDispatch,
    Verification,
    Reconciliation,
}

/// Stable retry classification for agent recovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum RetryClassification {
    SafeImmediate,
    #[default]
    SafeAfterReobserve,
    SafeAfterReconcile,
    UnsafeUntilReconciled,
    RequiresUserDecision,
    NotRetryable,
    Unknown,
}

/// Bounded recovery guidance attached to every canonical failure.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RetryGuidance {
    pub classification: RetryClassification,
    pub recommended_operation: String,
}

impl Default for RetryGuidance {
    fn default() -> Self {
        Self {
            classification: RetryClassification::SafeAfterReobserve,
            recommended_operation: "inspect_page".into(),
        }
    }
}

/// Structured failure that can be carried across transports without parsing text.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GlassError {
    pub code: String,
    #[serde(default)]
    pub phase: ErrorPhase,
    pub message: String,
    #[serde(default)]
    pub mutation_possible: bool,
    #[serde(default)]
    pub retry: RetryGuidance,
    /// Kept as a tolerated compatibility field for pre-0.2.2 clients.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retryable: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Value>,
}

impl GlassError {
    /// Validate bounded, non-empty diagnostic fields.
    pub fn validate(&self) -> Result<(), ProtocolError> {
        if self.code.is_empty() || self.code.len() > MAX_ERROR_CODE_BYTES {
            return Err(ProtocolError::InvalidField(
                "error code must be a bounded non-empty string".into(),
            ));
        }
        if self.message.is_empty() || self.message.len() > MAX_MESSAGE_BYTES {
            return Err(ProtocolError::InvalidField(
                "error message must be a bounded non-empty string".into(),
            ));
        }
        validate_identifier(
            &self.retry.recommended_operation,
            "retry.recommendedOperation",
        )?;
        Ok(())
    }
}

/// Validation failure for the canonical protocol envelope.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProtocolError {
    UnsupportedVersion(u32),
    InvalidField(String),
}

impl std::fmt::Display for ProtocolError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnsupportedVersion(version) => {
                write!(formatter, "unsupported Glass protocol version {version}")
            }
            Self::InvalidField(detail) => formatter.write_str(detail),
        }
    }
}

impl std::error::Error for ProtocolError {}

fn validate_identifier(value: &str, field: &str) -> Result<(), ProtocolError> {
    if value.is_empty() || value.len() > MAX_ID_BYTES || value.chars().any(char::is_whitespace) {
        return Err(ProtocolError::InvalidField(format!(
            "{field} must be a bounded non-whitespace identifier"
        )));
    }
    Ok(())
}

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

    fn request() -> GlassRequest {
        GlassRequest {
            protocol_version: GLASS_PROTOCOL_VERSION,
            request_id: "request-1".into(),
            correlation_id: Some("run-1".into()),
            session_id: Some("session-1".into()),
            mutation_lease: Some(MutationLeaseRef {
                session_id: "session-1".into(),
                token: "lease-1".into(),
            }),
            operation: "browser.observe".into(),
            payload: serde_json::json!({"level": "interactive"}),
            deadline_ms: Some(5_000),
        }
    }

    #[test]
    fn request_round_trips_and_validates() {
        let request = request();
        request.validate().unwrap();
        let value = serde_json::to_value(&request).unwrap();
        assert_eq!(value["protocolVersion"], 1);
        assert_eq!(value["mutationLease"]["sessionId"], "session-1");
        let decoded: GlassRequest = serde_json::from_value(value).unwrap();
        assert_eq!(decoded, request);
    }

    #[test]
    fn response_requires_exactly_one_outcome() {
        let response = GlassResponse {
            protocol_version: GLASS_PROTOCOL_VERSION,
            request_id: "request-1".into(),
            correlation_id: None,
            ok: false,
            result: None,
            error: Some(GlassError {
                code: "target.stale".into(),
                phase: ErrorPhase::Preflight,
                message: "a mutation lease is required".into(),
                mutation_possible: false,
                retry: RetryGuidance {
                    classification: RetryClassification::SafeAfterReobserve,
                    recommended_operation: "inspect_page".into(),
                },
                retryable: Some(true),
                details: None,
            }),
        };
        response.validate().unwrap();
        let mut invalid = response.clone();
        invalid.ok = true;
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn bounds_and_unknown_fields_fail_closed() {
        let mut request = request();
        request.operation = "bad operation".into();
        assert!(request.validate().is_err());
        let unknown = serde_json::json!({
            "protocolVersion": 1,
            "requestId": "request-1",
            "operation": "browser.observe",
            "payload": {},
            "future": true
        });
        assert!(serde_json::from_value::<GlassRequest>(unknown).is_err());
    }

    #[test]
    fn task_compile_boundary_decodes_and_compiles_without_browser_state() {
        let task = serde_json::json!({
            "schemaVersion": 1,
            "task": "region.extract",
            "scope": {"regionName": "Checkout"},
            "limits": {"maxActions": 8, "timeoutMs": 5000, "maxItems": 32},
            "risk": "readOnly"
        });
        let request = GlassRequest {
            protocol_version: GLASS_PROTOCOL_VERSION,
            request_id: "compile-1".into(),
            correlation_id: None,
            session_id: None,
            mutation_lease: None,
            operation: TASK_COMPILE_OPERATION.into(),
            payload: serde_json::json!({"task": task}),
            deadline_ms: None,
        };
        let plan = compile_task_request(&request).unwrap();
        assert_eq!(plan.task, crate::task_protocol::TaskKind::RegionExtract);
        assert_eq!(plan.scope.region_name.as_deref(), Some("Checkout"));
        assert_eq!(plan.limits.max_actions, 8);
        assert_eq!(
            plan.revision,
            crate::task_protocol::TaskRevisionPolicy::Exact
        );

        let mut wrong_operation = request.clone();
        wrong_operation.operation = "browser.observe".into();
        assert!(wrong_operation.decode_task_compile().is_err());

        let mut unknown = request.clone();
        unknown.payload["futureField"] = true.into();
        assert!(unknown.decode_task_compile().is_err());

        let mut invalid = request;
        invalid.payload["task"]["task"] = "form.fill".into();
        assert!(compile_task_request(&invalid).is_err());
    }

    #[test]
    fn task_compile_result_round_trips_through_success_response() {
        let request = GlassRequest {
            protocol_version: GLASS_PROTOCOL_VERSION,
            request_id: "compile-2".into(),
            correlation_id: None,
            session_id: None,
            mutation_lease: None,
            operation: TASK_COMPILE_OPERATION.into(),
            payload: serde_json::json!({
                "task": {
                    "schemaVersion": 1,
                    "task": "field.read",
                    "scope": {"entityKind": "field", "entityName": "Email"},
                    "limits": {"maxActions": 4, "timeoutMs": 2000, "maxItems": 1},
                    "risk": "readOnly"
                }
            }),
            deadline_ms: None,
        };
        let result = compile_task_result(&request).unwrap();
        let response = GlassResponse {
            protocol_version: GLASS_PROTOCOL_VERSION,
            request_id: request.request_id.clone(),
            correlation_id: None,
            ok: true,
            result: Some(serde_json::to_value(&result).unwrap()),
            error: None,
        };
        assert_eq!(response.decode_task_compile_result().unwrap(), result);

        let mut unknown = response.clone();
        unknown.result.as_mut().unwrap()["futureField"] = true.into();
        assert!(unknown.decode_task_compile_result().is_err());

        let mut failure = response;
        failure.ok = false;
        failure.result = None;
        failure.error = Some(GlassError {
            code: "task.invalid".into(),
            phase: ErrorPhase::Preflight,
            message: "invalid task".into(),
            mutation_possible: false,
            retry: RetryGuidance::default(),
            retryable: None,
            details: None,
        });
        assert!(failure.decode_task_compile_result().is_err());
    }

    #[test]
    fn additive_response_fields_are_tolerated() {
        let response: GlassResponse = serde_json::from_value(serde_json::json!({
            "protocolVersion": 1,
            "requestId": "request-1",
            "ok": false,
            "error": {
                "code": "target.stale",
                "message": "stale",
                "retryable": true,
                "future": "ignored"
            },
            "future": true
        }))
        .unwrap();
        assert_eq!(
            response.error.unwrap().retry.classification,
            RetryClassification::SafeAfterReobserve
        );
    }
}