superdoc-sdk 2.25.0

Beta Rust SDK for the SuperDoc document runtime
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
639
640
641
642
643
644
645
646
647
648
use crate::{
    generated::types::{
        DocCapabilitiesGetBoundParams, DocCapabilitiesGetResult, DocPresetDispatchBoundParams,
        DocPresetDispatchResult, DocPresetGetSystemPromptParams, DocPresetGetSystemPromptResult,
        DocPresetGetToolsParams, DocPresetGetToolsResult,
    },
    wire::Presence,
    Document, Error, InvokeOptions, Result,
};
use serde::Deserialize;
use serde_json::Value;
use std::sync::OnceLock;

pub(crate) fn prepare_core_dispatch(
    tool_name: &str,
    args: &mut Value,
    options: &mut InvokeOptions,
    configured: Option<&DocPresetGetToolsParams>,
) -> Result<()> {
    if !args.is_object() {
        let mut error = Error::new("INVALID_ARGUMENT", "tool arguments must be an object");
        error.details = Some(Box::new(serde_json::json!({"toolName": tool_name})));
        return Err(error);
    }
    let authority = action_policy()?;
    validate_core_policy(tool_name, args, configured, authority)?;
    let Some(tool) = authority
        .preflight
        .tools
        .iter()
        .find(|tool| tool.name == tool_name)
    else {
        let mut error = Error::new("TOOL_DISPATCH_NOT_FOUND", "Unknown Core tool");
        error.host_message = Some(format!("Unknown tool: {tool_name}").into());
        error.details = Some(Box::new(
            serde_json::json!({"toolName":tool_name,"preset":"core"}),
        ));
        return Err(error);
    };
    validate_core_arguments(tool, args, &authority.preflight)?;
    if options.dry_run == Some(true) {
        let mut error = Error::new(
            "CAPABILITY_UNSUPPORTED",
            "the core preset dispatcher does not support dryRun previews",
        );
        error.operation_id = Some("doc.preset.dispatch".into());
        return Err(error);
    }
    if options
        .change_mode
        .as_deref()
        .is_some_and(|mode| !["direct", "tracked"].contains(&mode))
    {
        return Err(Error::new(
            "INVALID_ARGUMENT",
            "core dispatch change mode must be direct or tracked",
        ));
    }
    let explicit = (tool_name == "superdoc_perform_action")
        .then(|| args.get("expectedRevision"))
        .flatten();
    let revision = match explicit {
        Some(value) => value.as_str(),
        None => options.expected_revision.as_deref(),
    };
    if revision.is_some() || explicit.is_some() {
        let revision = revision.filter(|revision| !revision.is_empty());
        let Some(revision) = revision else {
            let mut error = Error::new(
                "INVALID_ARGUMENT",
                "expectedRevision must be a non-empty live revision or a non-negative safe integer.",
            );
            error.details = Some(Box::new(
                serde_json::json!({"preset":"core","option":"expectedRevision"}),
            ));
            return Err(error);
        };
        options.expected_revision = Some(revision.to_owned());
    }
    Ok(())
}

pub(crate) fn stale_revision_message(action: &str) -> String {
    format!("{action}: expectedRevision is stale. Inspect this live document again before editing.")
}

pub(crate) fn stale_action_revision_receipt(
    args: &Value,
    live_revision: &str,
    configured: Option<&DocPresetGetToolsParams>,
) -> Result<Value> {
    let action = args.get("action").and_then(Value::as_str);
    let intent = action.unwrap_or("superdoc_perform_action");
    let mut receipt = serde_json::json!({
        "status": "failed",
        "intent": intent,
        "preSnapshot": { "revision": live_revision },
        "selectedTargets": [],
        "executedOperations": [],
        "verification": [],
        "errors": [{
            "code": "REVISION_CONFLICT",
            "message": stale_revision_message(intent),
            "recovery": { "kind": "reinspect" },
        }],
    });
    let enforcing = configured.is_some_and(
        |configured| matches!(&configured.enforce_change_mode, Presence::Present(mode) if mode == "tracked"),
    );
    if enforcing {
        let requested_tracked = args.get("changeMode").and_then(Value::as_str) == Some("tracked");
        let actions = &action_policy()?.actions;
        let disposition = action.and_then(|action| {
            actions
                .iter()
                .find(|entry| entry.name == action)
                .map(|entry| entry.disposition.as_str())
        });
        let (change_mode, forced) = match disposition {
            Some("tracked") => ("tracked", !requested_tracked),
            Some(_) => ("direct", requested_tracked),
            None => (
                if requested_tracked {
                    "tracked"
                } else {
                    "direct"
                },
                false,
            ),
        };
        receipt["changeMode"] = Value::from(change_mode);
        receipt["changeModeForced"] = Value::from(forced);
    }
    Ok(receipt)
}

fn invalid_core_arguments(message: String, details: Value) -> Error {
    let mut error = Error::new("INVALID_ARGUMENT", "Core tool arguments are invalid");
    error.host_message = Some(message.into());
    error.details = Some(Box::new(details));
    error
}

fn trim_core_csv_name<'a>(name: &'a str, authority: &CorePreflight) -> &'a str {
    name.trim_matches(|character: char| authority.trim_code_points.contains(&(character as u32)))
}

fn csv_names<'a>(value: &'a Presence<String>, authority: &CorePreflight) -> Vec<&'a str> {
    match value {
        Presence::Missing => Vec::new(),
        Presence::Present(value) => value
            .split(',')
            .map(|name| trim_core_csv_name(name, authority))
            .filter(|name| !name.is_empty())
            .collect(),
    }
}

fn validate_core_policy(
    tool_name: &str,
    args: &Value,
    configured: Option<&DocPresetGetToolsParams>,
    authority: &ActionPolicy,
) -> Result<()> {
    let Some(configured) = configured else {
        return Ok(());
    };
    let enforcing = match &configured.enforce_change_mode {
        Presence::Missing => false,
        Presence::Present(mode) if mode == "tracked" => true,
        Presence::Present(mode) => {
            return Err(invalid_core_arguments(
                format!(
                    "enforceChangeMode: only \"tracked\" is supported; got {}.",
                    serde_json::json!(mode)
                ),
                serde_json::json!({"enforceChangeMode":mode,"supported":["tracked"]}),
            ))
        }
    };
    let allow = csv_names(&configured.allow_direct_actions, &authority.preflight);
    if !configured.allow_direct_actions.is_missing() && !enforcing {
        return Err(invalid_core_arguments(
            "allowDirectActions requires enforceChangeMode: \"tracked\"; without enforcement every action already runs as requested.".into(),
            serde_json::json!({"allowDirectActions":allow})));
    }
    if enforcing
        && authority
            .preflight
            .enforcement_side_doors
            .iter()
            .any(|name| name == tool_name)
    {
        return Err(invalid_core_arguments(
            format!("{tool_name} bypasses the tracked-changes policy and is refused under enforceChangeMode: \"tracked\"."),
            serde_json::json!({"toolName":tool_name,"reason":"enforce-change-mode"})));
    }
    if tool_name == "superdoc_perform_action" {
        if let Some(action) = args.get("action").and_then(Value::as_str) {
            if csv_names(&configured.exclude_actions, &authority.preflight).contains(&action) {
                return Err(invalid_core_arguments(
                    format!("Action {action} is excluded by configuration."),
                    serde_json::json!({"toolName":tool_name,"action":action,"excluded":true,"reason":"excluded"}),
                ));
            }
            if enforcing
                && !allow.contains(&"*")
                && !allow.contains(&action)
                && authority
                    .actions
                    .iter()
                    .any(|entry| entry.name == action && entry.disposition == "direct")
            {
                return Err(invalid_core_arguments(
                    format!("Action {action} edits the document directly and is refused under enforceChangeMode: \"tracked\". Pass it in allowDirectActions to permit it."),
                    serde_json::json!({"toolName":tool_name,"action":action,"excluded":true,"reason":"direct-only"})));
            }
        }
    }
    Ok(())
}

fn meaningful_argument_key(key: &str, authority: &CorePreflight) -> bool {
    key.chars().any(|character| {
        let point = character as u32;
        let at = authority
            .letter_number_ranges
            .partition_point(|range| range[1] < point);
        authority
            .letter_number_ranges
            .get(at)
            .is_some_and(|range| range[0] <= point)
    })
}

fn validate_core_arguments(tool: &CoreTool, args: &Value, authority: &CorePreflight) -> Result<()> {
    let unknown = args
        .as_object()
        .expect("Core arguments were checked")
        .keys()
        .filter(|name| !tool.known_keys.contains(name) && meaningful_argument_key(name, authority))
        .cloned()
        .collect::<Vec<_>>();
    if !unknown.is_empty() {
        let retired = unknown
            .iter()
            .filter(|name| authority.retired_arguments.contains_key(*name))
            .cloned()
            .collect::<Vec<_>>();
        let message = if retired.is_empty() {
            format!(
                "Unknown argument(s) for {}: {}",
                tool.name,
                unknown.join(", ")
            )
        } else {
            retired
                .iter()
                .map(|name| authority.retired_arguments[name].as_str())
                .collect::<Vec<_>>()
                .join(" ")
        };
        let mut details = serde_json::json!({"toolName":tool.name,"unknownKeys":unknown,"knownKeys":tool.known_keys});
        if !retired.is_empty() {
            details["retiredKeys"] = serde_json::json!(retired);
        }
        return Err(invalid_core_arguments(message, details));
    }
    let missing = tool
        .required_keys
        .iter()
        .filter(|name| args.get(name.as_str()).is_none_or(Value::is_null))
        .collect::<Vec<_>>();
    if !missing.is_empty() {
        return Err(invalid_core_arguments(
            format!(
                "Missing required argument(s) for {}: {}",
                tool.name,
                missing
                    .iter()
                    .map(|name| name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            serde_json::json!({"toolName":tool.name,"missingKeys":missing}),
        ));
    }
    Ok(())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CoreTool {
    name: String,
    known_keys: Vec<String>,
    required_keys: Vec<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CorePreflight {
    catalog_sha256: String,
    dispatch_sha256: String,
    action_source_sha256: String,
    tools: Vec<CoreTool>,
    enforcement_side_doors: Vec<String>,
    retired_arguments: std::collections::BTreeMap<String, String>,
    unicode_version: String,
    character_data_sha256: String,
    letter_number_ranges: Vec<[u32; 2]>,
    trim_code_points: Vec<u32>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ActionPolicy {
    version: u32,
    descriptor_sha256: String,
    contract_hash: String,
    actions: Vec<Action>,
    preflight: CorePreflight,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Action {
    name: String,
    operations: Vec<String>,
    disposition: String,
}

fn action_policy() -> Result<&'static ActionPolicy> {
    static POLICY: OnceLock<std::result::Result<ActionPolicy, String>> = OnceLock::new();
    let policy = POLICY.get_or_init(|| {
        serde_json::from_str(include_str!("../assets/action-policy.json"))
            .map_err(|error| error.to_string())
    });
    let policy = policy
        .as_ref()
        .map_err(|_| Error::new("HOST_PROTOCOL_ERROR", "generated action policy is invalid"))?;
    if policy.version != 2
        || policy.descriptor_sha256.len() != 64
        || policy.contract_hash != crate::generated::CONTRACT_HASH
        || policy.preflight.catalog_sha256.len() != 64
        || policy.preflight.dispatch_sha256.len() != 64
        || policy.preflight.action_source_sha256.len() != 64
        || policy.preflight.tools.len() != 6
        || policy.preflight.unicode_version.is_empty()
        || policy.preflight.character_data_sha256.len() != 64
        || policy.preflight.letter_number_ranges.is_empty()
    {
        return Err(Error::new(
            "HOST_PROTOCOL_ERROR",
            "generated action policy does not match the SDK contract",
        ));
    }
    Ok(policy)
}

fn unavailable_from_operations(operations: &Value) -> Result<Vec<String>> {
    Ok(action_policy()?
        .actions
        .iter()
        .filter(|action| {
            action.disposition == "tracked"
                && action.operations.iter().any(|id| {
                    let capability = &operations[id];
                    capability["available"] != true
                        || (capability["tracked"] != true
                            && capability["trackedSupport"] != "conditional")
                })
        })
        .map(|action| action.name.clone())
        .collect())
}

fn unavailable_tracked_actions(capabilities: &DocCapabilitiesGetResult) -> Result<Vec<String>> {
    unavailable_from_operations(
        &serde_json::to_value(&capabilities.operations).map_err(Error::decode)?,
    )
}

fn merge_exclusions(
    configured: &Presence<String>,
    unavailable: &[String],
    authority: &CorePreflight,
) -> Presence<String> {
    if unavailable.is_empty() {
        return configured.clone();
    }
    let mut names = Vec::<String>::new();
    let configured = match configured {
        Presence::Present(value) => value
            .split(',')
            .map(|name| trim_core_csv_name(name, authority))
            .filter(|value| !value.is_empty())
            .map(str::to_owned)
            .collect::<Vec<_>>(),
        Presence::Missing => Vec::new(),
    };
    for name in configured.into_iter().chain(unavailable.iter().cloned()) {
        if !names.contains(&name) {
            names.push(name);
        }
    }
    Presence::Present(names.join(","))
}

#[derive(Clone)]
pub struct CoreToolkit {
    document: Document,
    policy: DocPresetGetToolsParams,
    tools: DocPresetGetToolsResult,
    system_prompt: DocPresetGetSystemPromptResult,
    capabilities: Option<Box<DocCapabilitiesGetResult>>,
}

impl CoreToolkit {
    pub fn tools(&self) -> &DocPresetGetToolsResult {
        &self.tools
    }

    pub fn system_prompt(&self) -> &DocPresetGetSystemPromptResult {
        &self.system_prompt
    }

    pub fn prompt(&self) -> &str {
        &self.system_prompt.prompt
    }

    pub fn policy(&self) -> &DocPresetGetToolsParams {
        &self.policy
    }

    pub fn capabilities_snapshot(&self) -> Option<&DocCapabilitiesGetResult> {
        self.capabilities.as_deref()
    }

    pub async fn dispatch(
        &self,
        params: &DocPresetDispatchBoundParams,
    ) -> Result<DocPresetDispatchResult> {
        self.dispatch_with_options(params, InvokeOptions::default())
            .await
    }

    pub async fn dispatch_with_options(
        &self,
        params: &DocPresetDispatchBoundParams,
        mut options: InvokeOptions,
    ) -> Result<DocPresetDispatchResult> {
        let mut params = params.clone();
        let mut args = match &params.args {
            Presence::Missing => serde_json::json!({}),
            Presence::Present(args) => args.clone(),
        };
        if params.tool_name == "superdoc_perform_action" && args.get("expectedRevision").is_some() {
            params.expected_revision = Presence::Missing;
        } else if !params.expected_revision.is_missing() {
            options.expected_revision = None;
        }
        prepare_core_dispatch(
            &params.tool_name,
            &mut args,
            &mut options,
            Some(&self.policy),
        )?;
        if let Presence::Present(revision) = &params.expected_revision {
            let invalid = || {
                Error::new("INVALID_ARGUMENT", "expectedRevision must be a non-empty live revision or a non-negative safe integer.")
            };
            let revision = match serde_json::to_value(revision).map_err(Error::decode)? {
                Value::String(value) if !value.is_empty() => value,
                Value::Number(value) => {
                    let value = value.as_f64().ok_or_else(invalid)?;
                    if value < 0.0
                        || value.fract() != 0.0
                        || value > crate::wire::Integer::MAX as f64
                    {
                        return Err(invalid());
                    }
                    if value == 0.0 {
                        "0".into()
                    } else {
                        value.to_string()
                    }
                }
                _ => return Err(invalid()),
            };
            options.expected_revision = Some(revision);
        }
        if let Some(receipt) = self
            .document
            .check_core_revision(&params.tool_name, &args, &options, Some(&self.policy))
            .await?
        {
            return Ok(DocPresetDispatchResult::new().with_result(receipt));
        }
        params.args = Presence::Present(args);
        params.preset = self.policy.preset.clone();
        params.exclude_actions = self.policy.exclude_actions.clone();
        params.enforce_change_mode = self.policy.enforce_change_mode.clone();
        params.allow_direct_actions = self.policy.allow_direct_actions.clone();
        self.document
            .api()
            .preset()
            .dispatch_with_options(&params, options)
            .await
    }
}

#[derive(Clone)]
pub struct FullToolkit {
    document: Document,
    policy: DocPresetGetToolsParams,
    tools: DocPresetGetToolsResult,
    system_prompt: DocPresetGetSystemPromptResult,
}

impl FullToolkit {
    pub fn tools(&self) -> &DocPresetGetToolsResult {
        &self.tools
    }

    pub fn system_prompt(&self) -> &DocPresetGetSystemPromptResult {
        &self.system_prompt
    }

    pub fn prompt(&self) -> &str {
        &self.system_prompt.prompt
    }

    pub fn policy(&self) -> &DocPresetGetToolsParams {
        &self.policy
    }

    pub async fn dispatch(
        &self,
        params: &DocPresetDispatchBoundParams,
    ) -> Result<DocPresetDispatchResult> {
        self.dispatch_with_options(params, InvokeOptions::default())
            .await
    }

    pub async fn dispatch_with_options(
        &self,
        params: &DocPresetDispatchBoundParams,
        options: InvokeOptions,
    ) -> Result<DocPresetDispatchResult> {
        let mut params = params.clone();
        params.preset = self.policy.preset.clone();
        params.exclude_actions = self.policy.exclude_actions.clone();
        params.enforce_change_mode = self.policy.enforce_change_mode.clone();
        params.allow_direct_actions = self.policy.allow_direct_actions.clone();
        self.document
            .api()
            .preset()
            .dispatch_with_options(&params, options)
            .await
    }
}

impl Document {
    pub async fn full_toolkit(&self, input: &DocPresetGetToolsParams) -> Result<FullToolkit> {
        let mut policy = input.clone();
        if let Presence::Present(preset) = &policy.preset {
            if preset != "full" {
                return Err(Error::new(
                    "INVALID_ARGUMENT",
                    "full_toolkit requires the full preset",
                ));
            }
        }
        policy.preset = Presence::Present("full".to_owned());
        let tools = self.api().preset().get_tools(&policy).await?;
        let mut prompt_params = DocPresetGetSystemPromptParams::new();
        prompt_params.preset = policy.preset.clone();
        prompt_params.exclude_actions = policy.exclude_actions.clone();
        prompt_params.enforce_change_mode = policy.enforce_change_mode.clone();
        prompt_params.allow_direct_actions = policy.allow_direct_actions.clone();
        let system_prompt = self
            .api()
            .preset()
            .get_system_prompt(&prompt_params)
            .await?;
        Ok(FullToolkit {
            document: self.clone(),
            policy,
            tools,
            system_prompt,
        })
    }
}

impl Document {
    pub async fn core_toolkit(&self, input: &DocPresetGetToolsParams) -> Result<CoreToolkit> {
        let mut policy = input.clone();
        if let Presence::Present(preset) = &policy.preset {
            if preset != "core" {
                return Err(Error::new(
                    "INVALID_ARGUMENT",
                    "core_toolkit requires the core preset",
                ));
            }
        }
        policy.preset = Presence::Present("core".to_owned());
        let capabilities = if matches!(&policy.enforce_change_mode, Presence::Present(mode) if mode == "tracked")
        {
            Some(Box::new(
                self.api()
                    .capabilities()
                    .get(&DocCapabilitiesGetBoundParams::new())
                    .await?,
            ))
        } else {
            None
        };
        if let Some(capabilities) = &capabilities {
            policy.exclude_actions = merge_exclusions(
                &policy.exclude_actions,
                &unavailable_tracked_actions(capabilities)?,
                &action_policy()?.preflight,
            );
        }
        let tools = self.api().preset().get_tools(&policy).await?;
        let mut prompt_params = DocPresetGetSystemPromptParams::new();
        prompt_params.preset = policy.preset.clone();
        prompt_params.exclude_actions = policy.exclude_actions.clone();
        prompt_params.enforce_change_mode = policy.enforce_change_mode.clone();
        prompt_params.allow_direct_actions = policy.allow_direct_actions.clone();
        let system_prompt = self
            .api()
            .preset()
            .get_system_prompt(&prompt_params)
            .await?;
        Ok(CoreToolkit {
            document: self.clone(),
            policy,
            tools,
            system_prompt,
            capabilities,
        })
    }
}

#[cfg(test)]
#[path = "agent_tests.rs"]
mod tests;