apoc 0.9.1

Agentic process control for LLMs
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
//! Durable non-pausing logpoints and expression watches.

use std::time::Duration;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::{DebuggerManager, DebuggerSession, now_ms};

const TAP_SENTINEL_PREFIX: &str = "__apoc_tap:";
const WATCH_POLL_MS: u64 = 250;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTap {
    pub id: String,
    pub session_id: String,
    pub backend_id: Option<String>,
    pub file: String,
    pub line: u64,
    pub expression: String,
    pub url_regex: String,
    pub resolved: bool,
    pub enabled: bool,
    pub hits: u64,
    pub created_at: u64,
    pub updated_at: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTapHit {
    pub id: String,
    pub tap_id: String,
    pub session_id: String,
    pub at: u64,
    pub value: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTapEvent {
    pub sequence: u64,
    pub id: String,
    pub tap_id: String,
    pub at: u64,
    pub value: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWatch {
    pub id: String,
    pub session_id: String,
    pub target: String,
    pub expression: String,
    pub access: String,
    pub enabled: bool,
    pub hits: u64,
    pub last_value: Option<String>,
    pub last_error: Option<String>,
    pub created_at: u64,
    pub updated_at: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWatchHit {
    pub id: String,
    pub watch_id: String,
    pub session_id: String,
    pub at: u64,
    pub old_value: Option<String>,
    pub new_value: Option<String>,
    pub error: Option<String>,
}

impl DebuggerManager {
    pub async fn tap_add(
        &self,
        session_id: &str,
        file: String,
        line: u64,
        expression: String,
        url_regex: Option<String>,
    ) -> Result<DebuggerTap, String> {
        if line == 0 {
            return Err("Debugger tap line must be at least 1".to_string());
        }
        if expression.trim().is_empty() {
            return Err("Debugger tap expression cannot be empty".to_string());
        }
        let session = self.session(session_id).await?;
        let at = now_ms();
        let mut tap = DebuggerTap {
            id: uuid::Uuid::now_v7().to_string(),
            session_id: session_id.to_string(),
            backend_id: None,
            file: file.clone(),
            line,
            expression,
            url_regex: url_regex.unwrap_or_else(|| suffix_url_regex(&file)),
            resolved: false,
            enabled: true,
            hits: 0,
            created_at: at,
            updated_at: at,
        };
        let result = install_tap(&session, &tap).await?;
        tap.backend_id = result
            .get("breakpointId")
            .and_then(Value::as_str)
            .map(ToString::to_string);
        tap.resolved = result
            .get("locations")
            .and_then(Value::as_array)
            .is_some_and(|locations| !locations.is_empty());
        self.store.put_debugger_tap(&tap)?;
        Ok(tap)
    }

    pub fn tap_list(&self, session_id: &str) -> Result<Vec<DebuggerTap>, String> {
        self.store.debugger_taps(session_id)
    }

    pub fn tap_hits(
        &self,
        session_id: &str,
        tap_id: &str,
        limit: usize,
    ) -> Result<Vec<DebuggerTapHit>, String> {
        let tap = self
            .store
            .debugger_tap(tap_id)?
            .ok_or_else(|| format!("Debugger tap \"{tap_id}\" not found"))?;
        if tap.session_id != session_id {
            return Err(format!(
                "Debugger tap \"{tap_id}\" does not belong to session \"{session_id}\""
            ));
        }
        self.store.debugger_tap_hits(tap_id, limit)
    }

    pub async fn tap_remove(&self, session_id: &str, tap_id: &str) -> Result<DebuggerTap, String> {
        let mut tap = self
            .store
            .debugger_tap(tap_id)?
            .ok_or_else(|| format!("Debugger tap \"{tap_id}\" not found"))?;
        if tap.session_id != session_id {
            return Err(format!(
                "Debugger tap \"{tap_id}\" does not belong to session \"{session_id}\""
            ));
        }
        if let Some(backend_id) = tap.backend_id.as_deref()
            && let Ok(session) = self.session(session_id).await
        {
            let _ = session
                .send(
                    "Debugger.removeBreakpoint",
                    json!({"breakpointId":backend_id}),
                )
                .await;
        }
        tap.enabled = false;
        tap.backend_id = None;
        tap.updated_at = now_ms();
        self.store.put_debugger_tap(&tap)?;
        Ok(tap)
    }

    pub(super) async fn restore_taps(
        &self,
        session: &std::sync::Arc<DebuggerSession>,
    ) -> Result<(), String> {
        for mut tap in self.store.debugger_taps(&session.id)? {
            if !tap.enabled {
                continue;
            }
            let result = install_tap(session, &tap).await?;
            tap.backend_id = result
                .get("breakpointId")
                .and_then(Value::as_str)
                .map(ToString::to_string);
            tap.resolved = result
                .get("locations")
                .and_then(Value::as_array)
                .is_some_and(|locations| !locations.is_empty());
            tap.updated_at = now_ms();
            self.store.put_debugger_tap(&tap)?;
        }
        Ok(())
    }

    pub async fn watch_add(
        &self,
        session_id: &str,
        target: String,
        expression: Option<String>,
        access: String,
    ) -> Result<DebuggerWatch, String> {
        self.session(session_id).await?;
        if target.trim().is_empty() {
            return Err("Debugger watch target cannot be empty".to_string());
        }
        if !matches!(access.as_str(), "read" | "write" | "rw") {
            return Err("Debugger watch access must be read, write, or rw".to_string());
        }
        let expression = expression.unwrap_or_else(|| target.clone());
        if expression.trim().is_empty() {
            return Err("Debugger watch expression cannot be empty".to_string());
        }
        let at = now_ms();
        let watch = DebuggerWatch {
            id: uuid::Uuid::now_v7().to_string(),
            session_id: session_id.to_string(),
            target,
            expression,
            access,
            enabled: true,
            hits: 0,
            last_value: None,
            last_error: None,
            created_at: at,
            updated_at: at,
        };
        self.store.put_debugger_watch(&watch)?;
        self.spawn_watch_worker(session_id).await;
        Ok(watch)
    }

    pub fn watch_list(&self, session_id: &str) -> Result<Vec<DebuggerWatch>, String> {
        self.store.debugger_watches(session_id)
    }

    pub fn watch_hits(
        &self,
        session_id: &str,
        watch_id: &str,
        limit: usize,
    ) -> Result<Vec<DebuggerWatchHit>, String> {
        let watch = self
            .store
            .debugger_watch(watch_id)?
            .ok_or_else(|| format!("Debugger watch \"{watch_id}\" not found"))?;
        if watch.session_id != session_id {
            return Err(format!(
                "Debugger watch \"{watch_id}\" does not belong to session \"{session_id}\""
            ));
        }
        self.store.debugger_watch_hits(watch_id, limit)
    }

    pub async fn watch_remove(
        &self,
        session_id: &str,
        watch_id: &str,
    ) -> Result<DebuggerWatch, String> {
        let mut watch = self
            .store
            .debugger_watch(watch_id)?
            .ok_or_else(|| format!("Debugger watch \"{watch_id}\" not found"))?;
        if watch.session_id != session_id {
            return Err(format!(
                "Debugger watch \"{watch_id}\" does not belong to session \"{session_id}\""
            ));
        }
        watch.enabled = false;
        watch.updated_at = now_ms();
        self.store.put_debugger_watch(&watch)?;
        Ok(watch)
    }

    pub(super) async fn resume_watch_worker(&self, session_id: &str) {
        if self
            .store
            .debugger_watches(session_id)
            .is_ok_and(|watches| watches.iter().any(|watch| watch.enabled))
        {
            self.spawn_watch_worker(session_id).await;
        }
    }

    async fn spawn_watch_worker(&self, session_id: &str) {
        self.stop_watch_worker(session_id).await;
        let manager = self.clone();
        let session_id = session_id.to_string();
        let task_session = session_id.clone();
        let task = tokio::spawn(async move {
            while let Ok(watches) = manager.store.debugger_watches(&task_session) {
                let watches = watches
                    .into_iter()
                    .filter(|watch| watch.enabled)
                    .collect::<Vec<_>>();
                if watches.is_empty() {
                    break;
                }
                let session = match manager.session(&task_session).await {
                    Ok(session) => session,
                    Err(_) => break,
                };
                for watch in watches {
                    let result = evaluate_watch(&session, &watch.expression).await;
                    let (new_value, error) = match result {
                        Ok(value) => (Some(value), None),
                        Err(error) => (None, Some(error)),
                    };
                    if watch.last_value == new_value && watch.last_error == error {
                        continue;
                    }
                    let hit = DebuggerWatchHit {
                        id: uuid::Uuid::now_v7().to_string(),
                        watch_id: watch.id.clone(),
                        session_id: task_session.clone(),
                        at: now_ms(),
                        old_value: watch.last_value.clone(),
                        new_value,
                        error,
                    };
                    let _ = manager.store.record_debugger_watch_hit(&hit);
                }
                tokio::time::sleep(Duration::from_millis(WATCH_POLL_MS)).await;
            }
        });
        self.watch_tasks.lock().await.insert(session_id, task);
    }

    async fn stop_watch_worker(&self, session_id: &str) {
        if let Some(task) = self.watch_tasks.lock().await.remove(session_id) {
            task.abort();
        }
    }
}

async fn install_tap(session: &DebuggerSession, tap: &DebuggerTap) -> Result<Value, String> {
    session
        .send(
            "Debugger.setBreakpointByUrl",
            json!({
                "lineNumber":tap.line - 1,
                "columnNumber":0,
                "urlRegex":tap.url_regex,
                "condition":tap_condition(&tap.id, &tap.expression)
            }),
        )
        .await
}

async fn evaluate_watch(session: &DebuggerSession, expression: &str) -> Result<String, String> {
    let result = session
        .send(
            "Runtime.evaluate",
            json!({
                "expression":expression,
                "returnByValue":true,
                "awaitPromise":true,
                "silent":true
            }),
        )
        .await?;
    if let Some(details) = result.get("exceptionDetails") {
        return Err(details
            .pointer("/exception/description")
            .and_then(Value::as_str)
            .or_else(|| details.get("text").and_then(Value::as_str))
            .unwrap_or("Watch expression failed")
            .to_string());
    }
    let object = result.get("result").unwrap_or(&result);
    Ok(remote_value(object))
}

pub(super) fn parse_tap_sentinel(params: &Value) -> Option<(String, String)> {
    let args = params.get("args")?.as_array()?;
    let sentinel = args.first()?.get("value")?.as_str()?;
    let tap_id = sentinel.strip_prefix(TAP_SENTINEL_PREFIX)?.to_string();
    if tap_id.is_empty() {
        return None;
    }
    let value = args.get(1).map_or_else(String::new, remote_value);
    Some((tap_id, value))
}

fn tap_condition(tap_id: &str, expression: &str) -> String {
    let sentinel = serde_json::to_string(&format!("{TAP_SENTINEL_PREFIX}{tap_id}"))
        .expect("tap sentinel is serializable");
    format!(
        "void console.log({sentinel},(()=>{{try{{return ({expression})}}catch(e){{return 'tap-expr-error:'+e}}}})())"
    )
}

fn suffix_url_regex(file: &str) -> String {
    let cleaned = file
        .strip_prefix("./")
        .or_else(|| file.strip_prefix('/'))
        .unwrap_or(file);
    let mut escaped = String::with_capacity(cleaned.len());
    for character in cleaned.chars() {
        if matches!(
            character,
            '.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '\\'
        ) {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}

fn remote_value(value: &Value) -> String {
    if let Some(value) = value.get("value") {
        return match value {
            Value::String(value) => value.clone(),
            value => serde_json::to_string(value).unwrap_or_default(),
        };
    }
    value
        .get("unserializableValue")
        .and_then(Value::as_str)
        .or_else(|| value.get("description").and_then(Value::as_str))
        .or_else(|| value.get("type").and_then(Value::as_str))
        .unwrap_or_default()
        .to_string()
}

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

    #[test]
    fn tap_condition_is_non_pausing_and_guards_expression_errors() {
        let condition = tap_condition("tap-1", "value * 2");
        assert!(condition.starts_with("void console.log("));
        assert!(condition.contains("__apoc_tap:tap-1"));
        assert!(condition.contains("tap-expr-error:"));
    }

    #[test]
    fn parses_tap_sentinel_values_and_rejects_user_console() {
        let params = json!({"args":[
            {"type":"string","value":"__apoc_tap:tap-1"},
            {"type":"number","value":42}
        ]});
        assert_eq!(
            parse_tap_sentinel(&params),
            Some(("tap-1".to_string(), "42".to_string()))
        );
        assert!(parse_tap_sentinel(&json!({"args":[{"value":"hello"}]})).is_none());
    }

    #[test]
    fn source_suffix_becomes_a_literal_url_regex() {
        assert_eq!(suffix_url_regex("./src/a+b.ts"), "src/a\\+b\\.ts");
    }
}