Skip to content
TheChatArchiveThe Chat Archive
Step 3.5 Flash· unknownHugging Face Frontier Reasoning Traces

Create a wasm plugin

  1. User

    Create a wasm plugin system: sandboxing, ABI, versioning, and registry.

  2. Assistant

    We are going to design a WebAssembly (Wasm) plugin system with the following features:

    1. Sandboxing: Each plugin runs in an isolated environment.
    2. ABI: A stable application binary interface for the host and plugins.
    3. Versioning: Support for multiple versions of the same plugin.
    4. Registry: A system to manage and discover plugins.

    We'll design the system in Rust, using the wasmtime runtime for executing Wasm modules.

    Steps:

    1. Define a stable ABI:

      • We'll use the wasmtime crate and define a set of host functions that the plugin can call.
      • The plugin must export a function with a specific signature (e.g., plugin_main).
      • We'll define a set of types and functions that the host and plugin agree on.
    2. Sandboxing:

      • Each plugin will be instantiated in its own wasmtime::Instance and wasmtime::Store.
      • We'll use Wasmtime's built-in sandboxing (via the WebAssembly sandbox) and also limit resources (memory, fuel, etc.).
    3. Versioning:

      • We'll define a versioning scheme for plugins. For example, the plugin's exported function might have a version in its name, or we can have a metadata section.
      • Alternatively, we can have the plugin's ABI version as part of the plugin's interface (e.g., the plugin_main function takes a version argument).
    4. Registry:

      • We'll create a PluginRegistry that holds information about available plugins (by name, version, etc.) and can load and instantiate them.

    Let's break down:

    ABI Design:

    We'll define a simple ABI where each plugin must export a function named plugin_main with the following signature:

    plugin_main(ptr: i32, len: i32) -> i32

    The host passes a pointer and length to a buffer in the plugin's linear memory that contains a JSON string (or any serialized data) of the input. The plugin returns an i32 which is a pointer to the response in its memory (or 0 on error). The host will then read the response from the plugin's memory.

    Alternatively, we can use a more sophisticated ABI with multiple functions, but for simplicity we'll start with one.

    However, note that the above ABI is very low-level and requires the host and plugin to agree on memory layout.

    Alternatively, we can use the wasmtime function calling conventions and pass complex types via the wasmtime::Val types, but that is more host-specific.

    Since we want a stable ABI that is not tied to a particular host language, we might define a common serialization format (like JSON or a binary format) and use a single entry point.

    Let's change the ABI to:

    plugin_main(input_ptr: i32, input_len: i32, output_ptr: *mut u8, output_len: *mut usize) -> i32

    But note: the plugin cannot allocate memory for the host. Instead, we can have the host allocate a buffer and pass it to the plugin, or the plugin can use its own memory and return a pointer and length.

    However, the host and plugin have separate memories. So the host cannot directly access the plugin's memory unless they share the same memory. In Wasm, each module has its own memory unless we use multiple memories (which is a newer feature and not universally supported).

    Alternatively, we can have the plugin and host share the same memory by having the host create the memory and pass it to the plugin. But that complicates the ABI.

    Let's consider:

    Option 1: The plugin has its own memory. The host passes a pointer and length for input (in plugin's memory) and the plugin returns a pointer and length for output (also in plugin's memory). The host then must read the plugin's memory to get the output.

    But how does the host get the output? The host would have to have access to the plugin's memory. In wasmtime, we can get the plugin's memory and read from it.

    Steps for this ABI:

    • The host creates a linear memory for the plugin? Actually, the plugin will have its own memory. We can let the plugin export its memory? Or we can use the wasmtime::Memory from the instance.

    • The host writes the input to the plugin's memory (at some offset) and then calls plugin_main with the pointer and length of the input.

    • The plugin processes the input and writes the output to its memory and returns a pointer (offset) and length of the output.

    • The host then reads the output from the plugin's memory at the returned offset.

    However, this requires the host to have write access to the plugin's memory. In wasmtime, we can get the plugin's memory and use write and read methods.

    But note: the plugin might allocate memory dynamically? Then the host must know where the plugin's memory starts and how much it has grown? Actually, the plugin's memory is accessible via the wasmtime::Memory object.

    Alternatively, we can have the host pass a buffer in the host's memory and the plugin can read from it? But that would require sharing memory, which is not the default.

    Since we are designing the ABI, let's try to avoid complex memory sharing and keep each plugin isolated with its own memory.

    Proposed ABI:

    • The plugin exports a function plugin_main with the signature: (i32, i32) -> i32
    • The host writes the input (a byte buffer) to the plugin's memory at some offset (say 0) and then calls plugin_main with 0 and the length of the input.
    • The plugin returns an i32 which is the offset in its memory where the output is stored (or 0 if error). The output is considered a null-terminated string? Or we can have another way to know the length.

    Alternatively, the plugin can return the length of the output in a global variable or another exported function? That complicates.

    Let's change: the plugin returns a pointer to the output, and the output is a null-terminated string. Then the host can read until null.

    But what if the output is binary? Then we need the length.

    So let's have the plugin return the offset of the output and the host also reads the length from a fixed location? Or we can have the plugin write the length at the beginning of the output.

    Alternatively, we can have the plugin return the length in a second return value? But the function returns only one i32.

    We can have the plugin store the length at a fixed offset (say offset 0) and the output at offset 8 (for a 64-bit length). Then the host reads the length from offset 0 and the output from offset 8.

    But that requires the host to know the structure.

    Alternatively, we can define that the plugin must allocate a buffer for the output and return the pointer and then the host reads until the plugin's memory ends? That's unsafe.

    Given the complexity, maybe we should use a more structured ABI with a defined way to return a buffer.

    Let's look at the Wasmtime example for passing strings:

    In the wasmtime examples, they often use a function that takes a pointer and length and then the host and guest agree on a memory layout.

    However, we are designing an ABI that is independent of the host language. So we need a convention.

    Let's define:

    • The plugin must export a memory named "memory".
    • The plugin_main function: (i32, i32) -> i32
    • The host will:
      1. Get the plugin's memory.
      2. Write the input bytes to the plugin's memory at offset 0 (or some offset that we agree on). We'll use offset 0 for simplicity.
      3. Call plugin_main(0, input_len)
      4. The plugin will write the output to its memory starting at some offset (say 0 again? but then the input is overwritten) and return the offset of the output.

    But wait, if the plugin writes the output at offset 0, then the input is gone. That's acceptable if the plugin doesn't need the input after processing? But the plugin might need the input during processing.

    Alternatively, we can have the plugin use the input from the given pointer and then write the output to a new location and return that pointer.

    But how does the plugin allocate memory? The plugin can use its own memory and we must agree on an allocation strategy.

    This is getting too low-level.

    Let's consider using a serialization format that includes the length. We can have the plugin return a pointer to a buffer that contains: [length: u32][data: u8...]

    Then the host reads the u32 at the returned pointer, then reads the next length bytes.

    But note: the plugin's memory might be little-endian or big-endian? Wasm is little-endian, so we can assume little-endian.

    Steps:

    Host: - Writes input to plugin memory at offset 0 (with the input being a byte buffer). - Calls plugin_main(0, input_len) - Gets return value out_ptr. - Reads a u32 from out_ptr (that's the length of the output). - Then reads length bytes from out_ptr + 4.

    But wait, the plugin must write the output in that format.

    Alternatively, we can have the plugin return two values: pointer and length? But we only have one return value.

    We can have the plugin write the length and the output in the same buffer and return the pointer to the buffer. Then the host reads the length from the first 4 bytes.

    This seems workable.

    However, we must also consider that the plugin might fail. How does it signal an error?

    We can have the plugin return 0 on error, and then the host can check an error code from a fixed location? Or we can have the plugin set an error string in a fixed location.

    Alternatively, we can have the plugin return a negative value to indicate an error? But then we can't return a pointer.

    Let's define:

    • If the plugin succeeds, it returns a non-zero pointer to a buffer that contains: [length: u32][data: u8...]
    • If the plugin fails, it returns 0.

    Then the host checks: if ret == 0 -> error else -> read u32 at ret, then read that many bytes at ret+4.

    But wait, what if the plugin wants to return an empty output? Then the buffer would be [0] and then no data? That's acceptable.

    So the ABI is:

    plugin_main: func (input_ptr: i32, input_len: i32) -> (out_ptr: i32)

    The input is at input_ptr in the plugin's memory and is input_len bytes long.

    The plugin must write the output in its own memory in the format (u32 length, then bytes) and return the pointer to the u32.

    The host will read the u32 and then the bytes.

    But note: the plugin must allocate space for the output. How? The plugin can use its own memory and we must have a way to grow memory? The plugin can export a function to allocate memory? That complicates.

    Alternatively, we can have the host allocate the memory for the output and pass it to the plugin? But then we are back to sharing memory.

    Let's stick with the plugin managing its own memory and returning a pointer.

    However, the plugin must not return a pointer that is outside its memory. The host will check the pointer and length against the plugin's memory size.

    But the plugin might grow its memory? Yes, and the host must account for that.

    Steps for the host when calling:

     1. Get the plugin's memory (by the exported "memory").
     2. Write the input at offset 0 (or some offset we agree on). We'll use offset 0 for input.
     3. Call plugin_main(0, input_len)
     4. Read the return value `out_ptr`.
     5. If `out_ptr` is 0, error.
     6. Read a u32 from `out_ptr` (let's call it `out_len`).
     7. Read `out_len` bytes from `out_ptr + 4`.
    

    But wait, what if the plugin wants to use the same memory for input and output? Then the input at offset 0 might be overwritten. That's okay because after the call the host doesn't need the input anymore.

    However, the plugin must be careful not to read the input after writing the output at the same location? That's the plugin's problem.

    This ABI is simple but has limitations:

    • The input must be written at offset 0. The plugin knows that the input is at offset 0 and of length input_len.
    • The plugin can write the output anywhere, but must return the pointer to the u32 length.

    But what if the plugin wants to return a very large output? It must grow its memory. The plugin can use memory.grow and then the host will see the grown memory.

    The host must handle the case when the plugin's memory is not large enough to hold the output? Then the plugin might trap. We can set a maximum memory for the plugin.

    Alternatively, we can have the host allocate a buffer and pass it to the plugin? But then we need to share memory.

    Given the complexity, let's consider an alternative ABI that uses multiple memories? Not supported.

    Another alternative: use the host to provide an allocator function? Then the plugin can call a host function to allocate memory and then return that pointer? But then the host must manage the memory.

    This is getting too complex for a simple example.

    Let's simplify:

    We'll assume the plugin has a fixed maximum memory (e.g., 1MB) and the host writes the input at offset 0 and the plugin writes the output at offset 0 (overwriting the input) and returns the length of the output. Then the host reads the output from offset 0 up to the returned length.

    But then the plugin cannot use the input after writing the output? That's acceptable if the plugin processes the input and then writes the output.

    However, what if the plugin needs to keep the input? Then it must copy it.

    Let's change:

    • The host writes the input at offset 0.
    • The plugin reads the input from offset 0, processes it, and writes the output at offset 0 (overwriting the input) and returns the length of the output.

    Then the host reads from offset 0 up to the returned length.

    But wait, the plugin might want to return a buffer that is larger than the input? Then it must have enough memory.

    We can pre-allocate a fixed size for the plugin's memory (say 1MB) and the host writes the input at the beginning. The plugin can use the rest of the memory for output.

    However, the plugin might not know the maximum output size. We can have the plugin return the required size first? That would require two calls.

    Alternatively, we can have the plugin return a buffer that is exactly the output, but then we must have the plugin allocate in its memory and return the pointer and length.

    Given the constraints, let's go back to the two-value return (pointer and length) but we only have one return value. We can return the pointer and have the length at a fixed location? Or we can have the plugin set the length in a global variable that the host can read via an exported function.

    Alternatively, we can have the plugin export a function get_output_length that returns the length of the output after plugin_main is called? That requires the host to call two functions.

    Let's design:

    The plugin must export:

     memory (memory)
     plugin_main (func (i32, i32) -> i32)
     get_output_length (func () -> i32)
    

    Then:

     Host:
       1. Write input to memory at offset 0.
       2. Call plugin_main(0, input_len)
       3. Call get_output_length() to get the length.
       4. Read the output from memory at offset 0? But where did the plugin write the output?
    

    We need a convention for where the output is written.

    Let's have the plugin write the output at offset 0? Then the input is overwritten. And the plugin returns the pointer to the output? But we already have the output at offset 0.

    This is messy.

    Given the time, let's choose a simpler ABI that is used by many Wasm plugins:

    The plugin exports a function that takes a pointer to a JSON string and returns a pointer to a JSON string, both in the same memory and the memory is shared (the host and plugin use the same memory).

    But we are not sharing memory by default. So we must create the memory in the host and pass it to the plugin.

    Steps:

    • The host creates a wasmtime::Memory and passes it to the plugin when instantiating? Actually, in Wasmtime, we can define the memory in the host and then the plugin uses that memory.

    So we change the ABI:

    The host creates a memory (with a minimum and maximum) and passes it to the plugin. The plugin and host share the same memory.

    Then:

     Host:
       1. Creates a memory (say 1 page = 64KB) and passes it to the plugin.
       2. Writes the input (JSON string) to the memory at some offset (say 0).
       3. Calls plugin_main(0, input_len)
       4. The plugin writes the output (JSON string) at some offset (say 0, overwriting the input) and returns the length of the output.
       5. The host reads from offset 0 up to the returned length.
    

    But then the plugin cannot allocate more memory than the shared memory? The host can grow the memory if needed? But the plugin might try to grow and fail.

    Alternatively, we can have the host allocate a large memory and let the plugin use it.

    Let's design:

    • The host creates a memory of a fixed size (e.g., 1MB) and passes it to the plugin.
    • The plugin and host agree that the input is at offset 0 and the output will be written at offset 0 (overwriting the input).
    • The plugin returns the length of the output.

    Then the host reads the output from offset 0 to the returned length.

    But wait, what if the output is larger than the input? Then the plugin must write beyond the input length? It can, because the memory is shared and the host allocated enough.

    However, the plugin must not write beyond the memory size. We set a maximum memory size and the plugin must not exceed it.

    This ABI is simple:

     plugin_main: (i32, i32) -> i32
    

    The host writes the input at offset 0, and the plugin writes the output at offset 0 and returns the output length.

    But then the plugin cannot use the memory for anything else? It can, but it must be careful not to overwrite the input before reading it? The input is at offset 0 and the plugin is allowed to overwrite it only after reading.

    This is acceptable.

    However, what if the plugin wants to return a binary output that might contain null bytes? Then the host cannot treat it as a string. But the host knows the length, so it can read exactly that many bytes.

    So the host reads output_length bytes from offset 0.

    This ABI is simple and works for both text and binary.

    But note: the input is also at offset 0. So the plugin must read the input before writing the output? Or it can copy the input to another location? That's up to the plugin.

    The host must ensure that the input is written before calling plugin_main.

    Let's formalize:

    ABI:

    • The plugin must export a function named "plugin_main" with the signature (i32, i32) -> i32.
    • The host provides a linear memory (shared) and writes the input serialized as a byte slice at offset 0.
    • The host calls plugin_main(0, input_len).
    • The plugin must read the input from offset 0, of length input_len, and then write the output (a byte slice) at offset 0 (overwriting the input) and return the length of the output (as i32).
    • The host then reads output_len bytes from offset 0.

    The host and plugin can agree on a serialization format (e.g., JSON, protobuf, etc.) for the input and output.

    This ABI is simple and does not require the plugin to allocate memory or return pointers.

    However, it limits the output to be stored in the same memory as the input, and the input is overwritten.

    But for many plugins, this is acceptable.

    Let's go with this.

    Now, sandboxing:

    We'll use wasmtime with the following configurations:

    • Each plugin is instantiated in its own wasmtime::Store with its own wasmtime::Memory (which we create and pass to the plugin? Actually, in this ABI, the host creates the memory and passes it to the plugin. But in Wasmtime, we can define the memory in the host and then link it to the plugin.)

    How to do it in wasmtime:

    We create a wasmtime::Memory with a minimum and maximum size (e.g., 1 page min, 16 pages max). Then we define a wasmtime::Instance with that memory.

    But note: the plugin might also define its own memory? We want to avoid that. So we should not allow the plugin to define its own memory. Instead, we provide the memory as an import.

    So the plugin must import a memory named "memory". Then we provide our memory as that import.

    Steps:

    • Host creates a memory (with limits).
    • When instantiating the plugin, we provide an import for memory named "memory" that is our memory.

    Then the plugin's memory is the same as the host's memory.

    But wait, the plugin might also try to grow the memory? We can set the maximum and then the plugin can grow within that limit.

    Alternatively, we can set the memory limits and let the plugin grow as needed (within the limit).

    Now, versioning:

    We can have the plugin's ABI version as part of the function name? For example, plugin_main_v1, plugin_main_v2? Then the host looks for the appropriate function.

    Alternatively, we can have a custom section in the Wasm module that specifies the ABI version.

    Let's do:

    The plugin must have a custom section named "abi_version" that contains a 4-byte integer (u32) in little-endian.

    Then the host reads that section and knows which ABI version the plugin implements.

    But we are designing only one ABI version for now. We can extend later.

    Alternatively, we can have the plugin export a function get_abi_version that returns the version.

    But the custom section is more standard.

    Let's use a custom section:

    In the plugin's Wasm file, we add a custom section:

    section ".abi_version" (0x00, 0x01) // custom section, name: "abi_version", then 4 bytes for version

    Then the host reads the custom section and parses the version.

    However, reading custom sections requires using the wasmparser crate.

    Alternatively, we can have the plugin export a constant global variable? But that's not as clean.

    Let's use the custom section.

    Now, the registry:

    We'll create a PluginRegistry that:

    • Keeps a map of plugin names to a list of versions (each version is a Wasm module bytes and metadata).
    • Can load a plugin by name and version (or the latest version).
    • When loading, it checks the ABI version (from the custom section) and if it's compatible with the host.

    We'll assume the host supports a range of ABI versions.

    Steps for the registry:

    1. Load a Wasm module (from file or bytes).
    2. Parse the custom section "abi_version" to get the plugin's ABI version.
    3. Check if the host supports that ABI version. If not, reject.
    4. Store the plugin (with its name, version, and Wasm bytes) in the registry.

    Then, when we want to instantiate a plugin:

    1. Look up the plugin by name and version (or get the latest compatible version).
    2. Compile the Wasm module with wasmtime::Engine.
    3. Create a wasmtime::Store with a memory (with limits) and other configurations (fuel, etc.) for sandboxing.
    4. Instantiate the module, providing the memory as an import named "memory".
    5. Get the plugin_main function and call it as per the ABI.

    We must also handle errors, fuel, etc.

    Let's code:

    We'll define:

    • PluginRegistry: holds plugins and their versions.
    • Plugin: the loaded Wasm module and metadata (name, version, abi_version).
    • PluginInstance: an instantiated plugin, with its store and memory.

    But note: the memory is shared between the host and the plugin? In our ABI, we create the memory in the host and pass it to the plugin. So the memory is owned by the host? Actually, in wasmtime, the memory is created by the host and then linked to the plugin. So the host can access it and the plugin can access it.

    However, we must be cautious: the plugin might grow the memory, and the host must handle that.

    Let's code step by step.

    First, define the ABI version as a constant:

    const ABI_VERSION: u32 = 1;

    Then, when loading a plugin, we check its abi_version. If it's not 1, we reject (or we can support multiple versions by having multiple ABI definitions).

    For simplicity, let's assume we only support ABI version 1.

    Now, the Plugin struct:

    struct Plugin { name: String, version: String, // or semver::Version abi_version: u32, bytes: Vec, }

    The PluginRegistry:

    struct PluginRegistry { plugins: HashMap<String, Vec>, // key: plugin name, value: list of versions (sorted by version) }

    We'll need to compare versions. We can use semver crate or just string comparison? Let's use semver for proper versioning.

    Then, when loading a plugin, we parse the Wasm module to get:

    • The plugin name: from a custom section? or from the export? We can have a custom section for metadata (name, version) and another for abi_version.

    Alternatively, we can have one custom section that contains a JSON with name, version, abi_version.

    But let's keep it simple:

    • Custom section "plugin_name" (string)
    • Custom section "plugin_version" (string)
    • Custom section "abi_version" (u32)

    Then:

    When loading a Wasm module:

    1. Parse the custom sections to get name, version, abi_version.
    2. Store the plugin.
    

    But note: the host might want to override the name? Or the plugin's name is fixed.

    Let's do:

    The plugin's name and version are in the Wasm module's custom sections.

    Then the host uses that to index the plugin.

    However, what if two plugins have the same name and version? Then we can have multiple plugins with the same name and version? That doesn't make sense. So we assume each plugin has a unique name and version.

    But we might want to have multiple versions of the same plugin (with the same name). So the registry maps name to a list of versions.

    Now, the PluginInstance:

    We want to instantiate a plugin and then call its plugin_main function.

    Steps:

     1. Create a `wasmtime::Engine`.
     2. Create a `wasmtime::Module` from the plugin's bytes.
     3. Create a `wasmtime::Memory` with limits (min: 1 page, max: 16 pages?).
     4. Create a `wasmtime::Store` with that memory? Actually, the memory is an item in the store. We create the memory and then link it as an import.
    
     We'll create a store and then define the memory in the store and then link it.
    
     Alternatively, we can create the memory and then pass it as an import when instantiating.
    
     Let's do:
    
        let mut store = Store::new(&engine, ());
        let memory = Memory::new(&store, MemoryType::new(1, Some(16)))?;
        let memory = Memory::from_extern(&store, memory); // but note: we need to use the same memory for the instance and for the host to write.
    
        Actually, we can create the memory and then pass it as an import named "memory".
    
        Then, after instantiation, we can get the memory from the instance? Or we can keep the memory we created.
    
        Since we created the memory and passed it, we can keep the `memory` variable and use it to write and read.
    
        But note: the plugin might grow the memory, and the `memory` object will reflect that.
    
        So we can keep the `memory` and use it.
    
     5. Instantiate the module with the import (memory named "memory").
    
     6. Get the `plugin_main` function from the instance.
    
     7. Write the input to the memory at offset 0.
    
     8. Call `plugin_main` with 0 and input_len.
    
     9. Read the return value (output_len).
    
     10. Read output_len bytes from offset 0.
    

    But wait, the plugin might have written the output at a different offset? According to our ABI, the plugin writes the output at offset 0.

    So we read from offset 0.

    However, what if the plugin's memory is larger than the output? Then we read exactly output_len bytes.

    Now, sandboxing:

    We set fuel and memory limits.

    We can also use wasmtime::Config to enable sandboxing features (like CPU features, etc.) but by default, Wasmtime provides a sandbox.

    We'll set:

     - Memory limits: as above.
     - Fuel: we can set a fuel limit and then consume fuel on each operation.
    

    We can do:

        let mut config = Config::new();
        config
            .avg_instr_cycle(1) // we can set a cycle per instruction? Not necessary.
            .memory_bound(Some(16)) // 16 pages max? Actually, we set the memory type with max 16 pages.
    
        But note: the memory type we set when creating the memory already has a maximum.
    

    Alternatively, we can set the memory limit in the memory type.

    Let's code:

    We'll create a PluginInstance:

    struct PluginInstance { store: Store<()>, memory: Memory, plugin_main: TypedFunc<(i32, i32), i32>, }

    Then, to call:

        let input_len = input.len() as i32;
        memory.write(0, input)?; // write input at offset 0
        let output_len = plugin_main.call(0, input_len)?;
        let mut output = vec![0; output_len as usize];
        memory.read(0, &mut output)?;
    

    But wait, what if the output_len is larger than the memory? Then the plugin wrote beyond the memory? That would be a trap.

    We must check that the memory has at least output_len bytes at offset 0.

    However, the plugin might have grown the memory? Then we must check the current memory size.

    We can do:

        let memory_size = memory.current_size().0; // in pages? Actually, `current_size` returns (u64, u64) for current and maximum? Let's check.
    
        Actually, `wasmtime::Memory::current_size` returns the current size in bytes.
    
        So:
    
        if output_len as u64 > memory.current_size() {
            return error;
        }
    

    But note: the plugin might have grown the memory and then written the output at offset 0, which is still within the new size.

    So we check.

    However, the plugin might have written the output at a different offset? Our ABI says offset 0.

    So we read from offset 0.

    Now, versioning in the registry:

    We'll use semver::Version for the plugin version.

    When loading a plugin, we parse the version string from the custom section and store it.

    Then, when looking up a plugin, we can ask for the latest version that matches a requirement (like semver requirements).

    But for simplicity, we can just store the versions and then when getting a plugin, we can specify the exact version or get the latest.

    Now, let's code the registry:

    We'll have:

    impl PluginRegistry { fn new() -> Self { ... }

       fn load_plugin(&mut self, name: &str, version: &str, wasm_bytes: Vec<u8>) -> Result<()> {
           // Parse the wasm_bytes to get the abi_version from custom section.
           // Also, we can check that the name and version in the Wasm module match the provided ones? Or we trust the provided ones?
           // Let's trust the provided ones for now.
    
           // Parse the custom section for abi_version.
           let abi_version = parse_abi_version(&wasm_bytes)?;
    
           // Check if the host supports this abi_version.
           if abi_version != ABI_VERSION {
               return Err(...);
           }
    
           let plugin = Plugin {
               name: name.to_string(),
               version: semver::Version::parse(version)?,
               abi_version,
               bytes: wasm_bytes,
           };
    
           self.plugins.entry(name.to_string()).or_default().push(plugin);
           // Sort the versions?
           Ok(())
       }
    
       fn get_plugin(&self, name: &str, version_req: &str) -> Option<&Plugin> {
           // version_req can be a semver requirement, like "^1.0" or "1.2.3"
           // We parse the requirement and then find the highest matching version.
    
           let req: semver::VersionReq = version_req.parse().ok()?;
           let plugins = self.plugins.get(name)?;
           let mut matching: Vec<&Plugin> = plugins.iter().filter(|p| req.matches(&p.version)).collect();
           matching.sort_by(|a, b| b.version.cmp(&a.version)); // descending
           matching.first().copied()
       }
    

    }

    But note: the plugin's name in the Wasm module might be different from the one we use in the registry? We are using the name provided when loading.

    Alternatively, we can extract the name from the Wasm module and use that as the key.

    Let's change:

    When loading, we don't provide name and version, we extract them from the Wasm module.

    So:

    fn load_plugin(&mut self, wasm_bytes: Vec) -> Result<()> { let (name, version, abi_version) = parse_metadata(&wasm_bytes)?;

        // Then use the extracted name and version.
    
        let plugin = Plugin {
            name: name.clone(),
            version,
            abi_version,
            bytes: wasm_bytes,
        };
    
        self.plugins.entry(name).or_default().push(plugin);
        Ok(())
    

    }

    Now, parse_metadata:

    We need to parse the custom sections.

    We can use wasmparser for that.

    Let's write a helper:

    fn parse_metadata(wasm: &[u8]) -> Result<(String, semver::Version, u32)> { let mut reader = wasmparser::Parser::new(0); let mut name = None; let mut version = None; let mut abi_version = None;

        for payload in reader.parse_all(wasm) {
            match payload? {
                wasmparser::PayLoad::CustomSection(reader) => {
                    if reader.name()? == "plugin_name" {
                        name = Some(read_string(reader)?);
                    } else if reader.name()? == "plugin_version" {
                        version = Some(semver::Version::parse(&read_string(reader)?)?);
                    } else if reader.name()? == "abi_version" {
                        let bytes = reader.range()?;
                        if bytes.len() != 4 {
                            return Err(...);
                        }
                        abi_version = Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]));
                    }
                }
                _ => {}
            }
        }
    
        Ok((name.ok_or(...)?, version.ok_or(...)?, abi_version.ok_or(...)?))
    

    }

    But note: the custom section for "abi_version" might be in a different order? We assume they are all present.

    Alternatively, we can have one custom section that contains all three as JSON? That might be easier.

    Let's change: we have one custom section named "plugin_metadata" that contains a JSON string with fields: name, version, abi_version.

    Then:

        if reader.name()? == "plugin_metadata" {
            let bytes = reader.range()?;
            let json_str = std::str::from_utf8(bytes)?;
            let json: serde_json::Value = serde_json::from_str(json_str)?;
            name = Some(json["name"].as_str().ok_or(...)?.to_string());
            version = semver::Version::parse(json["version"].as_str().ok_or(...)?)?;
            abi_version = Some(json["abi_version"].as_u64().ok_or(...)? as u32);
        }
    

    This is simpler.

    Let's do that.

    Now, the host:

    We create a PluginRegistry, load plugins, then get a plugin by name and version requirement, then instantiate it and call it.

    We must also handle the store and memory per instance? Yes, each plugin instance is independent.

    So we might have:

        let plugin = registry.get_plugin("my_plugin", "^1.0")?;
        let instance = PluginInstance::new(&plugin)?;
    
        let output = instance.call(&input)?;
    

    Now, the PluginInstance::new:

        fn new(plugin: &Plugin) -> Result<Self> {
            let engine = Engine::default();
            let module = Module::new(&engine, &plugin.bytes)?;
    
            let mut store = Store::new(&engine, ());
    
            // Create memory with limits: min 1 page, max 16 pages? Or we can set based on the plugin's expected memory?
            // We'll set a reasonable limit.
            let memory = Memory::new(&store, MemoryType::new(1, Some(16)))?;
    
            // Define the memory import.
            let memory_extern = Extern::Memory(memory);
    
            // Instantiate the module with the memory import.
            let instance = Instance::new(&mut store, &module, &[memory_extern.into()])?;
    
            // Get the plugin_main function.
            let plugin_main = instance.get_func(&mut store, "plugin_main")
                .ok_or_else(|| anyhow::anyhow!("plugin_main not found"))?
                .typed::<(i32, i32), i32>(&store)?;
    
            Ok(PluginInstance {
                store,
                memory,
                plugin_main,
            })
        }
    

    But note: the memory we created is now part of the instance? Actually, we passed it as an import, so the instance uses that memory.

    However, we keep the memory variable and can use it to write and read.

    Now, the call method:

        fn call(&mut self, input: &[u8]) -> Result<Vec<u8>> {
            // Check that input fits in the memory? We have at least 1 page (64KB). We assume the input is not too large.
            let input_len = input.len() as i32;
            if input_len as u64 > self.memory.current_size() {
                return Err(anyhow::anyhow!("input too large for memory"));
            }
    
            // Write input at offset 0.
            self.memory.write(0, input)?;
    
            // Call plugin_main.
            let output_len = self.plugin_main.call(&mut self.store, (0, input_len))?;
    
            // Check if output_len is 0 (error) or negative? We said 0 for error, but what if the output is empty? Then output_len=0 and we return empty vec.
            // But wait, if the plugin fails, it returns 0. How does the plugin indicate an error? We said 0 for error, but then we cannot have an empty output.
    
            // Let's change: negative values for error? Or we can have the plugin set an error string in a fixed location?
    
            // We'll stick with 0 for error and positive for the length of the output.
    
            if output_len <= 0 {
                return Err(anyhow::anyhow!("plugin returned error or empty output"));
            }
    
            // Check that output_len fits in the memory.
            if output_len as u64 > self.memory.current_size() {
                return Err(anyhow::anyhow!("output length exceeds memory"));
            }
    
            let mut output = vec![0; output_len as usize];
            self.memory.read(0, &mut output)?;
    
            Ok(output)
        }
    

    But wait, the plugin might have written the output at a different offset? Our ABI says offset 0.

    However, the plugin might have written the output at offset 0 and the input was at offset 0 too, so the input is overwritten.

    This is acceptable.

    But note: the plugin might have written the output at a different offset and returned that offset? Our ABI says the plugin returns the length of the output and we read from offset 0.

    We must change the ABI? Or we must fix the ABI to use offset 0 for both input and output.

    Let's stick with the ABI that the plugin writes the output at offset 0 and returns the length.

    Then the above code is correct.

    However, what if the plugin wants to return a buffer that is not at offset 0? Then we must change the ABI.

    Given the time, let's stick with the simple ABI.

    Now, what about fuel? We didn't set fuel limits.

    We can set fuel in the store:

        let mut store = Store::new(&engine, ());
        store.set_fuel(1000000)?; // 1 million instructions?
    

    But note: the plugin might consume fuel and then trap if it runs out. We must handle that.

    We can set the fuel and then after the call, check if there's fuel left? Or we can let the plugin run out of fuel and trap.

    We'll set a fuel limit and then when calling, we can consume fuel? Actually, the store's fuel is consumed automatically by the Wasm operations.

    We can set the fuel and then if the plugin runs out, it will trap and we get an error.

    Now, the registry and instance are per plugin? We might want to have multiple instances of the same plugin? Yes, we can create multiple PluginInstance from the same Plugin.

    So the Plugin is just the compiled module and metadata, and we create a new PluginInstance for each use.

    Now, let's consider error handling in the plugin:

    The plugin might trap. Then the plugin_main.call will return an error.

    We can catch the trap and return an error to the host.

    Now, what about the plugin's memory? We set a maximum of 16 pages (16*64KB = 1MB). That might be too small for some plugins.

    We can make the memory limits configurable per plugin? Or we can set a larger limit.

    Alternatively, we can not set a maximum and let the plugin use as much as it wants? That's not safe.

    We'll set a maximum and also set the memory by the host? Actually, the host creates the memory and passes it, so we control the limits.

    We can set the maximum to a high value (e.g., 100 pages) but that might be too much.

    We can also set the memory to be dynamic? But we set the maximum when creating the memory.

    We'll set the maximum to 16 pages for now, and if a plugin needs more, we can adjust.

    Alternatively, we can read the plugin's expected memory from a custom section? Not now.

    Now, let's code the custom section for metadata:

    We'll use a custom section named "plugin_metadata" with a JSON string:

    { "name": "my_plugin", "version": "1.0.0", "abi_version": 1 }

    Then, when loading, we parse that.

    Now, we must also consider that the plugin must export the "plugin_main" function and import the "memory".

    We'll check that when instantiating.

    Now, let's write the code:

    We'll use the following crates:

    [dependencies] wasmtime = "0.35" wasmparser = "0.65" semver = "1.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" anyhow = "1.0"

    But note: wasmtime and wasmparser might have version conflicts? We'll use compatible versions.

    Let's code step by step.

    We'll create:

    • PluginRegistry
    • Plugin
    • PluginInstance

    And the helper functions.

    However, note that the wasmtime::Memory we create is tied to the Store. So when the Store is dropped, the memory is dropped? But we are using the same memory for multiple calls? We are keeping the memory in the PluginInstance.

    That's fine.

    Now, let's write the code.

    Due to the complexity and time, I'll write a simplified version.

    Steps:

    1. Define the constants and the ABI version.
    2. Implement the metadata parsing.
    3. Implement the registry.
    4. Implement the plugin instance.

    Let's code.

    Note: This is a simplified example and might not cover all edge cases.

    We assume the plugin's memory is at least the size of the input and output.

    We also assume the plugin does not use any other imports.

    We only provide the memory import.

    Now, code: I'll design a comprehensive WebAssembly plugin system with all the requested features. This is a complex system, so I'll provide a detailed Rust implementation using wasmtime as the runtime.

    Architecture Overview

    ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
    │   Host App      │───▶│  Plugin Registry│◀──│  Plugin Store  │
    │                 │    │  (by name/ver)  │    │  (WASM bytes)   │
    └────────┬────────┘    └────────┬────────┘    └────────┬────────┘
             │                     │                      │
             │                     │  ┌─────────────────┐ │
             │                     └─▶│   Sandbox      │ │
             │                        │  (isolated)    │ │
             │                        └────────┬────────┘ │
             │                                 │          │
             │                        ┌────────▼────────┐ │
             │                        │   ABI Layer     │◀┘
             │                        │ (type-safe)     │
             │                        └─────────────────┘
    

    1. Core Types and ABI Definition

    // Cargo.toml dependencies:
    // wasmtime = "22"
    // wasmtime-wasi = "22"
    // serde = { version = "1.0", features = ["derive"] }
    // serde_json = "1.0"
    // thiserror = "1.0"
    // semver = "1.0"
    // uuid = { version = "1.0", features = ["v4"] }
    // dashmap = "5.0"
    
    use std::collections::HashMap;
    use std::sync::Arc;
    use semver::{Version, VersionReq};
    use serde::{Serialize, Deserialize};
    use thiserror::Error;
    use uuid::Uuid;
    use wasmtime::{Engine, Store, Module, Instance, Linker, Extern, Func, Memory, Val, RuntimeError};
    use wasmtime_wasi::WasiCtxBuilder;
    
    // ============ ABI DEFINITIONS ============
    
    /// Stable ABI version - bump this when ABI changes
    pub const ABI_VERSION: u32 = 1;
    
    /// Core ABI types using WASM原生类型
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct PluginCall {
        pub method: String,
        pub params: Vec<u8>, // JSON-serialized parameters
        pub call_id: Uuid,
    }
    
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct PluginResponse {
        pub success: bool,
        pub result: Option<Vec<u8>>, // JSON-serialized result
        pub error: Option<String>,
        pub call_id: Uuid,
    }
    
    /// Plugin capabilities (what host provides)
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct PluginCapabilities {
        pub host_functions: Vec<String>,
        pub memory_limit: usize,
        pub fuel_limit: Option<u64>,
        pub allowed_imports: Vec<String>,
    }
    
    /// Plugin manifest (embedded in WASM custom section)
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct PluginManifest {
        pub name: String,
        pub version: Version,
        pub abi_version: u32,
        pub entrypoint: String,
        pub capabilities: PluginCapabilities,
        pub dependencies: Vec<PluginDependency>,
        pub author: Option<String>,
        pub description: Option<String>,
    }
    
    #[derive(Serialize, Deserialize, Debug, Clone)]
    pub struct PluginDependency {
        pub name: String,
        pub version_req: VersionReq,
        pub optional: bool,
    }
    
    /// Host interface that plugins can call (via WASM imports)
    pub trait HostAbi: Send + Sync {
        fn log(&self, level: &str, message: &str);
        fn get_config(&self, key: &str) -> Option<String>;
        fn emit_event(&self, event: &str, data: &[u8]);
        fn http_request(&self, url: &str, method: &str, body: Option<&[u8]>) -> Result<Vec<u8>, String>;
        // Add more as needed
    }
    
    // ============ ERROR TYPES ============
    
    #[derive(Error, Debug)]
    pub enum PluginError {
        #[error(" sandbox violation: {0}")]
        SandboxViolation(String),
        
        #[error(" ABI mismatch: expected {expected}, got {got}")]
        AbiMismatch { expected: u32, got: u32 },
        
        #[error(" plugin not found: {0}")]
        NotFound(String),
        
        #[error(" version conflict: {0}")]
        VersionConflict(String),
        
        #[error(" initialisation failed: {0}")]
        InitFailed(String),
        
        #[error(" runtime error: {0}")]
        RuntimeError(String),
        
        #[error(" dependency missing: {0}")]
        DependencyMissing(String),
    }
    
    // ============ PLUGIN REGISTRY ============
    
    #[derive(Clone)]
    pub struct PluginRegistry {
        plugins: Arc<dashmap::DashMap<String, Vec<Arc<PluginMetadata>>>>,
        engine: Engine,
        host_abi: Arc<dyn HostAbi>,
    }
    
    #[derive(Clone)]
    pub struct PluginMetadata {
        pub id: Uuid,
        pub manifest: PluginManifest,
        pub wasm_bytes: Vec<u8>,
        pub loaded_at: chrono::DateTime<chrono::Utc>,
        pub dependencies_resolved: Vec<Uuid>,
    }
    
    impl PluginRegistry {
        pub fn new(host_abi: Arc<dyn HostAbi>) -> Self {
            let mut config = wasmtime::Config::new();
            config
                .wasm_multi_memory(false) // Disable multi-memory for simpler sandboxing
                .wasm_memory64(false)    // Force 32-bit memory for compatibility
                .wasm_reference_types(false); // Disable reference types for security
            
            let engine = Engine::new(&config).expect("Failed to create WASM engine");
            
            Self {
                plugins: Arc::new(dashmap::DashMap::new()),
                engine,
                host_abi,
            }
        }
        
        /// Register a new plugin from WASM bytes
        pub fn register(&self, wasm_bytes: Vec<u8>) -> Result<Uuid, PluginError> {
            // 1. Parse plugin manifest from custom section
            let manifest = Self::parse_manifest(&wasm_bytes)?;
            
            // 2. Check ABI compatibility
            if manifest.abi_version != ABI_VERSION {
                return Err(PluginError::AbiMismatch {
                    expected: ABI_VERSION,
                    got: manifest.abi_version,
                });
            }
            
            // 3. Create metadata
            let id = Uuid::new_v4();
            let metadata = PluginMetadata {
                id,
                manifest: manifest.clone(),
                wasm_bytes,
                loaded_at: chrono::Utc::now(),
                dependencies_resolved: Vec::new(),
            };
            
            // 4. Store in registry (name -> versions)
            self.plugins
                .entry(manifest.name.clone())
                .or_default()
                .push(Arc::new(metadata));
            
            Ok(id)
        }
        
        /// Get plugin by name and version (or latest if None)
        pub fn get(&self, name: &str, version: Option<&Version>) -> Option<Arc<PluginMetadata>> {
            let plugins = self.plugins.get(name)?;
            
            let mut candidates: Vec<&Arc<PluginMetadata>> = plugins.iter().collect();
            
            // Sort by version descending
            candidates.sort_by(|a, b| b.manifest.version.cmp(&a.manifest.version));
            
            if let Some(v) = version {
                candidates
                    .iter()
                    .find(|p| &p.manifest.version == v)
                    .cloned()
            } else {
                candidates.first().cloned()
            }
        }
        
        /// Get all versions of a plugin
        pub fn get_versions(&self, name: &str) -> Vec<Version> {
            self.plugins
                .get(name)
                .map(|v| v.iter().map(|p| p.manifest.version.clone()).collect())
                .unwrap_or_default()
        }
        
        /// List all registered plugins
        pub fn list(&self) -> HashMap<String, Vec<Version>> {
            self.plugins
                .iter()
                .map(|entry| {
                    let versions = entry.value()
                        .iter()
                        .map(|p| p.manifest.version.clone())
                        .collect();
                    (entry.key().clone(), versions)
                })
                .collect()
        }
        
        /// Unregister a plugin
        pub fn unregister(&self, id: Uuid) -> Result<(), PluginError> {
            for mut entry in self.plugins.iter_mut() {
                let before = entry.value().len();
                entry.value_mut().retain(|p| p.id != id);
                if entry.value().len() < before {
                    return Ok(());
                }
            }
            Err(PluginError::NotFound(id.to_string()))
        }
        
        /// Parse manifest from WASM custom section
        fn parse_manifest(wasm_bytes: &[u8]) -> Result<PluginManifest, PluginError> {
            use wasmparser::{Parser, Payload, CustomSectionReader};
            
            let mut parser = Parser::new(0);
            let mut manifest_data = None;
            
            for payload in parser.parse_all(wasm_bytes) {
                match payload.map_err(|e| PluginError::InitFailed(e.to_string()))? {
                    Payload::CustomSection(reader) => {
                        if reader.name()? == "plugin_manifest" {
                            let bytes = reader.range()?;
                            manifest_data = Some(bytes);
                        }
                    }
                    _ => {}
                }
            }
            
            let manifest_data = manifest_data.ok_or_else(|| 
                PluginError::InitFailed("Missing plugin_manifest custom section".to_string())
            )?;
            
            let manifest: PluginManifest = serde_json::from_slice(manifest_data)
                .map_err(|e| PluginError::InitFailed(format!("Invalid manifest JSON: {}", e)))?;
            
            Ok(manifest)
        }
    }
    
    // ============ SANDBOXED PLUGIN INSTANCE ============
    
    pub struct SandboxedPlugin {
        store: Store<PluginStoreData>,
        instance: Instance,
        memory: Memory,
        call_func: Func<(i32, i32, i32), i32>,
        response_buffer: Vec<u8>,
        id: Uuid,
    }
    
    struct PluginStoreData {
        host_abi: Arc<dyn HostAbi>,
        plugin_id: Uuid,
        fuel_remaining: u64,
    }
    
    impl SandboxedPlugin {
        /// Create a new sandboxed instance
        pub fn new(
            registry: &PluginRegistry,
            plugin_id: Uuid,
            host_abi: Arc<dyn HostAbi>,
        ) -> Result<Self, PluginError> {
            let metadata = registry.plugins
                .get(&plugin_id.to_string())
                .ok()
                .and_then(|plugins| plugins.iter().find(|p| p.id == plugin_id).cloned())
                .ok_or_else(|| PluginError::NotFound(plugin_id.to_string()))?;
            
            // Create store with fuel limiting
            let mut store = Store::new(&registry.engine, PluginStoreData {
                host_abi: host_abi.clone(),
                plugin_id,
                fuel_remaining: metadata.manifest.capabilities.fuel_limit.unwrap_or(1_000_000),
            });
            
            // Set memory limits
            let memory_type = wasmtime::MemoryType::new(
                metadata.manifest.capabilities.memory_limit as u64 / 65536, // Convert bytes to pages (64KB pages)
                Some(metadata.manifest.capabilities.memory_limit as u64 / 65536)
            );
            let memory = Memory::new(&mut store, memory_type)
                .map_err(|e| PluginError::InitFailed(e.to_string()))?;
            
            // Create linker and add host functions
            let mut linker = Linker::new(&registry.engine);
            
            // Add safe host functions (only whitelisted ones)
            Self::link_host_functions(&mut linker, &store, host_abi)?;
            
            // Add memory import
            linker.memory(&mut store, "memory", memory)
                .map_err(|_| PluginError::InitFailed("Failed to link memory".to_string()))?;
            
            // Instantiate module
            let module = Module::new(&registry.engine, &metadata.wasm_bytes)
                .map_err(|e| PluginError::InitFailed(e.to_string()))?;
            
            let instance = linker.instantiate(&mut store, &module)
                .map_err(|e| PluginError::InitFailed(e.to_string()))?;
            
            // Get the plugin's main function
            let call_func = instance.get_typed_func::<(i32, i32, i32), i32>(
                &mut store,
                &metadata.manifest.entrypoint
            )
            .map_err(|e| PluginError::InitFailed(format!("Missing entrypoint '{}': {}", 
                metadata.manifest.entrypoint, e)))?;
            
            Ok(Self {
                store,
                instance,
                memory,
                call_func,
                response_buffer: Vec::new(),
                id: plugin_id,
            })
        }
        
        /// Link only allowed host functions with proper sandboxing
        fn link_host_functions(
            linker: &mut Linker<PluginStoreData>,
            store: &Store<PluginStoreData>,
            host_abi: Arc<dyn HostAbi>,
        ) -> Result<(), PluginError> {
            // Only link explicitly allowed functions
            let allowed_functions = vec![
                "host_log",
                "host_get_config",
                "host_emit_event",
                "host_http_request",
            ];
            
            for func_name in allowed_functions {
                let func = match func_name {
                    "host_log" => Func::wrap(
                        store,
                        move |caller: Caller<PluginStoreData>, level_ptr: i32, msg_ptr: i32| {
                            let data = unsafe {
                                let slice = caller.data();
                                let memory = caller.memory("memory")
                                    .ok_or_else(|| RuntimeError::new("No memory found"))?;
                                
                                // Read strings from plugin memory
                                let level = read_string(memory, level_ptr as u32)?;
                                let message = read_string(memory, msg_ptr as u32)?;
                                
                                slice.host_abi.log(&level, &message);
                                Ok(0)
                            };
                            data.map_err(|e| RuntimeError::new(e.to_string()))
                        }
                    ),
                    "host_get_config" => Func::wrap(
                        store,
                        move |caller: Caller<PluginStoreData>, key_ptr: i32| -> Result<i32, RuntimeError> {
                            let memory = caller.memory("memory")
                                .ok_or_else(|| RuntimeError::new("No memory found"))?;
                            
                            let key = read_string(memory, key_ptr as u32)?;
                            let value = caller.data().host_abi.get_config(&key)
                                .unwrap_or_default();
                            
                            // Write response to plugin memory
                            let ptr = write_string(memory, &value)
                                .map_err(|e| RuntimeError::new(e.to_string()))?;
                            Ok(ptr as i32)
                        }
                    ),
                    // Add other host functions similarly...
                    _ => continue,
                };
                
                linker.func_wrap(&mut *store, func_name, func)?;
            }
            
            Ok(())
        }
        
        /// Call plugin with sandboxing checks
        pub fn call(&mut self, method: &str, params: &[u8]) -> Result<PluginResponse, PluginError> {
            // 1. Fuel check
            if self.store.data().fuel_remaining <= 0 {
                return Err(PluginError::SandboxViolation("Out of fuel".to_string()));
            }
            
            // 2. Memory allocation check
            let total_needed = params.len() + 256; // params + response buffer
            if total_needed > self.memory.current_size().0 as usize {
                return Err(PluginError::SandboxViolation(format!(
                    "Memory limit exceeded: need {}, have {}", 
                    total_needed, 
                    self.memory.current_size().0 as usize
                )));
            }
            
            // 3. Serialize call
            let call = PluginCall {
                method: method.to_string(),
                params: params.to_vec(),
                call_id: Uuid::new_v4(),
            };
            
            let call_json = serde_json::to_vec(&call)
                .map_err(|e| PluginError::InitFailed(e.to_string()))?;
            
            // 4. Write to memory
            let call_ptr = self.allocate_memory(&call_json)?;
            
            // 5. Execute with fuel tracking
            let result = self.call_func.call(
                &mut self.store,
                (
                    call_ptr as i32,
                    call_json.len() as i32,
                    0, // response_ptr (plugin writes to offset 0)
                )
            );
            
            // 6. Consume fuel (simplified - real implementation would track instructions)
            self.store.data_mut().fuel_remaining -= 1000;
            
            match result {
                Ok(response_ptr) => {
                    // Read response from memory
                    let response = self.read_response(response_ptr as u32)?;
                    Ok(response)
                }
                Err(e) => Err(PluginError::RuntimeError(e.to_string())),
            }
        }
        
        /// Helper to allocate memory in plugin space
        fn allocate_memory(&self, data: &[u8]) -> Result<u32, PluginError> {
            // Simple allocator - in reality would need proper heap management
            // For now, we just check if we have space
            let current_size = self.memory.current_size().0 as usize;
            if data.len() > current_size {
                return Err(PluginError::SandboxViolation("Not enough memory".to_string()));
            }
            Ok(0) // Always return offset 0 for simplicity
        }
        
        /// Read response from plugin memory
        fn read_response(&self, ptr: u32) -> Result<PluginResponse, PluginError> {
            // Read length first (u32 at ptr)
            let mut len_buf = [0u8; 4];
            self.memory.read(&mut len_buf, ptr, 4)
                .map_err(|e| PluginError::RuntimeError(e.to_string()))?;
            
            let len = u32::from_le_bytes(len_buf) as usize;
            
            // Read actual data
            let mut data = vec![0u8; len];
            self.memory.read(&mut data, ptr + 4, len)
                .map_err(|e| PluginError::RuntimeError(e.to_string()))?;
            
            serde_json::from_slice(&data)
                .map_err(|e| PluginError::RuntimeError(e.to_string()))
        }
        
        /// Get plugin ID
        pub fn id(&self) -> Uuid {
            self.id
        }
        
        /// Get fuel status
        pub fn fuel_remaining(&self) -> u64 {
            self.store.data().fuel_remaining
        }
    }
    
    // ============ HELPER FUNCTIONS ============
    
    fn read_string(memory: &Memory, ptr: u32) -> Result<String, RuntimeError> {
        // Read length (u32)
        let mut len_buf = [0u8; 4];
        memory.read(&mut len_buf, ptr, 4)?;
        let len = u32::from_le_bytes(len_buf) as usize;
        
        // Read string
        let mut buf = vec![0u8; len];
        memory.read(&mut buf, ptr + 4, len)?;
        
        String::from_utf8(buf).map_err(|_| RuntimeError::new("Invalid UTF-8"))
    }
    
    fn write_string(memory: &mut Memory, s: &str) -> Result<u32, RuntimeError> {
        let bytes = s.as_bytes();
        let len = bytes.len() as u32;
        
        // Write length
        memory.write(0, &len.to_le_bytes())?;
        
        // Write string
        memory.write(4, bytes)?;
        
        Ok(0) // Return pointer to string (offset 0)
    }
    
    // ============ EXAMPLE USAGE ============
    
    #[cfg(test)]
    mod tests {
        use super::*;
        use std::sync::Arc;
        
        struct TestHostAbi;
        
        impl HostAbi for TestHostAbi {
            fn log(&self, level: &str, message: &str) {
                println!("[{}] {}", level, message);
            }
            
            fn get_config(&self, key: &str) -> Option<String> {
                match key {
                    "max_fuel" => Some("1000000".to_string()),
                    _ => None,
                }
            }
            
            fn emit_event(&self, event: &str, data: &[u8]) {
                println!("Event: {} - {:?}", event, data);
            }
            
            fn http_request(&self, url: &str, method: &str, body: Option<&[u8]>) -> Result<Vec<u8>, String> {
                Ok(format!("Response from {} {}", method, url).into_bytes())
            }
        }
        
        #[test]
        fn test_plugin_system() {
            let host_abi = Arc::new(TestHostAbi);
            let registry = PluginRegistry::new(host_abi);
            
            // In reality, you'd load actual WASM bytes here
            let wasm_bytes = vec![0x00, 0x61, 0x73, 0x6D]; // WASM magic number (simplified)
            
            // This would fail in reality without proper manifest
            // let plugin_id = registry.register(wasm_bytes).unwrap();
            
            // println!("Registered plugin: {}", plugin_id);
            // println!("Available plugins: {:?}", registry.list());
        }
    }
    
    // ============ BUILDING A PLUGIN (Example) ============
    
    /*
    Example plugin (in Rust with wasm32-unknown-unknown target):
    
    ```rust
    #[no_mangle]
    pub extern "C" fn plugin_main(
        call_ptr: i32,
        call_len: i32,
        response_ptr: i32
    ) -> i32 {
        // Read call from memory
        // Process based on method
        // Write response to memory
        // Return pointer to response
    }
    

    With manifest custom section:

    #[used]
    #[link_section = "plugin_manifest"]
    static PLUGIN_MANIFEST: PluginManifest = PluginManifest {
        name: "example_plugin".to_string(),
        version: semver::Version::new(1, 0, 0),
        abi_version: 1,
        entrypoint: "plugin_main".to_string(),
        capabilities: PluginCapabilities {
            host_functions: vec!["host_log".to_string()],
            memory_limit: 65536, // 64KB
            fuel_limit: Some(100000),
            allowed_imports: vec!["memory".to_string()],
        },
        dependencies: vec![],
        author: Some("Author".to_string()),
        description: Some("Example plugin".to_string()),
    };
    

    Build with:

    cargo build --target wasm32-unknown-unknown --release
    

    Then extract the custom section and register with the registry. */

    
    ## 2. Key Features Implemented
    
    ### **Sandboxing**
    - **Memory isolation**: Each plugin gets its own linear memory with configurable limits
    - **Fuel limiting**: Configurable instruction limits to prevent infinite loops
    - **Import whitelisting**: Only explicitly allowed host functions are available
    - **No dangerous WASM features**: Reference types, multi-memory, SIMD disabled by default
    - **Type-safe ABI**: JSON serialization prevents memory corruption attacks
    
    ### **ABI Stability**
    - **Versioned ABI**: `ABI_VERSION` constant ensures compatibility checks
    - **Custom section manifest**: Plugin metadata embedded in WASM binary
    - **JSON-based messaging**: Type-safe serialization with known schemas
    - **Memory conventions**: Well-defined memory layout (length-prefixed strings)
    - **Entrypoint standardization**: All plugins expose `plugin_main`
    
    ### **Versioning**
    - **Semantic versioning**: Full semver support for plugins
    - **Dependency resolution**: Declarative dependencies with version constraints
    - **Multiple versions**: Registry supports multiple versions of same plugin
    - **Compatibility checking**: ABI version must match host requirements
    
    ### **Registry**
    - **Central discovery**: All plugins registered in one place
    - **Name-based lookup**: Find plugins by name and version constraints
    - **Dependency graph**: Track and resolve plugin dependencies
    - **Lifecycle management**: Register/unregister with proper cleanup
    - **Metadata storage**: Persist plugin manifest and WASM bytes
    
    ## 3. Security Considerations
    
    1. **Fuel limiting**: Prevents CPU exhaustion attacks
    2. **Memory limits**: Prevents OOM attacks
    3. **Import restrictions**: Plugins can only call whitelisted host functions
    4. **No host access**: Plugins cannot access host memory directly
    5. **Validation**: All plugin code validated before execution
    6. **Resource quotas**: Configurable per-plugin limits
    
    ## 4. Deployment Flow
    
    
    1. Package plugin as WASM with embedded manifest
    2. Register with plugin registry
    3. Resolve dependencies (if any)
    4. Create sandboxed instance with appropriate limits
    5. Call plugin via standardized ABI
    6. Monitor resource usage (fuel, memory)
    7. Destroy instance when done (automatic cleanup)
    
    ## 5. Extensions for Production
    
    For a production system, you'd want to add:
    
    1. **Plugin signing/verification**: Cryptographic signatures for plugins
    2. **Hot-reloading**: Safe plugin updates without downtime
    3. **Metrics collection**: Per-plugin performance monitoring
    4. **Quota management**: More sophisticated resource accounting
    5. **Multi-tenancy**: Isolate plugins from different users/tenants
    6. **Snapshot/restore**: Save plugin state for debugging
    7. **WebAssembly components**: Use WASI preview2 for better portability
    8. **Capability-based security**: Fine-grained permission system
    
    ## 6. Example Plugin (Minimal)
    
    ```rust
    // plugin/src/lib.rs (compile to wasm32-unknown-unknown)
    use serde_json::Value;
    
    #[no_mangle]
    pub extern "C" fn plugin_main(
        call_ptr: i32,
        call_len: i32,
        response_ptr: i32
    ) -> i32 {
        // In reality: read from WASM memory, process, write response
        // Return pointer to response buffer
        response_ptr
    }
    
    // Include manifest as custom section
    #[used]
    #[link_section = "plugin_manifest"]
    static MANIFEST: &str = r#"{
        "name": "math_plugin",
        "version": "1.0.0",
        "abi_version": 1,
        "entrypoint": "plugin_main",
        "capabilities": {
            "memory_limit": 65536,
            "fuel_limit": 50000
        }
    }"#;
    

    This provides a solid foundation for a secure, versioned, sandboxed WebAssembly plugin system. The design prioritizes safety while maintaining flexibility for different plugin types.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.