golem-schema 1.6.1

Golem schema and value model
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
// Copyright 2024-2026 Golem Cloud
//
// Licensed under the Golem Source License v1.1 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://license.golem.cloud/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Round-trip conversion between the recursive in-memory schema model in
//! [`super`] and the flat, index-based wire types from the
//! `golem:core@2.0.0` WIT package.
//!
//! The wire types themselves are generated in this crate. The active generated
//! module is selected by the mutually-exclusive `guest` and `host` features and
//! re-exported through [`wire`].

mod decode;
mod encode;

#[cfg(all(feature = "guest", not(feature = "host")))]
pub mod direct;

#[cfg(any(
    all(feature = "guest", not(feature = "host")),
    all(feature = "host", not(feature = "guest"))
))]
mod model;

#[cfg(all(feature = "guest", not(feature = "host")))]
pub(crate) mod guest;

#[cfg(all(feature = "host", not(feature = "guest")))]
pub(crate) mod host;

/// Generated `golem:core@2.0.0` types used as the wire shape.
#[cfg(all(feature = "guest", not(feature = "host")))]
pub use guest::generated::golem::core::types as wire;

/// Generated `golem:core@2.0.0` types used as the wire shape.
#[cfg(all(feature = "host", not(feature = "guest")))]
pub use host::generated::golem::core::types as wire;

pub(crate) use decode::decode_value_by_ref;
pub use decode::{
    DecodeError, GraphDecoder, decode_graph, decode_metadata, decode_typed, decode_value,
};
pub use encode::{
    EncodeError, GraphEncoder, encode_graph, encode_metadata, encode_typed, encode_value,
};
#[cfg(all(feature = "guest", not(feature = "host")))]
pub use encode::{encode_typed_async, encode_value_async};

#[cfg(all(feature = "guest", not(feature = "host")))]
pub use decode::decode_typed_owned;
#[cfg(all(feature = "guest", not(feature = "host")))]
pub use encode::encode_typed_owned;

#[cfg(all(feature = "host", not(feature = "guest")))]
pub use decode::{
    decode_typed_rejecting_permission_card_with, decode_typed_rejecting_quota_with,
    decode_typed_rejecting_secret_with, decode_value_rejecting_permission_card_with,
    decode_value_rejecting_quota_with, decode_value_rejecting_secret_with, decode_value_with,
    reject_permission_card_handles_in_value_tree, reject_quota_handles_in_value_tree,
    reject_secret_handles_in_value_tree,
};
#[cfg(all(feature = "host", not(feature = "guest")))]
pub use encode::{encode_value_with, encode_value_with_streams};
#[cfg(all(feature = "host", not(feature = "guest")))]
pub use host_support::{
    PermissionCardHandleDropper, PermissionCardHandleRep, PermissionCardResolver,
    QuotaTokenHandleDropper, QuotaTokenHandleRep, QuotaTokenResolver, SchemaValueStreamResolver,
    SecretHandleDropper, SecretHandleRep, SecretResolver,
};

#[cfg(all(feature = "guest", not(feature = "host")))]
pub use guest_support::{GuestPermissionCardHandle, GuestQuotaTokenHandle, GuestSecretHandle};

/// Create a native Component Model stream carrying schema value trees.
#[cfg(all(feature = "guest", not(feature = "host")))]
pub fn new_schema_value_stream() -> (
    wit_bindgen::StreamWriter<wire::SchemaValueTree>,
    wit_bindgen::StreamReader<wire::SchemaValueTree>,
) {
    guest::generated::wit_stream::new()
}

/// Host-side bridge for the opaque `golem:core/types.quota-token` resource.
///
/// The resource is generated by this crate's host bindings and mapped (via the
/// `with` clause in [`host`]) to [`QuotaTokenHandleRep`]. golem-schema never
/// inspects the handle payload; the embedder (the worker executor) stores its
/// own rich quota state inside the box and converts handles to/from the trusted
/// snapshot [`crate::schema::schema_value::QuotaTokenValuePayload`] through the
/// [`QuotaTokenResolver`] trait at the value-tree boundary.
#[cfg(all(feature = "host", not(feature = "guest")))]
mod host_support {
    use crate::schema::schema_value::{
        PermissionCardValuePayload, QuotaTokenValuePayload, SecretValuePayload,
    };
    use crate::schema::{SchemaValueStream, SchemaValueStreamHandleRep};
    use wasmtime::component::Resource;

    pub trait SchemaValueStreamResolver {
        type Error: std::fmt::Display;

        fn handle_from_stream(
            &mut self,
            stream: SchemaValueStream,
        ) -> Result<Resource<SchemaValueStreamHandleRep>, Self::Error>;

        fn stream_from_handle(
            &mut self,
            handle: Resource<SchemaValueStreamHandleRep>,
        ) -> Result<SchemaValueStream, Self::Error>;

        fn drop_stream_handle(&mut self, handle: Resource<SchemaValueStreamHandleRep>);
    }

    /// Opaque host representation backing the `quota-token` WIT resource.
    ///
    /// The boxed payload is owned and interpreted solely by the embedder; this
    /// crate only moves the handle in and out of the resource table. The payload
    /// is intentionally private so embedders go through [`Self::new`],
    /// [`Self::downcast_ref`], and [`Self::downcast_mut`] rather than touching
    /// the erased box directly.
    pub struct QuotaTokenHandleRep {
        payload: Box<dyn std::any::Any + Send + Sync>,
    }

    impl QuotaTokenHandleRep {
        pub fn new(payload: impl std::any::Any + Send + Sync) -> Self {
            Self {
                payload: Box::new(payload),
            }
        }

        pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> {
            self.payload.downcast_ref::<T>()
        }

        pub fn downcast_mut<T: std::any::Any>(&mut self) -> Option<&mut T> {
            self.payload.downcast_mut::<T>()
        }

        /// Consume the handle, returning the owned payload if it has the
        /// expected type. On a type mismatch the handle is returned unchanged in
        /// the `Err` so the caller can recover or drop it.
        pub fn into_payload<T: std::any::Any>(self) -> Result<T, Self> {
            match self.payload.downcast::<T>() {
                Ok(boxed) => Ok(*boxed),
                Err(payload) => Err(Self { payload }),
            }
        }
    }

    /// Boundary bridge between owned `quota-token` handles carried inside a
    /// `schema-value-tree` and the trusted host snapshot.
    ///
    /// Implemented by the embedder that owns the resource table. The codec calls
    /// these hooks while lifting/lowering value trees so that the snapshot never
    /// crosses the WASM boundary as forgeable data.
    pub trait QuotaTokenResolver {
        type Error: std::fmt::Display;

        /// Consume an owned handle lifted from a value tree and return its
        /// trusted snapshot.
        ///
        /// The handle is always removed from the resource table: implementations
        /// must delete the entry on every path for a valid handle, including
        /// when extracting the snapshot afterwards fails. The codec gives up
        /// ownership of the handle when calling this, so it cannot clean up a
        /// handle that an `Err` return leaves behind in the table.
        fn snapshot_handle(
            &mut self,
            handle: Resource<QuotaTokenHandleRep>,
        ) -> Result<QuotaTokenValuePayload, Self::Error>;

        /// Materialize a fresh owned handle from a trusted snapshot so it can be
        /// lowered to a guest.
        ///
        /// On `Err`, implementations must not leave a newly created handle or
        /// resource-table entry behind: the codec only tracks handles that were
        /// returned to it, so it cannot clean up an entry abandoned by a failed
        /// call.
        fn handle_from_snapshot(
            &mut self,
            snapshot: &QuotaTokenValuePayload,
        ) -> Result<Resource<QuotaTokenHandleRep>, Self::Error>;

        /// Drop an owned handle without snapshotting it. Used to release handles
        /// that are left unconsumed when decoding fails partway through a tree.
        fn drop_handle(&mut self, handle: Resource<QuotaTokenHandleRep>);
    }

    /// Boundary bridge between owned `secret` handles carried inside a
    /// `schema-value-tree` and the trusted host snapshot.
    pub trait SecretResolver {
        type Error: std::fmt::Display;

        /// Consume an owned handle lifted from a value tree and return its
        /// trusted, plaintext-free snapshot.
        fn snapshot_secret_handle(
            &mut self,
            handle: Resource<SecretHandleRep>,
        ) -> Result<SecretValuePayload, Self::Error>;

        /// Materialize a fresh owned handle from a trusted snapshot so it can be
        /// lowered to a guest.
        fn secret_handle_from_snapshot(
            &mut self,
            snapshot: &SecretValuePayload,
        ) -> Result<Resource<SecretHandleRep>, Self::Error>;

        /// Drop an owned handle without snapshotting it.
        fn drop_secret_handle(&mut self, handle: Resource<SecretHandleRep>);
    }

    /// Minimal capability needed to clean up owned `quota-token` handles at
    /// boundaries that *reject* quota tokens.
    ///
    /// Reject paths never snapshot or mint handles; they only need to delete a
    /// handle that the guest already transferred into the resource table. This
    /// is a strictly smaller capability than [`QuotaTokenResolver`], so callers
    /// that lack a full resolver (e.g. the standalone agent-type extraction
    /// host) can still drain handles. Every [`QuotaTokenResolver`] is a
    /// `QuotaTokenHandleDropper` via the blanket impl below.
    pub trait QuotaTokenHandleDropper {
        /// Delete an owned handle from the resource table without inspecting it.
        fn drop_quota_token_handle(&mut self, handle: Resource<QuotaTokenHandleRep>);
    }

    /// Minimal capability needed to clean up owned `secret` handles at
    /// boundaries that reject secret transport.
    pub trait SecretHandleDropper {
        /// Delete an owned secret handle from the resource table without
        /// inspecting it.
        fn drop_secret_handle(&mut self, handle: Resource<SecretHandleRep>);
    }

    impl<R: QuotaTokenResolver> QuotaTokenHandleDropper for R {
        fn drop_quota_token_handle(&mut self, handle: Resource<QuotaTokenHandleRep>) {
            QuotaTokenResolver::drop_handle(self, handle)
        }
    }

    impl<R: SecretResolver> SecretHandleDropper for R {
        fn drop_secret_handle(&mut self, handle: Resource<SecretHandleRep>) {
            SecretResolver::drop_secret_handle(self, handle)
        }
    }

    /// Opaque host representation backing the `secret` WIT resource.
    ///
    /// The boxed payload is owned and interpreted solely by the embedder. This
    /// crate only gives the resource a shared table representation so the core
    /// `secret` handle can be generated and linked alongside `quota-token`.
    pub struct SecretHandleRep {
        payload: Box<dyn std::any::Any + Send + Sync>,
    }

    impl SecretHandleRep {
        pub fn new(payload: impl std::any::Any + Send + Sync) -> Self {
            Self {
                payload: Box::new(payload),
            }
        }

        pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> {
            self.payload.downcast_ref::<T>()
        }

        pub fn downcast_mut<T: std::any::Any>(&mut self) -> Option<&mut T> {
            self.payload.downcast_mut::<T>()
        }

        pub fn into_payload<T: std::any::Any>(self) -> Result<T, Self> {
            match self.payload.downcast::<T>() {
                Ok(boxed) => Ok(*boxed),
                Err(payload) => Err(Self { payload }),
            }
        }
    }

    /// Opaque host representation backing the `permission-card` WIT resource.
    ///
    /// The boxed payload is owned and interpreted solely by the embedder; this
    /// crate only moves the handle in and out of the resource table. The payload
    /// is intentionally private so embedders go through [`Self::new`],
    /// [`Self::downcast_ref`], and [`Self::downcast_mut`] rather than touching
    /// the erased box directly.
    pub struct PermissionCardHandleRep {
        payload: Box<dyn std::any::Any + Send + Sync>,
    }

    impl PermissionCardHandleRep {
        pub fn new(payload: impl std::any::Any + Send + Sync) -> Self {
            Self {
                payload: Box::new(payload),
            }
        }

        pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> {
            self.payload.downcast_ref::<T>()
        }

        pub fn downcast_mut<T: std::any::Any>(&mut self) -> Option<&mut T> {
            self.payload.downcast_mut::<T>()
        }

        /// Consume the handle, returning the owned payload if it has the
        /// expected type. On a type mismatch the handle is returned unchanged in
        /// the `Err` so the caller can recover or drop it.
        pub fn into_payload<T: std::any::Any>(self) -> Result<T, Self> {
            match self.payload.downcast::<T>() {
                Ok(boxed) => Ok(*boxed),
                Err(payload) => Err(Self { payload }),
            }
        }
    }

    /// Boundary bridge between owned `permission-card` handles carried inside a
    /// `schema-value-tree` and the trusted host snapshot.
    ///
    /// Implemented by the embedder that owns the resource table. The codec calls
    /// these hooks while lifting/lowering value trees so that the snapshot never
    /// crosses the WASM boundary as forgeable data. Only `card_id` is
    /// authoritative; the other snapshot fields are trusted cache verified
    /// against the card store.
    pub trait PermissionCardResolver {
        type Error: std::fmt::Display;

        /// Consume an owned handle lifted from a value tree and return its
        /// trusted snapshot.
        ///
        /// The handle is always removed from the resource table: implementations
        /// must delete the entry on every path for a valid handle, including
        /// when extracting the snapshot afterwards fails. The codec gives up
        /// ownership of the handle when calling this, so it cannot clean up a
        /// handle that an `Err` return leaves behind in the table.
        fn snapshot_permission_card_handle(
            &mut self,
            handle: Resource<PermissionCardHandleRep>,
        ) -> Result<PermissionCardValuePayload, Self::Error>;

        /// Materialize a fresh owned handle from a trusted snapshot so it can be
        /// lowered to a guest.
        ///
        /// On `Err`, implementations must not leave a newly created handle or
        /// resource-table entry behind: the codec only tracks handles that were
        /// returned to it, so it cannot clean up an entry abandoned by a failed
        /// call.
        fn permission_card_handle_from_snapshot(
            &mut self,
            snapshot: &PermissionCardValuePayload,
        ) -> Result<Resource<PermissionCardHandleRep>, Self::Error>;

        /// Drop an owned handle without snapshotting it. Used to release handles
        /// that are left unconsumed when decoding fails partway through a tree.
        fn drop_permission_card_handle(&mut self, handle: Resource<PermissionCardHandleRep>);
    }

    /// Minimal capability needed to clean up owned `permission-card` handles at
    /// boundaries that reject permission-card transport.
    ///
    /// Reject paths never snapshot or mint handles; they only need to delete a
    /// handle that the guest already transferred into the resource table. This
    /// is a strictly smaller capability than [`PermissionCardResolver`], so
    /// callers that lack a full resolver can still drain handles. Every
    /// [`PermissionCardResolver`] is a `PermissionCardHandleDropper` via the
    /// blanket impl below.
    pub trait PermissionCardHandleDropper {
        /// Delete an owned handle from the resource table without inspecting it.
        fn drop_permission_card_handle(&mut self, handle: Resource<PermissionCardHandleRep>);
    }

    impl<R: PermissionCardResolver> PermissionCardHandleDropper for R {
        fn drop_permission_card_handle(&mut self, handle: Resource<PermissionCardHandleRep>) {
            PermissionCardResolver::drop_permission_card_handle(self, handle)
        }
    }
}

/// Guest-side carrier for the opaque, owned `golem:core/types.quota-token`
/// resource handle.
///
/// A `quota-token` is an affine capability: the guest may hold and transfer it,
/// but can never inspect or forge it. Inside a [`SchemaValue`] the handle is
/// stored in a shared, take-once cell so the value AST can satisfy
/// `Clone`/`PartialEq` without duplicating the underlying capability. Cloning a
/// `SchemaValue` that contains a token shares the same one-shot cell; lowering
/// the value to a WIT `schema-value-tree` (encoding) takes the handle out
/// exactly once (first encode wins). Dropping the cell without encoding releases
/// the underlying resource via wit-bindgen's generated RAII drop.
#[cfg(all(feature = "guest", not(feature = "host")))]
mod guest_support {
    use super::wire;
    use crate::schema::conversion::{FromSchema, FromSchemaError, IntoSchema, SchemaBuilder};
    use crate::schema::metadata::TypeId;
    use crate::schema::schema_type::{PermissionCardSpec, QuotaTokenSpec, SchemaType};
    use crate::schema::schema_value::SchemaValue;
    use std::sync::{Arc, Mutex};

    #[derive(Clone)]
    pub struct GuestQuotaTokenHandle {
        inner: Arc<Mutex<Option<wire::QuotaToken>>>,
    }

    // The methods below expose the affine owned handle so the codec (this
    // crate) and the SDK wrappers (`golem-rust`, a separate crate) can move it
    // through encode/decode and call borrowing quota operations on it. They have
    // to stay `pub` because they cross that crate boundary, but they are not a
    // supported guest API: a guest that calls `take`/`new`/`with_handle` could
    // move the underlying `wire::QuotaToken` resource around outside the
    // take-once cell and defeat the affine/unforgeable guarantee. They are
    // hidden from the documented surface (`#[doc(hidden)]`) to discourage that;
    // genuine forgery is only possible through wit-bindgen's own hidden resource
    // handle accessors, which are outside this crate's control.
    impl GuestQuotaTokenHandle {
        /// Wrap a freshly received owned handle in a take-once cell.
        #[doc(hidden)]
        pub fn new(handle: wire::QuotaToken) -> Self {
            Self {
                inner: Arc::new(Mutex::new(Some(handle))),
            }
        }

        /// Take the owned handle out of the cell. Returns `None` if it was
        /// already transferred (consumed) by a previous encode.
        #[doc(hidden)]
        pub fn take(&self) -> Option<wire::QuotaToken> {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .take()
        }

        /// Whether the handle is still present (not yet transferred).
        #[doc(hidden)]
        pub fn is_present(&self) -> bool {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .is_some()
        }

        /// Run `f` with a shared reference to the owned handle, if it is still
        /// present (i.e. has not been transferred out by an encode). Returns
        /// `None` if the handle was already consumed.
        ///
        /// Used by SDK wrappers to invoke borrowing quota operations
        /// (`reserve`, `split`) on the underlying resource without taking
        /// ownership of it.
        #[doc(hidden)]
        pub fn with_handle<R>(&self, f: impl FnOnce(&wire::QuotaToken) -> R) -> Option<R> {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .as_ref()
                .map(f)
        }

        /// Identity of the shared cell, used to detect the same token appearing
        /// more than once in a single value tree.
        #[doc(hidden)]
        pub fn cell_id(&self) -> *const () {
            Arc::as_ptr(&self.inner).cast()
        }
    }

    impl std::fmt::Debug for GuestQuotaTokenHandle {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let state = if self.is_present() {
                "present"
            } else {
                "consumed"
            };
            write!(f, "GuestQuotaTokenHandle(<{state}>)")
        }
    }

    impl PartialEq for GuestQuotaTokenHandle {
        fn eq(&self, other: &Self) -> bool {
            Arc::ptr_eq(&self.inner, &other.inner)
        }
    }

    impl serde::Serialize for GuestQuotaTokenHandle {
        fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom(
                "quota-token handles cannot be serialized; transfer them through a WIT schema-value-tree",
            ))
        }
    }

    impl<'de> serde::Deserialize<'de> for GuestQuotaTokenHandle {
        fn deserialize<D: serde::Deserializer<'de>>(_deserializer: D) -> Result<Self, D::Error> {
            Err(serde::de::Error::custom(
                "quota-token handles cannot be deserialized or forged from data",
            ))
        }
    }

    impl IntoSchema for GuestQuotaTokenHandle {
        fn type_id() -> TypeId {
            TypeId::new("golem.core.QuotaToken")
        }

        fn register_in(_builder: &mut SchemaBuilder) -> SchemaType {
            SchemaType::quota_token(QuotaTokenSpec::default())
        }

        fn to_value(&self) -> SchemaValue {
            SchemaValue::QuotaToken(self.clone())
        }
    }

    impl FromSchema for GuestQuotaTokenHandle {
        fn from_value(value: &SchemaValue) -> Result<Self, FromSchemaError> {
            match value {
                SchemaValue::QuotaToken(h) => Ok(h.clone()),
                other => Err(FromSchemaError::shape_mismatch(
                    "quota-token",
                    format!("{other:?}"),
                    "QuotaToken",
                )),
            }
        }
    }

    #[derive(Clone)]
    pub struct GuestSecretHandle {
        inner: Arc<Mutex<Option<wire::Secret>>>,
    }

    impl GuestSecretHandle {
        /// Wrap a freshly received owned handle in a take-once cell.
        #[doc(hidden)]
        pub fn new(handle: wire::Secret) -> Self {
            Self {
                inner: Arc::new(Mutex::new(Some(handle))),
            }
        }

        /// Take the owned handle out of the cell. Returns `None` if it was
        /// already transferred by a previous encode.
        #[doc(hidden)]
        pub fn take(&self) -> Option<wire::Secret> {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .take()
        }

        /// Whether the handle is still present (not yet transferred).
        #[doc(hidden)]
        pub fn is_present(&self) -> bool {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .is_some()
        }

        /// Run `f` with a shared reference to the owned handle, if it is still
        /// present.
        #[doc(hidden)]
        pub fn with_handle<R>(&self, f: impl FnOnce(&wire::Secret) -> R) -> Option<R> {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .as_ref()
                .map(f)
        }

        /// Identity of the shared cell, used to detect the same secret
        /// appearing more than once in a single value tree.
        #[doc(hidden)]
        pub fn cell_id(&self) -> *const () {
            Arc::as_ptr(&self.inner).cast()
        }
    }

    impl std::fmt::Debug for GuestSecretHandle {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let state = if self.is_present() {
                "present"
            } else {
                "consumed"
            };
            write!(f, "GuestSecretHandle(<{state}>)")
        }
    }

    impl PartialEq for GuestSecretHandle {
        fn eq(&self, other: &Self) -> bool {
            Arc::ptr_eq(&self.inner, &other.inner)
        }
    }

    impl serde::Serialize for GuestSecretHandle {
        fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom(
                "secret handles cannot be serialized; transfer them through a WIT schema-value-tree",
            ))
        }
    }

    impl<'de> serde::Deserialize<'de> for GuestSecretHandle {
        fn deserialize<D: serde::Deserializer<'de>>(_deserializer: D) -> Result<Self, D::Error> {
            Err(serde::de::Error::custom(
                "secret handles cannot be deserialized or forged from data",
            ))
        }
    }

    impl IntoSchema for GuestSecretHandle {
        fn type_id() -> TypeId {
            TypeId::new("golem.core.Secret")
        }

        fn register_in(_builder: &mut SchemaBuilder) -> SchemaType {
            SchemaType::secret(Default::default())
        }

        fn to_value(&self) -> SchemaValue {
            SchemaValue::Secret(self.clone())
        }
    }

    impl FromSchema for GuestSecretHandle {
        fn from_value(value: &SchemaValue) -> Result<Self, FromSchemaError> {
            match value {
                SchemaValue::Secret(h) => Ok(h.clone()),
                other => Err(FromSchemaError::shape_mismatch(
                    "secret",
                    format!("{other:?}"),
                    "Secret",
                )),
            }
        }
    }

    #[derive(Clone)]
    pub struct GuestPermissionCardHandle {
        inner: Arc<Mutex<Option<wire::PermissionCard>>>,
    }

    // The methods below expose the affine owned handle so the codec (this
    // crate) and the SDK wrappers (`golem-rust`, a separate crate) can move it
    // through encode/decode and call borrowing permission operations on it.
    // They have to stay `pub` because they cross that crate boundary, but they
    // are not a supported guest API: a guest that calls `take`/`new`/`with_handle`
    // could move the underlying `wire::PermissionCard` resource around outside
    // the take-once cell and defeat the affine/unforgeable guarantee. They are
    // hidden from the documented surface (`#[doc(hidden)]`) to discourage that;
    // genuine forgery is only possible through wit-bindgen's own hidden resource
    // handle accessors, which are outside this crate's control.
    impl GuestPermissionCardHandle {
        /// Wrap a freshly received owned handle in a take-once cell.
        #[doc(hidden)]
        pub fn new(handle: wire::PermissionCard) -> Self {
            Self {
                inner: Arc::new(Mutex::new(Some(handle))),
            }
        }

        /// Take the owned handle out of the cell. Returns `None` if it was
        /// already transferred (consumed) by a previous encode.
        #[doc(hidden)]
        pub fn take(&self) -> Option<wire::PermissionCard> {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .take()
        }

        /// Whether the handle is still present (not yet transferred).
        #[doc(hidden)]
        pub fn is_present(&self) -> bool {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .is_some()
        }

        /// Run `f` with a shared reference to the owned handle, if it is still
        /// present.
        #[doc(hidden)]
        pub fn with_handle<R>(&self, f: impl FnOnce(&wire::PermissionCard) -> R) -> Option<R> {
            self.inner
                .lock()
                .unwrap_or_else(|poison| poison.into_inner())
                .as_ref()
                .map(f)
        }

        /// Identity of the shared cell, used to detect the same card appearing
        /// more than once in a single value tree.
        #[doc(hidden)]
        pub fn cell_id(&self) -> *const () {
            Arc::as_ptr(&self.inner).cast()
        }
    }

    impl std::fmt::Debug for GuestPermissionCardHandle {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let state = if self.is_present() {
                "present"
            } else {
                "consumed"
            };
            write!(f, "GuestPermissionCardHandle(<{state}>)")
        }
    }

    impl PartialEq for GuestPermissionCardHandle {
        fn eq(&self, other: &Self) -> bool {
            Arc::ptr_eq(&self.inner, &other.inner)
        }
    }

    impl serde::Serialize for GuestPermissionCardHandle {
        fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom(
                "permission-card handles cannot be serialized; transfer them through a WIT schema-value-tree",
            ))
        }
    }

    impl<'de> serde::Deserialize<'de> for GuestPermissionCardHandle {
        fn deserialize<D: serde::Deserializer<'de>>(_deserializer: D) -> Result<Self, D::Error> {
            Err(serde::de::Error::custom(
                "permission-card handles cannot be deserialized or forged from data",
            ))
        }
    }

    impl IntoSchema for GuestPermissionCardHandle {
        fn type_id() -> TypeId {
            TypeId::new("golem.core.PermissionCard")
        }

        fn register_in(_builder: &mut SchemaBuilder) -> SchemaType {
            SchemaType::permission_card(PermissionCardSpec::default())
        }

        fn to_value(&self) -> SchemaValue {
            SchemaValue::PermissionCard(self.clone())
        }
    }

    impl FromSchema for GuestPermissionCardHandle {
        fn from_value(value: &SchemaValue) -> Result<Self, FromSchemaError> {
            match value {
                SchemaValue::PermissionCard(h) => Ok(h.clone()),
                other => Err(FromSchemaError::shape_mismatch(
                    "permission-card",
                    format!("{other:?}"),
                    "PermissionCard",
                )),
            }
        }
    }
}

#[cfg(any(
    all(feature = "guest", not(feature = "host")),
    all(feature = "host", not(feature = "guest"))
))]
pub use model::*;

#[cfg(any(
    all(feature = "guest", not(feature = "host")),
    all(feature = "host", not(feature = "guest"))
))]
impl From<wire::Uuid> for uuid::Uuid {
    fn from(value: wire::Uuid) -> Self {
        uuid::Uuid::from_u64_pair(value.high_bits, value.low_bits)
    }
}

#[cfg(any(
    all(feature = "guest", not(feature = "host")),
    all(feature = "host", not(feature = "guest"))
))]
impl From<uuid::Uuid> for wire::Uuid {
    fn from(uuid: uuid::Uuid) -> Self {
        let (high_bits, low_bits) = uuid.as_u64_pair();
        Self {
            high_bits,
            low_bits,
        }
    }
}

#[cfg(any(
    all(feature = "guest", not(feature = "host")),
    all(feature = "host", not(feature = "guest"))
))]
impl From<uuid::Uuid> for wire::CardId {
    fn from(uuid: uuid::Uuid) -> Self {
        Self { uuid: uuid.into() }
    }
}