workforce-skill-sdk 0.1.1

SDK for building WASM-based skills for workforce agents
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
//! # workforce-skill-sdk
//!
//! Write custom workforce skill tools in Rust that compile to WASM.
//!
//! This crate wraps the raw WASM host ABI so you write normal Rust code
//! instead of pointer manipulation. Compile with `--target wasm32-unknown-unknown`
//! and distribute via a GitHub repo.
//!
//! ## Quick Start
//!
//! ```rust,ignore
//! use workforce_skill_sdk::prelude::*;
//!
//! workforce_skill_sdk::init!();
//!
//! tool!(get_weather, "Get current weather", {
//!     "type": "object",
//!     "properties": {
//!         "city": { "type": "string", "description": "City name" }
//!     },
//!     "required": ["city"]
//! }, |input: ToolInput| {
//!     let city = input.get_str("city").unwrap_or("unknown");
//!     let resp = http::get(
//!         &format!("https://wttr.in/{}?format=j1", city),
//!         &[],
//!     );
//!     match resp {
//!         Some(r) if r.is_success() => ToolOutput::success(json!({"weather": r.body})),
//!         _ => ToolOutput::error("Failed to fetch weather"),
//!     }
//! });
//! ```
//!
//! ## Architecture
//!
//! Skill authors write tool handlers that receive a `ToolInput` (the agent's
//! input parameters) and return a `ToolOutput` (success/failure with data).
//! The SDK handles serialisation, memory management, and host function calls.

use serde_json::Value;
use std::collections::HashMap;

// ─── Raw FFI ─────────────────────────────────────────────────────────────────
// Host functions provided by the workforce WASM runtime.
// Users never call these directly — use the `vault`, `http`, `log`, and
// `config` modules instead.

#[cfg(target_arch = "wasm32")]
#[allow(dead_code)]
extern "C" {
    fn wf_log(level: i32, msg_ptr: i32, msg_len: i32);
    fn wf_set_response(ptr: i32, len: i32);
    fn wf_get_host_response_len() -> i32;
    fn wf_get_host_response(buf_ptr: i32, buf_len: i32) -> i32;
    fn wf_generate_uuid() -> i32;
    fn wf_current_time() -> i32;
    fn wf_vault_get(key_ptr: i32, key_len: i32) -> i32;
    fn wf_vault_set(key_ptr: i32, key_len: i32, val_ptr: i32, val_len: i32) -> i32;
    fn wf_config_get(key_ptr: i32, key_len: i32) -> i32;
    fn wf_http_fetch(
        method_ptr: i32,
        method_len: i32,
        url_ptr: i32,
        url_len: i32,
        headers_ptr: i32,
        headers_len: i32,
        body_ptr: i32,
        body_len: i32,
    ) -> i32;
    fn wf_read_artifact(id_ptr: i32, id_len: i32) -> i32;
    fn wf_stage_artifact(payload_ptr: i32, payload_len: i32) -> i32;
    fn wf_tool_invoke(name_ptr: i32, name_len: i32, args_ptr: i32, args_len: i32) -> i32;
    fn wf_tool_invoke_many(payload_ptr: i32, payload_len: i32) -> i32;
}

// ─── Common host response reader ────────────────────────────────────────────

#[cfg(target_arch = "wasm32")]
fn read_host_response_string() -> Option<String> {
    let len = unsafe { wf_get_host_response_len() };
    if len <= 0 {
        return None;
    }
    let mut buf = vec![0u8; len as usize];
    let read = unsafe { wf_get_host_response(buf.as_mut_ptr() as i32, len) };
    if read <= 0 {
        return None;
    }
    buf.truncate(read as usize);
    String::from_utf8(buf).ok()
}

// ─── ToolInput ──────────────────────────────────────────────────────────────

/// Input parameters received by a tool handler.
///
/// Wraps the JSON input from the agent with convenience accessors.
#[derive(Debug, Clone)]
pub struct ToolInput {
    /// Raw JSON input from the agent.
    pub data: Value,
    /// The tool name being invoked.
    pub tool_name: String,
    /// The agent ID making the request.
    pub agent_id: String,
    /// The user ID making the request, if known. `None` for system-
    /// initiated work that didn't opt into a synthetic identity. Skills
    /// that read per-user credentials via `vault::get` don't need this —
    /// the host applies user scoping automatically — but it's exposed
    /// here for skills that want to surface "I am acting on behalf of X"
    /// in their tool output.
    pub user_id: Option<String>,
}

impl ToolInput {
    /// Parse a `ToolInput` from the request JSON the runtime provides.
    pub fn from_json(json: &str) -> Option<Self> {
        let v: Value = serde_json::from_str(json).ok()?;
        Some(Self {
            data: v["input"].clone(),
            tool_name: v["tool_name"].as_str().unwrap_or("").to_string(),
            agent_id: v["agent_id"].as_str().unwrap_or("").to_string(),
            user_id: v["user_id"].as_str().map(|s| s.to_string()),
        })
    }

    /// Get a string parameter by key.
    pub fn get_str(&self, key: &str) -> Option<&str> {
        self.data.get(key).and_then(|v| v.as_str())
    }

    /// Get an integer parameter by key.
    pub fn get_i64(&self, key: &str) -> Option<i64> {
        self.data.get(key).and_then(|v| v.as_i64())
    }

    /// Get a float parameter by key.
    pub fn get_f64(&self, key: &str) -> Option<f64> {
        self.data.get(key).and_then(|v| v.as_f64())
    }

    /// Get a boolean parameter by key.
    pub fn get_bool(&self, key: &str) -> Option<bool> {
        self.data.get(key).and_then(|v| v.as_bool())
    }

    /// Get a nested JSON value by key.
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.data.get(key)
    }

    /// Get the raw input as a reference.
    pub fn raw(&self) -> &Value {
        &self.data
    }
}

// ─── ToolOutput ─────────────────────────────────────────────────────────────

/// Output from a tool handler.
///
/// Serialised to JSON and returned to the workforce runtime, which passes
/// it back to the agent as a `ToolResult`.
#[derive(Debug, Clone)]
pub struct ToolOutput {
    success: bool,
    result: Value,
    error: Option<String>,
}

impl ToolOutput {
    /// Create a successful output with the given result data.
    pub fn success(result: Value) -> Self {
        Self {
            success: true,
            result,
            error: None,
        }
    }

    /// Create a failure output with an error message.
    pub fn error(message: &str) -> Self {
        Self {
            success: false,
            result: Value::Null,
            error: Some(message.to_string()),
        }
    }

    /// Serialise to the JSON format the runtime expects.
    pub fn into_json(self) -> String {
        let obj = serde_json::json!({
            "success": self.success,
            "result": self.result,
            "error": self.error,
        });
        serde_json::to_string(&obj)
            .unwrap_or_else(|_| r#"{"success":false,"error":"serialisation failed"}"#.to_string())
    }
}

// ─── vault module ───────────────────────────────────────────────────────────

/// Read and write secrets in the workforce vault.
///
/// All paths are automatically scoped to `wasm-skills/{skill_name}/` — you
/// only need to provide the key name relative to your skill.
///
/// Requires the `vault` capability in your `Skill.toml`.
pub mod vault {
    #[allow(unused_imports)]
    use super::*;

    /// Get a secret by key. Returns `None` if the key doesn't exist.
    ///
    /// ```rust,ignore
    /// let api_key = vault::get("api_key");
    /// ```
    pub fn get(key: &str) -> Option<String> {
        #[cfg(target_arch = "wasm32")]
        {
            let bytes = key.as_bytes();
            let result = unsafe { wf_vault_get(bytes.as_ptr() as i32, bytes.len() as i32) };
            if result < 0 {
                return None;
            }
            read_host_response_string()
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = key;
            None
        }
    }

    /// Set a secret. Returns `true` on success.
    ///
    /// ```rust,ignore
    /// vault::set("api_key", "sk-abc123");
    /// ```
    pub fn set(key: &str, value: &str) -> bool {
        #[cfg(target_arch = "wasm32")]
        {
            let key_bytes = key.as_bytes();
            let val_bytes = value.as_bytes();
            let result = unsafe {
                wf_vault_set(
                    key_bytes.as_ptr() as i32,
                    key_bytes.len() as i32,
                    val_bytes.as_ptr() as i32,
                    val_bytes.len() as i32,
                )
            };
            result == 0
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = (key, value);
            true
        }
    }
}

// ─── config module ──────────────────────────────────────────────────────────

/// Read skill-scoped configuration values.
///
/// Config values are set when the skill is installed/configured. They are
/// non-secret settings declared in the `[[config]]` section of `Skill.toml`.
///
/// Requires the `config` capability in your `Skill.toml`.
pub mod config {
    #[allow(unused_imports)]
    use super::*;

    /// Get a config value by key. Returns `None` if the key doesn't exist.
    ///
    /// ```rust,ignore
    /// let units = config::get("units").unwrap_or_else(|| "metric".to_string());
    /// ```
    pub fn get(key: &str) -> Option<String> {
        #[cfg(target_arch = "wasm32")]
        {
            let bytes = key.as_bytes();
            let result = unsafe { wf_config_get(bytes.as_ptr() as i32, bytes.len() as i32) };
            if result < 0 {
                return None;
            }
            read_host_response_string()
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = key;
            None
        }
    }
}

// ─── log module ─────────────────────────────────────────────────────────────

/// Structured logging from inside your WASM skill.
///
/// Messages appear in the workforce hub's log output prefixed with `[wasm-skill]`.
pub mod log {
    #[allow(unused_imports)]
    use super::*;

    /// Log an error message (level 0).
    pub fn error(msg: &str) {
        write(0, msg);
    }

    /// Log a warning message (level 1).
    pub fn warn(msg: &str) {
        write(1, msg);
    }

    /// Log an info message (level 2).
    pub fn info(msg: &str) {
        write(2, msg);
    }

    /// Log a debug message (level 3).
    pub fn debug(msg: &str) {
        write(3, msg);
    }

    fn write(level: i32, msg: &str) {
        #[cfg(target_arch = "wasm32")]
        {
            let bytes = msg.as_bytes();
            unsafe {
                super::wf_log(level, bytes.as_ptr() as i32, bytes.len() as i32);
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = (level, msg);
        }
    }
}

// ─── tools module ───────────────────────────────────────────────────────────

/// Invoke platform tools declared in this skill's `[[permissions]]`.
///
/// Requires the `tools` capability in your `Skill.toml`.
pub mod tools {
    #[allow(unused_imports)]
    use super::*;

    /// Invoke a platform tool declared in this skill's `[[permissions]]`.
    ///
    /// The call runs through the platform's governed dispatch — the user's
    /// tools grant (`cmd: skill grant <skill> tools`), the capability gate
    /// under the calling user, and the policy engine — so it can be refused
    /// even when declared. On refusal the runtime attaches the full remedy to
    /// this tool call's result for the agent; the `Err` here is a short
    /// category for the guest's own control flow. Rate-limited calls (429)
    /// are retried host-side with backoff before the envelope comes back.
    ///
    /// `Ok` is the platform envelope: `{"success": bool, "output": …,
    /// "error": …}` — check `success`, a tool-level failure is data, not a
    /// policy denial.
    ///
    /// ```rust,ignore
    /// let result = tools::invoke("slack.post_message", &json!({
    ///     "channel": "C123", "text": "done"
    /// }))?;
    /// ```
    pub fn invoke(name: &str, args: &Value) -> Result<Value, String> {
        #[cfg(target_arch = "wasm32")]
        {
            let name_bytes = name.as_bytes();
            let args_json = args.to_string();
            let args_bytes = args_json.as_bytes();
            let code = unsafe {
                wf_tool_invoke(
                    name_bytes.as_ptr() as i32,
                    name_bytes.len() as i32,
                    args_bytes.as_ptr() as i32,
                    args_bytes.len() as i32,
                )
            };
            match code {
                0 => read_host_response_string()
                    .and_then(|s| serde_json::from_str(&s).ok())
                    .ok_or_else(|| "tool result unavailable".to_string()),
                -2 => Err("the `tools` capability is not declared in Skill.toml".to_string()),
                -4 => Err(
                    "denied by platform policy (declaration, grant, capability, or rule) — \
                     surface this failure; the runtime attaches the remedy for the agent"
                        .to_string(),
                ),
                -5 => Err("tool-call budget exhausted for this invocation".to_string()),
                _ => Err("tool invocation failed".to_string()),
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = (name, args);
            Err("not running in the WASM runtime".to_string())
        }
    }

    /// Invoke several declared platform tools in one host call, dispatched
    /// concurrently host-side — guests have no threads, so this is the way
    /// to fan out (e.g. one query per service) instead of a serial loop.
    ///
    /// Each element passes the same governance as [`invoke`] and consumes
    /// one slot of the per-invocation tool-call budget. `Ok` preserves
    /// order: one platform envelope (`{"success", "output", "error"}`) per
    /// request — a per-element denial or failure arrives as an envelope
    /// with `success: false`, so a partial batch still returns the
    /// successes. `Err` is batch-level only (capability, grant, budget).
    ///
    /// ```rust,ignore
    /// let results = tools::invoke_many(&[
    ///     ("datadog.logs_search", json!({"query": "service:a status:error"})),
    ///     ("datadog.logs_search", json!({"query": "service:b status:error"})),
    /// ])?;
    /// ```
    pub fn invoke_many(calls: &[(&str, Value)]) -> Result<Vec<Value>, String> {
        #[cfg(target_arch = "wasm32")]
        {
            let payload = Value::Array(
                calls
                    .iter()
                    .map(|(name, args)| serde_json::json!({"tool": name, "args": args}))
                    .collect(),
            )
            .to_string();
            let bytes = payload.as_bytes();
            let code = unsafe { wf_tool_invoke_many(bytes.as_ptr() as i32, bytes.len() as i32) };
            match code {
                0 => read_host_response_string()
                    .and_then(|s| serde_json::from_str(&s).ok())
                    .ok_or_else(|| "tool results unavailable".to_string()),
                -2 => Err("the `tools` capability is not declared in Skill.toml".to_string()),
                -4 => Err(
                    "denied by platform policy (grant, marker ban, or rule) — surface \
                     this failure; the runtime attaches the remedy for the agent"
                        .to_string(),
                ),
                -5 => Err("tool-call budget exhausted for this invocation".to_string()),
                _ => Err("tool invocation failed".to_string()),
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = calls;
            Err("not running in the WASM runtime".to_string())
        }
    }
}

pub mod http {
    #[allow(unused_imports)]
    use super::*;

    /// Response from an HTTP request.
    #[derive(Debug, Clone)]
    pub struct FetchResponse {
        /// HTTP status code (e.g., 200, 404, 500).
        pub status: i32,
        /// Response body as a string.
        pub body: String,
        /// Body encoding: "utf8" for text, "base64" for binary content.
        pub body_encoding: String,
        /// Response headers.
        pub headers: HashMap<String, String>,
    }

    impl FetchResponse {
        /// Parse the response body as JSON.
        pub fn json(&self) -> Option<Value> {
            serde_json::from_str(&self.body).ok()
        }

        /// Check if the response status indicates success (2xx).
        pub fn is_success(&self) -> bool {
            (200..300).contains(&self.status)
        }

        /// Check if the body is base64-encoded (binary content).
        pub fn is_base64(&self) -> bool {
            self.body_encoding == "base64"
        }
    }

    /// Make an HTTP request.
    pub fn fetch(
        method: &str,
        url: &str,
        headers: &[(&str, &str)],
        body: Option<&str>,
    ) -> Option<FetchResponse> {
        #[cfg(target_arch = "wasm32")]
        {
            let method_bytes = method.as_bytes();
            let url_bytes = url.as_bytes();
            let headers_map: HashMap<&str, &str> = headers.iter().copied().collect();
            let headers_json = serde_json::to_string(&headers_map).unwrap_or_default();
            let headers_bytes = headers_json.as_bytes();
            let (body_bytes, body_len) = match body {
                Some(b) => (b.as_bytes(), b.len()),
                None => (&[] as &[u8], 0),
            };

            let result = unsafe {
                wf_http_fetch(
                    method_bytes.as_ptr() as i32,
                    method_bytes.len() as i32,
                    url_bytes.as_ptr() as i32,
                    url_bytes.len() as i32,
                    headers_bytes.as_ptr() as i32,
                    headers_bytes.len() as i32,
                    body_bytes.as_ptr() as i32,
                    body_len as i32,
                )
            };

            if result < 0 {
                return None;
            }

            read_fetch_response()
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = (method, url, headers, body);
            None
        }
    }

    /// Make a GET request.
    pub fn get(url: &str, headers: &[(&str, &str)]) -> Option<FetchResponse> {
        fetch("GET", url, headers, None)
    }

    /// Make a POST request with a body.
    pub fn post(url: &str, headers: &[(&str, &str)], body: &str) -> Option<FetchResponse> {
        fetch("POST", url, headers, Some(body))
    }

    /// Make a PUT request with a body.
    pub fn put(url: &str, headers: &[(&str, &str)], body: &str) -> Option<FetchResponse> {
        fetch("PUT", url, headers, Some(body))
    }

    /// Make a DELETE request.
    pub fn delete(url: &str, headers: &[(&str, &str)]) -> Option<FetchResponse> {
        fetch("DELETE", url, headers, None)
    }

    /// Make a PATCH request with a body.
    pub fn patch(url: &str, headers: &[(&str, &str)], body: &str) -> Option<FetchResponse> {
        fetch("PATCH", url, headers, Some(body))
    }

    #[cfg(target_arch = "wasm32")]
    fn read_fetch_response() -> Option<FetchResponse> {
        let json_str = read_host_response_string()?;
        let v: Value = serde_json::from_str(&json_str).ok()?;
        Some(FetchResponse {
            status: v["status"].as_i64().unwrap_or(0) as i32,
            body: v["body"].as_str().unwrap_or("").to_string(),
            body_encoding: v["body_encoding"].as_str().unwrap_or("utf8").to_string(),
            headers: v["headers"]
                .as_object()
                .map(|m| {
                    m.iter()
                        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                        .collect()
                })
                .unwrap_or_default(),
        })
    }
}

// ─── artifact module ────────────────────────────────────────────────────────

/// Read and stage workforce artifacts (uploaded files, produced outputs).
///
/// A skill takes the bytes of a staged file by `artifact_id`, transforms them
/// in-process, and stages the result for delivery — the bytes never pass
/// through the agent's LLM context.
///
/// Requires the `artifacts` capability in your `Skill.toml`.
pub mod artifact {
    #[allow(unused_imports)]
    use super::*;
    #[cfg(target_arch = "wasm32")]
    use base64::Engine;

    /// The bytes of a staged artifact plus its stored mime and size.
    #[derive(Debug, Clone)]
    pub struct Artifact {
        pub bytes: Vec<u8>,
        pub mime: String,
        pub size: usize,
    }

    /// A staged artifact ready for delivery. Pass it to [`attach`] so the
    /// runtime delivers the file to the conversation.
    #[derive(Debug, Clone)]
    pub struct StagedArtifact {
        pub artifact_id: String,
        pub media_type: String,
        pub filename: String,
        pub bytes: u64,
    }

    impl StagedArtifact {
        /// The delivery entry the runtime expects for one file.
        pub fn entry(&self) -> Value {
            serde_json::json!({
                "artifact_id": self.artifact_id,
                "media_type": self.media_type,
                "filename": self.filename,
            })
        }
    }

    /// Read a staged artifact by id. Returns `None` if it doesn't exist, isn't
    /// readable in this session, or exceeds the host read limit.
    pub fn read(id: &str) -> Option<Artifact> {
        #[cfg(target_arch = "wasm32")]
        {
            let bytes = id.as_bytes();
            let result = unsafe { wf_read_artifact(bytes.as_ptr() as i32, bytes.len() as i32) };
            if result < 0 {
                return None;
            }
            let v: Value = serde_json::from_str(&read_host_response_string()?).ok()?;
            let decoded = base64::engine::general_purpose::STANDARD
                .decode(v["bytes_base64"].as_str()?)
                .ok()?;
            Some(Artifact {
                bytes: decoded,
                mime: v["mime"]
                    .as_str()
                    .unwrap_or("application/octet-stream")
                    .to_string(),
                size: v["size"].as_u64().unwrap_or(0) as usize,
            })
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = id;
            None
        }
    }

    /// Stage `bytes` as a new artifact for delivery. `media_type` and
    /// `filename` label the delivered download. Returns `None` on failure.
    pub fn stage(bytes: &[u8], media_type: &str, filename: &str) -> Option<StagedArtifact> {
        #[cfg(target_arch = "wasm32")]
        {
            let payload = serde_json::json!({
                "bytes_base64": base64::engine::general_purpose::STANDARD.encode(bytes),
                "media_type": media_type,
                "filename": filename,
            })
            .to_string();
            let pb = payload.as_bytes();
            let result = unsafe { wf_stage_artifact(pb.as_ptr() as i32, pb.len() as i32) };
            if result < 0 {
                return None;
            }
            let v: Value = serde_json::from_str(&read_host_response_string()?).ok()?;
            Some(StagedArtifact {
                artifact_id: v["artifact_id"].as_str()?.to_string(),
                media_type: v["media_type"].as_str().unwrap_or(media_type).to_string(),
                filename: v["filename"].as_str().unwrap_or(filename).to_string(),
                bytes: v["bytes"].as_u64().unwrap_or(bytes.len() as u64),
            })
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = (bytes, media_type, filename);
            None
        }
    }

    /// Key under which the runtime scans a tool result for files to deliver.
    const DELIVERY_KEY: &str = "generated_images";

    /// Attach staged files to a tool result so the runtime delivers them. Sets
    /// the workforce file-delivery key on the result object; a non-object
    /// result or an empty `files` slice is returned unchanged.
    pub fn attach(mut result: Value, files: &[StagedArtifact]) -> Value {
        if let (Value::Object(map), false) = (&mut result, files.is_empty()) {
            map.insert(
                DELIVERY_KEY.to_string(),
                Value::Array(files.iter().map(StagedArtifact::entry).collect()),
            );
        }
        result
    }
}

// ─── util module ────────────────────────────────────────────────────────────

/// Utility functions for common operations in WASM skill handlers.
pub mod util {
    #[allow(unused_imports)]
    use super::*;

    /// Generate a new random UUID v4 string.
    pub fn generate_uuid() -> String {
        #[cfg(target_arch = "wasm32")]
        {
            let result = unsafe { super::wf_generate_uuid() };
            if result < 0 {
                return String::new();
            }
            read_host_response_string().unwrap_or_default()
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            // Fallback for native testing — not a real UUID
            format!("{:016x}", {
                use std::time::SystemTime;
                SystemTime::now()
                    .duration_since(SystemTime::UNIX_EPOCH)
                    .map(|d| d.as_nanos() as u64)
                    .unwrap_or(0)
            })
        }
    }

    /// Get the current UTC time as an RFC3339 string.
    pub fn current_time() -> String {
        #[cfg(target_arch = "wasm32")]
        {
            let result = unsafe { super::wf_current_time() };
            if result < 0 {
                return String::new();
            }
            read_host_response_string().unwrap_or_default()
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            use std::time::SystemTime;
            let secs = SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            format!("1970-01-01T00:00:{:02}Z", secs % 60)
        }
    }
}

// ─── Handler runtime ────────────────────────────────────────────────────────

/// Internal function used by the `tool!` macro. Do not call directly.
#[doc(hidden)]
pub fn __run_tool_handler<F>(ptr: i32, len: i32, f: F) -> i32
where
    F: FnOnce(ToolInput) -> ToolOutput,
{
    // Read the request JSON from guest memory.
    let request_json = unsafe {
        let slice = std::slice::from_raw_parts(ptr as *const u8, len as usize);
        String::from_utf8_lossy(slice).into_owned()
    };

    // Parse the input.
    let input = ToolInput::from_json(&request_json).unwrap_or_else(|| ToolInput {
        data: Value::Null,
        tool_name: String::new(),
        agent_id: String::new(),
        user_id: None,
    });

    // Call the user's handler.
    let output = f(input);
    let response_bytes = output.into_json().into_bytes();

    // Write response to guest memory: [4-byte LE length][data]
    let total = 4 + response_bytes.len();
    let layout = std::alloc::Layout::from_size_align(total, 1).expect("invalid layout");
    let out_ptr = unsafe { std::alloc::alloc(layout) };

    unsafe {
        let len_bytes = (response_bytes.len() as u32).to_le_bytes();
        std::ptr::copy_nonoverlapping(len_bytes.as_ptr(), out_ptr, 4);
        std::ptr::copy_nonoverlapping(
            response_bytes.as_ptr(),
            out_ptr.add(4),
            response_bytes.len(),
        );
    }

    out_ptr as i32
}

// ─── Macros ─────────────────────────────────────────────────────────────────

/// Initialize the workforce skill SDK runtime.
///
/// Call this once at the top of your `lib.rs`. Exports the `alloc` function
/// that the workforce runtime needs to pass data into your WASM module.
///
/// ```rust,ignore
/// workforce_skill_sdk::init!();
/// ```
#[macro_export]
macro_rules! init {
    () => {
        #[no_mangle]
        pub extern "C" fn alloc(size: i32) -> i32 {
            let layout = std::alloc::Layout::from_size_align(size as usize, 1).unwrap();
            unsafe { std::alloc::alloc(layout) as i32 }
        }
    };
}

/// Define a tool handler function.
///
/// This macro generates the `#[no_mangle] extern "C"` boilerplate so your
/// tool handler is a plain Rust closure that receives a [`ToolInput`] and
/// returns a [`ToolOutput`].
///
/// ```rust,ignore
/// use workforce_skill_sdk::prelude::*;
///
/// workforce_skill_sdk::init!();
///
/// tool!(get_weather, |input: ToolInput| {
///     let city = input.get_str("city").unwrap_or("unknown");
///     ToolOutput::success(json!({"city": city, "temp": 22}))
/// });
/// ```
#[macro_export]
macro_rules! tool {
    ($name:ident, |$input:ident : ToolInput| $body:expr) => {
        #[no_mangle]
        pub extern "C" fn $name(ptr: i32, len: i32) -> i32 {
            $crate::__run_tool_handler(ptr, len, |$input: $crate::ToolInput| $body)
        }
    };
}

// ─── Prelude ────────────────────────────────────────────────────────────────

/// Import everything you need to write skill tools.
///
/// ```rust,ignore
/// use workforce_skill_sdk::prelude::*;
/// ```
pub mod prelude {
    pub use crate::artifact;
    pub use crate::config;
    pub use crate::http;
    pub use crate::log;
    pub use crate::tools;
    pub use crate::util;
    pub use crate::vault;
    pub use crate::ToolInput;
    pub use crate::ToolOutput;
    pub use serde_json::{json, Value};
}

// ─── Tests ──────────────────────────────────────────────────────────────────

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

    #[test]
    fn tool_input_parsing() {
        let json = serde_json::to_string(&json!({
            "tool_name": "weather.get_forecast",
            "handler": "get_forecast",
            "input": {"city": "London", "units": "metric"},
            "agent_id": "agent-1",
        }))
        .unwrap();

        let input = ToolInput::from_json(&json).unwrap();
        assert_eq!(input.tool_name, "weather.get_forecast");
        assert_eq!(input.agent_id, "agent-1");
        assert_eq!(input.get_str("city"), Some("London"));
        assert_eq!(input.get_str("units"), Some("metric"));
        assert!(input.get_str("nonexistent").is_none());
    }

    #[test]
    fn tool_input_accessors() {
        let json = serde_json::to_string(&json!({
            "input": {"count": 42, "ratio": 2.78, "active": true},
        }))
        .unwrap();

        let input = ToolInput::from_json(&json).unwrap();
        assert_eq!(input.get_i64("count"), Some(42));
        assert_eq!(input.get_f64("ratio"), Some(2.78));
        assert_eq!(input.get_bool("active"), Some(true));
    }

    #[test]
    fn tool_input_missing_fields() {
        let json = r#"{"input": {}}"#;
        let input = ToolInput::from_json(json).unwrap();
        assert_eq!(input.tool_name, "");
        assert_eq!(input.agent_id, "");
        assert_eq!(input.user_id, None);
    }

    #[test]
    fn tool_input_parses_user_id() {
        let json = serde_json::to_string(&json!({
            "tool_name": "x",
            "agent_id": "a",
            "user_id": "alice",
            "input": {},
        }))
        .unwrap();
        let input = ToolInput::from_json(&json).unwrap();
        assert_eq!(input.user_id.as_deref(), Some("alice"));
    }

    #[test]
    fn tool_input_user_id_absent_when_unset() {
        let json = r#"{"tool_name": "x", "agent_id": "a", "input": {}}"#;
        let input = ToolInput::from_json(json).unwrap();
        assert_eq!(input.user_id, None);
    }

    #[test]
    fn tool_output_success() {
        let output = ToolOutput::success(json!({"data": "test"}));
        let json_str = output.into_json();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["success"], true);
        assert_eq!(parsed["result"]["data"], "test");
        assert!(parsed["error"].is_null());
    }

    #[test]
    fn tool_output_error() {
        let output = ToolOutput::error("something failed");
        let json_str = output.into_json();
        let parsed: Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["success"], false);
        assert!(parsed["result"].is_null());
        assert_eq!(parsed["error"], "something failed");
    }

    #[test]
    fn vault_get_noop_on_native() {
        assert!(vault::get("any-key").is_none());
    }

    #[test]
    fn vault_set_noop_on_native() {
        assert!(vault::set("key", "value"));
    }

    #[test]
    fn config_get_noop_on_native() {
        assert!(config::get("any-key").is_none());
    }

    #[test]
    fn http_get_noop_on_native() {
        assert!(http::get("https://example.com", &[]).is_none());
    }

    #[test]
    fn http_post_noop_on_native() {
        assert!(http::post("https://example.com", &[], "{}").is_none());
    }

    #[test]
    fn util_generate_uuid() {
        let id = util::generate_uuid();
        assert!(!id.is_empty());
    }

    #[test]
    fn util_current_time() {
        let time = util::current_time();
        assert!(!time.is_empty());
    }

    #[test]
    fn http_fetch_response_helpers() {
        let resp = http::FetchResponse {
            status: 200,
            body: r#"{"key": "value"}"#.to_string(),
            body_encoding: "utf8".to_string(),
            headers: HashMap::new(),
        };
        assert!(resp.is_success());
        assert!(!resp.is_base64());
        let json = resp.json().unwrap();
        assert_eq!(json["key"], "value");

        let err_resp = http::FetchResponse {
            status: 404,
            body: "not found".to_string(),
            body_encoding: "utf8".to_string(),
            headers: HashMap::new(),
        };
        assert!(!err_resp.is_success());

        let binary_resp = http::FetchResponse {
            status: 200,
            body: "aW1hZ2VkYXRh".to_string(),
            body_encoding: "base64".to_string(),
            headers: HashMap::new(),
        };
        assert!(binary_resp.is_base64());
    }

    #[test]
    fn artifact_read_stage_noop_on_native() {
        assert!(artifact::read("art_0").is_none());
        assert!(artifact::stage(b"x", "text/plain", "x.txt").is_none());
    }

    #[test]
    fn tools_invoke_noop_on_native() {
        assert!(tools::invoke("echo.say", &json!({})).is_err());
        assert!(tools::invoke_many(&[("echo.say", json!({}))]).is_err());
    }

    #[test]
    fn artifact_attach_sets_delivery_key() {
        let staged = artifact::StagedArtifact {
            artifact_id: "art_00000000000000000000000000000000".to_string(),
            media_type: "application/pdf".to_string(),
            filename: "out.pdf".to_string(),
            bytes: 42,
        };
        let out = artifact::attach(json!({ "rows": 3 }), std::slice::from_ref(&staged));
        assert_eq!(out["rows"], 3);
        let entries = out["generated_images"].as_array().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0]["artifact_id"], staged.artifact_id);
        assert_eq!(entries[0]["media_type"], "application/pdf");
        assert_eq!(entries[0]["filename"], "out.pdf");
    }

    #[test]
    fn artifact_attach_empty_is_unchanged() {
        let out = artifact::attach(json!({ "rows": 3 }), &[]);
        assert!(out.get("generated_images").is_none());
    }
}