A multi-agent service integration system supporting security isolation and dynamic expansion
By employing streaming event bridging, a layered orchestration engine, a secure sandbox, and a dynamic skill extension mechanism, this solution addresses issues such as low integration efficiency, weak security, and contextual gaps in enterprise system integration, enabling flexible, secure, and scalable automated collaboration for multi-agent business integration.
Patent Information
- Application Number
- CN202611295062.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-25
- Publication Date
- 2026-11-20
AI Technical Summary
Existing enterprise system integration suffers from problems such as low integration efficiency, poor flexibility, weak security, context breakage, poor real-time performance, complex maintenance, and rigid capabilities. In particular, it lacks security isolation and dynamic expansion capabilities when multiple agents are running collaboratively.
We construct a streaming event bridging layer, a layered intelligent agent orchestration engine, a secure sandbox isolation environment, a multi-level memory management system, and a dynamic skill extension mechanism. Through decoupling security verification, resource control, and context management via a declarative middleware pipeline, we achieve cross-process event channels, independent execution environments, and dynamic capability loading.
It enables flexible, secure, and scalable automated business integration between heterogeneous systems, ensuring secure isolation, real-time observability, dynamic capability expansion, and long-term memory for multi-agent collaboration, thereby improving the flexibility and maintainability of system integration.
Smart Images

Figure CN123139259A_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of interdisciplinary technology of artificial intelligence and enterprise system integration, and in particular relates to a multi-agent business integration system that supports secure isolation and dynamic expansion. Background Technology
[0002] As enterprises deepen their digital transformation, they typically operate dozens of heterogeneous business systems—including customer relationship management systems, enterprise resource planning systems, approval workflow systems, instant messaging systems, and file storage systems. Traditionally, data flow and business collaboration between these systems rely on manual operations or customized point-to-point interface development, which has the following shortcomings:
[0003] (1) Low integration efficiency: For each new system integration requirement, a new interface adaptation layer needs to be developed, which results in a long development cycle and high maintenance costs;
[0004] (2) Poor flexibility: Business rules are hard-coded in the interface code. Once the business process is adjusted, it needs to be redeveloped and deployed.
[0005] (3) Weak security: When the intelligent agent executes the tool call, it directly operates the host file system or executes system commands, lacking an isolated running boundary. The transmission of sensitive data between systems lacks a unified permission control and auditing mechanism.
[0006] (4) Context break: In long dialogues or multi-step business processes, context information is likely to exceed the context window limit of the large language model. Historical information is discarded, resulting in incomplete task execution or contradictions.
[0007] (5) Poor real-time performance: The execution process of the intelligent agent is a black box to the user. The user cannot perceive the execution progress and intermediate steps of the intelligent agent. Especially in tasks involving multiple service calls and long-term operation, the user experience is poor and it is difficult to intervene manually.
[0008] (6) Complex maintenance: Cross-cutting concerns such as security verification, resource control, and file operation management are mixed with the business logic code of the agent. Modifying any concern requires traversing all related code, resulting in poor maintainability and testability.
[0009] (7) Capability solidification: Adding new business capabilities (such as connecting to new third-party system APIs) requires modifying the agent's toolset and system prompts in the core code. External capability modules cannot be loaded and unloaded on demand at runtime, and the system needs to be redeployed for each new capability.
[0010] Therefore, there is an urgent need for a multi-agent business integration method that supports secure isolation and dynamic expansion. This method enables agents to autonomously orchestrate tasks, execute operations in isolated environments, provide real-time feedback on execution status, and load external capabilities on demand, thereby achieving flexible, secure, and scalable automated business integration between heterogeneous systems. Summary of the Invention
[0011] Purpose of the Invention: This invention proposes a multi-agent business integration system that supports secure isolation and dynamic expansion, aiming to solve the problems of low integration efficiency, poor flexibility, weak security, context fragmentation, poor real-time performance, complex maintenance, and rigid capabilities in existing enterprise system integration. By constructing a streaming event bridging layer, a layered agent orchestration engine, a secure sandbox isolation environment, a multi-level memory management system, a dynamic skill expansion mechanism, and a declarative middleware pipeline based on concern separation, cross-cutting concerns such as security verification, resource control, and context management are decoupled from the core agent logic and evolved independently in a composable pipeline form, achieving intelligent and automated integration between enterprise business systems.
[0012] The system includes a streaming event bridging module, a hierarchical orchestration engine module, a secure sandbox operation module, a memory management module, a dynamic capability extension module, and a declarative middleware pipeline module.
[0013] The streaming event bridging module is deployed between the gateway layer and the agent execution layer. It builds a cross-process event stream channel based on the publish-subscribe pattern, and pushes metadata events, execution step events and streaming content events generated during the operation of the agent to the front end in real time. It supports a disconnection reconnection mechanism based on event ID breakpoint resume.
[0014] The hierarchical orchestration engine module includes a main agent unit and sub-agent units. The main agent unit receives user instructions and decomposes tasks, delegating sub-tasks to sub-agent executors. The sub-agent unit manages a thread pool, creates an independent execution context for each sub-task, and runs in an independent checkpoint space. During execution, step events are captured in real time and pushed to the front end through an event stream to display the execution progress of the sub-agent. After execution, the structured results are returned to the delegation ledger of the main agent.
[0015] The secure sandbox runtime module provides an isolated command execution environment for each agent, including a sandbox abstract interface layer and a multi-backend adaptation layer. The sandbox abstract interface layer defines unified command execution, file reading and writing, environment variable injection, and file search. The multi-backend adaptation layer supports three forms: local process sandbox, container sandbox, and cloud sandbox, and automatically selects the appropriate one based on the deployment scenario. The secure sandbox runtime module also includes an environment policy controller, which verifies whether the injected environment variable names conform to security specifications to prevent command injection.
[0016] The memory management module includes a summarization middleware and a memory middleware. The summarization middleware is triggered when the number of conversation messages exceeds a preset threshold (total number of messages = 20, message tokens = 256K). The threshold can be dynamically adjusted according to the number of tokens in a single message. The conversation history is divided into a part to be summarized and a part to be retained. A large language model is called to generate structured summary text for the part to be summarized. The summary replaces the original historical messages to control the context length, while retaining the most recent conversation rounds to ensure the integrity of the recent context. After each round of conversation, the memory middleware sends the user input and the agent's response to the memory queue. After debouncing processing, two or more conversation segments within the same time window are merged. The large language model asynchronously extracts the structured memory containing entities, events, and preferences. The memory is then persistently stored for reuse in subsequent conversations based on semantic similarity.
[0017] The dynamic capability extension module includes a skill registration center, a slash command parser, and a credential security binding unit. The skill registration center maintains public skills and user-defined skills in the form of structured file packages. Each skill unit contains a skill description file, an optional tool whitelist, and a required credential declaration. The slash command parser identifies the slash skill reference format in user messages, parses the target skill by name and category, and reads the skill description content. The credential security binding unit extracts the corresponding credential value from the request-level credential storage when a skill is activated, injects it into the sandbox process as an environment variable, and destroys the credential value with the end of the child process's lifecycle after the request ends.
[0018] The declarative middleware pipeline module decouples cross-cutting concerns into independent middleware in the form of a middleware chain based on the principle of separation of concerns. These middleware include input validation middleware, read / write gating middleware, token budgeting middleware, and persistent context middleware. Each middleware follows a unified abstract interface and registers standard hook points for execution during the agent's lifecycle. Hook points include request modification interception before model invocation, response processing after model invocation, and post-processing after the agent completes its current inference round. Each middleware operates only on the agreed hook phases and has no state coupling or sequential dependency with each other. It can be independently configured to be enabled or disabled without modifying the agent's core logic.
[0019] The streaming event bridging module includes a cross-process bridge based on RedisStream (Redis stream), which performs the following steps:
[0020] Step 1-1: Create an independent RedisStream data structure for each agent running instance, using the running instance identifier concatenated with a fixed prefix as the Stream key name;
[0021] Steps 1-2: Events generated during the execution of the agent are written to the Stream in key-value pairs, and the expiration time of the Stream is set through the Redis (remote dictionary server, open source in-memory key-value database) transaction pipeline to achieve automatic cleanup of the Stream after the running instance ends;
[0022] Steps 1-3: The gateway layer frontend subscribes to the Stream and supports passing in the last received event ID as the starting reading position. When the connection is unexpectedly disconnected and the frontend reconnects, it carries the last received event ID in the Last-Event-ID header. The bridge locates the breakpoint position based on the received last event ID and continues reading, realizing breakpoint replay of the event.
[0023] Steps 1-4: Append an end marker when each Stream write ends. After the subscriber detects the end marker during the event reading process, it completes the subscription and releases the connection resources.
[0024] The cross-process bridge uses a batch read strategy, reading a maximum of 64 events at a time to reduce network round trips; the Stream retains a maximum of 256 events, automatically pruning the oldest records beyond that to ensure controllable memory usage; the Stream's expiration time is 86400 seconds by default, set during write operations via the Redis transaction pipeline; the cross-process bridge employs an exponential backoff retry strategy when the Redis connection is interrupted, with retry latency satisfying:
[0025] ,
[0026] in, The retry delay time, For the initial retry delay, The heartbeat interval is n, and the number of retries is n, which is generally a maximum of 3. After a successful retry, the subscription cursor position is restored with the event ID that was successfully read last time, to ensure that the event is not lost in the case of momentary interruption. After the retries reach the limit, an exception is thrown to the caller to terminate the subscription, and the upper layer implements the degradation handling.
[0027] The sub-agent unit in the hierarchical orchestration engine module includes an execution state machine, which includes the following states: waiting, indicating that the subtask has been created but has not yet been allocated execution resources; running, indicating that the sub-agent is executing; completed, indicating that the subtask has ended normally; failed, indicating that the subtask execution was abnormal; canceled, indicating that the subtask was actively canceled by external means; timed out, indicating that the subtask execution exceeded the preset time limit and was terminated.
[0028] The sub-agent unit captures newly added messages as step events during the sub-agent's operation. Each step event is truncated to control the event payload size, with a truncation limit of 8192 characters. Any part exceeding the truncation limit is marked as truncated and discarded. The truncated step events are pushed to the front end through the streaming event bridging module and persisted as a running instance event record, so that the front end can still load historical step information after the page is refreshed.
[0029] The sub-agent unit constructs an independent execution context when creating the sub-agent, including an independent checkpoint storage space and an independent token consumption counter; the checkpoint space of the sub-agent is isolated from the dialogue history of the main agent to prevent the internal reasoning messages of the sub-agent from polluting the context window of the main agent; the token counter of the sub-agent independently accumulates the input and output tokens during the tool call process, and injects the token consumption into the token count of the main agent after execution, realizing full-link token tracking;
[0030] The results of the sub-agents after execution are written to the main agent in the form of a structured summary. The summary includes a task description, sub-agent type, execution status, result summary text, and reference identifiers for the result data. The delegation ledger has a maximum number of entries, and when this limit is exceeded, the oldest completed record is automatically pruned. During each subsequent model inference, the delegation ledger is injected into the main agent in the form of a hidden message through a persistent context middleware, enabling the main agent to know the completion status of all historical delegated tasks.
[0031] The secure sandbox runtime module's sandbox abstract interface layer defines a file system mapping mechanism, mounting the host machine's task working directory and tool resource directory to different paths within the sandbox. This enables bidirectional secure data exchange between the host file system and the sandbox environment. Simultaneously, it restricts the range of accessible host machine paths within the sandbox using path regular expressions. The path validation rules are as follows:
[0032] ,
[0033] in, For the set of paths that are allowed to be accessed, The file path to be verified. This is a collection of mounted host machine directories. Regular expressions are used to match paths; out-of-range path access requests are intercepted at the sandbox abstraction layer to prevent the sandbox from accessing unauthorized directories without authorization.
[0034] The local process sandbox is implemented based on operating system subprocesses, limiting the working directory to the specified sandbox root directory. Command execution is completed by starting subprocesses, and environment variable dictionaries can be passed in. The built-in command timeout controller sets the default maximum execution time of a single command to 600 seconds and supports overwriting on a per-command basis. After the timeout, a termination signal is sent to the subprocess to force it to exit. The standard output and standard error output of the subprocess are captured through bounded pipes with a capture limit of 10MB. Any part exceeding the capture limit is discarded and marked as truncation.
[0035] The container sandbox is implemented based on the AIO (Integrated Proxy Sandbox Environment) sandbox backend. It sends structured commands to the container through the HTTP interface, supports custom image, port mapping and mount directory configuration, and provides stronger process isolation and resource limitation capabilities than the local process sandbox.
[0036] Before injecting environment variables, the environment policy controller verifies whether the variable name conforms to the POSIX (Portable Operating System Interface) environment variable naming convention. Variable names that do not conform to the convention are directly rejected and an exception is thrown. This policy layer defensively protects all sandbox backends. Even if the current backend passes environment variables in dictionary form instead of shell concatenation, future shell concatenation backends will not be vulnerable to command injection due to special characters in the environment variable name.
[0037] The summary middleware of the memory management module performs the following steps:
[0038] Step 2-1: Count the total number of messages in the current session. Total number of tokens The summary process is triggered when any metric exceeds the configured threshold. The triggering condition is as follows:
[0039] ,
[0040] in, As a triggering condition, and The trigger threshold is configurable;
[0041] Step 2-2: Divide the dialogue history into messages to be summarized. and reserved messages The message consists of two parts: retaining the content of the most recent K rounds of dialogue to ensure that the recent context is complete and not lost; and retaining system messages and hidden context messages marked as non-streamable to avoid being affected by the digest.
[0042] Steps 2-3: Invoke the dedicated large language model Treating summary messages Generate structured summary text S:
[0043] ,
[0044] in, It is a dedicated large language model (independent of the main task model). This is an earlier dialogue message awaiting a summary; the summary includes the key topics of the dialogue, completed steps, pending matters, and important decision-making criteria.
[0045] Steps 2-4: Before the summary is generated, trigger the pre-hook to notify other middleware that the message is about to be removed, allowing the message content to be backed up to external storage before the removal operation is performed;
[0046] Steps 2-5: Remove the original historical messages from the state and replace them with summary text, while saving the retained messages; in subsequent dialogues, the summary text is injected into the agent's input as a hidden persistent context data message through the persistent context middleware, and the character limit is set (default 8192 characters) to truncate excessively long summaries.
[0047] The memory middleware performs the following steps:
[0048] Step 3-1: After each round of agent responses, extract user messages from the dialogue state. And the final assistant's reply To ensure the semantic purity of memory retrieval, intermediate messages during the tool invocation process are excluded.
[0049] Step 3-2: Send the message pairs into the memory queue. The memory queue adopts a debouncing strategy and is configured with a fixed debouncing time window. (Default 60 seconds) Multiple consecutive dialogue segments within the same window are merged into a single batch processing:
[0050] ,
[0051] in, This is a collection of batch dialogue segments merged within the debounce window. For the first User messages in a round-robin conversation For the first The assistant in the conversation eventually replied to the message. For the first The user messages in the round-robin dialogue and the assistant's final reply message pair. For the first The timestamp of the round-robin conversation To debounce the window at its start time; to reduce the number of large language model calls and token consumption;
[0052] Step 3-3: After the debounce window expires, the large language model is invoked to extract dialogue fragments from the queue and generate structured memory records. :
[0053] ,
[0054] in, Memory categories (entities / events / preferences / decisions / knowledge / behaviors). For memorizing content, The confidence level is between 0 and 1, and m is the number of memory entries extracted in this batch. After extraction, deduplication logic is executed: the content field of the newly extracted facts is normalized by removing whitespace characters, and then compared with the existing facts in storage one by one. The actual set of new facts added after deduplication is calculated. for:
[0055] ,
[0056] in, This represents an additional set of new facts. Represents a set of existing facts. For memory record collection, for Memory elements in for Memory elements in A function to normalize whitespace characters. For new memory elements The original memory content text, Memorizing elements in an existing set of facts The original memory content text is persistently stored in an external storage system using atomic file updates (temporary files + atomic renaming);
[0057] Steps 3-4: At the start of subsequent conversations, relevant historical memory records are retrieved based on the current conversation topic using semantic similarity. The similarity calculation uses cosine similarity.
[0058] ,
[0059] in, for and Vector similarity, This is the embedding vector of the current query text. For the embedding vectors of the stored memory entries, select the top ones with the highest similarity. Memory is injected into the reasoning process of the agent as context, enabling knowledge continuation and personalized responses across sessions.
[0060] The public skills and user-defined skills are organized in a separate file directory, including skill description files in Markdown (a lightweight markup language). The file header declares skill metadata in YAML format, including: skill name, skill description, license information, list of required credentials, list of allowed tools, and whether automatic activation is allowed. Each skill unit is an independent capability carrier that can be copied, shared, and version managed.
[0061] The public skills mentioned are general capabilities built into the platform, and are read-only and cannot be edited;
[0062] The user-defined skills are personalized abilities created and managed by the user, and can be edited and deleted;
[0063] The slash instruction parser supports the following two complementary activation modes:
[0064] Explicit activation mode: Users explicitly reference skills in the input message in the format " / category / skill name" or " / skill name". The parser extracts the slash instruction part, separates the skill name and category identifier, accurately searches for matching skill files in the skill registry by name and category, reads the skill description content and calculates the content hash for subsequent change detection.
[0065] Automatic activation mode: During the inference process, the system automatically loads and injects the matching skill description text into the agent's system prompt based on the list of enabled skills in the current session configuration. The agent can autonomously determine whether to use a certain skill based on the current task requirements without the user having to explicitly specify it.
[0066] The input validation middleware in the declarative middleware pipeline module performs the following steps:
[0067] Step 4-1: Obtain the content of the most recent real user message before calling the large language model;
[0068] Step 4-2: Maintain an XML-formatted tag name that has special semantics in system prompts and internal framework messages (including a system-reserved tag blacklist). This includes memory, analysis, instruction, system prompts, roles, functions, context, and summaries; HTML entity escaping is performed on blacklist tags appearing in user messages.
[0069] ,
[0070] in, The original user message text, To verify the conversion function, For string replacement operations, "<" is escaped to "<" and ">" is escaped to ">", so that it is presented as plain text rather than structured instructions in the model. This defends against hint injection attacks from the source and serves as the first semantic protection barrier against structured hint injection.
[0071] Step 4-3: Add plain text boundary markers at the beginning and end of the user message to form an encapsulated structure of boundary markers, original user content, and boundary markers, serving as the second semantic protection barrier for structured prompt injection.
[0072] The read-write gated middleware in the declarative middleware pipeline module performs the following steps:
[0073] Step 5-1: Intercept the agent's call requests to file modification tools (including write_file and str_replace tools) and extract the target file path;
[0074] Step 5-2: Retrieve the most recent read record of the target file path in the dialogue message history. The read record is marked with the SHA-256 hash of the entire file content:
[0075] ,
[0076] in, A SHA-256 hash tag representing the content of a file. To read the entire contents of the time file; The data is stored in the metadata of the message returned by the read_file tool; if the message history is compressed due to the digest, resulting in the loss of read records, the read mark is also lost, and the gating determines that it has not been read.
[0077] Step 5-3, if a valid read tag is found Then, the current content of the target file is read through the sandbox and the SHA-256 hash value is calculated. ,and Comparison:
[0078] ,
[0079] in, represent and The comparison results This is the SHA-256 hash value of the current file content read through the sandbox before the write operation. The hash value of the read tag in the most recently read record; when When write operations are allowed, it means the file content has not been modified since the last read; when The write operation is rejected and an error message is returned, requiring the agent to reread the file before making any modifications;
[0080] Step 5-4: Immediately after the write operation is completed, invalidate the read marker of the file path, forcing any subsequent modification operation on the same file to be read again.
[0081] Step 5-5: The read mark check and write operation of the same file path are serialized using thread locks to prevent multiple concurrent tool calls from simultaneously writing based on the same expired read mark through gating in the same round.
[0082] The read / write gating middleware adopts a fault-based open strategy for cases where file content cannot be checked: when the sandbox backend returns an Error: prefix string (indicating read failure or lack of permission) or the target file is binary content, the read / write gating middleware allows the write operation and generates error information by itself, avoiding blocking the normal operation process due to the technical limitations of the gating itself;
[0083] The token budgeting middleware in the declarative middleware pipeline module accumulates the consumption of input and output tokens in a multi-round tool call loop, specifically by performing the following steps:
[0084] Step 6-1: After each model call, extract token usage metadata (usage_metadata) from the model response to count the input tokens. Output token Total number of tokens This is added to the cumulative consumption of this running instance;
[0085] Step 6-2: Calculate the consumption percentage of the three dimensions—input tokens, output tokens, and total tokens—and take the maximum value as the current budget pressure indicator. :
[0086] ,
[0087] in, This represents the current token budget pressure. , , These are the budget limits for input tokens, output tokens, and total tokens, respectively.
[0088] Step 6-3, when Before the next round of model calls, inject a budget warning message into the agent, informing it of the current usage and remaining quota for each dimension, and suggesting that it finish the current work as soon as possible; This indicates the alarm threshold, with a default value of 0.70.
[0089] Step 6-4, when At that time, the tool call request in the agent message is directly removed, and the large language model is forced to generate a final response without tool calls to prevent the uncontrolled tool call loop from consuming resources indefinitely. At the same time, the reason for stopping is recorded for the upper-layer caller to read and determine whether the termination is triggered by budget. This indicates the stop threshold, with a default value of 0.95.
[0090] Before the large model is invoked, the persistent context middleware in the declarative middleware pipeline module merges and renders the two types of persistent context data, namely summary text and delegation ledger, into a hidden user message, HumanMessage, which is injected into the request message list. This HumanMessage carries a specific hidden tag key, which is automatically identified and skipped during message history processing and streaming. The content of this HumanMessage contains an authoritative declaration tag, which explicitly tells the large language model that the content is historical observation data provided at runtime rather than scheduling instructions, preventing the text in the persistent context from being misinterpreted as commands by the model.
[0091] The persistent context middleware also maintains a single-execution flag for the persistent context injection: to run the instance identifier. Injecting state for key tracking:
[0092] ,
[0093] in, This is an injection determination function (injection is performed when it returns true). A status query function has been injected for the current round. To negate the logic; ensure that in each user round, persistent context messages are only injected into the first model call and not repeatedly injected into subsequent model calls in the tool call loop;
[0094] The delegated ledger limits the number of characters in the result summary of each subtask during rendering. If the limit is exceeded, it is truncated and an ellipsis is added. At the same time, the maximum number of entries in the delegated ledger is maintained. If the limit is exceeded, the earliest completed entry is pruned to maintain the compactness of the injection context.
[0095] This invention is applicable to scenarios such as enterprise office automation, approval workflow automation, cross-departmental data exchange and synchronization, intelligent customer service and work order processing where there are multiple system collaboration needs, and has significant technological progress and practical value.
[0096] The present invention has the following beneficial effects:
[0097] (1) Secure and isolated multi-agent collaboration: A secure sandbox runtime module provides each agent with an independent process-level isolated execution environment. An environment policy controller defensively verifies injected variables to prevent command injection. Combined with a hierarchical orchestration engine, a two-level collaborative architecture between the master agent and sub-agents is implemented. Sub-agents execute in parallel without interfering with each other in an independent checkpoint space. The execution results are aggregated to the master agent through a delegation ledger mechanism. This solves the core problem of agents directly manipulating the host environment and lacking security boundaries in traditional enterprise system integration.
[0098] (2) Real-time observable event-driven architecture: A cross-process real-time event channel is built based on RedisStream through the streaming event bridging module, which supports the publication and subscription of three types of events: metadata events, step events and streaming content events. The breakpoint replay mechanism and exponential backoff retry strategy of XREAD ensure that events are not lost in the instantaneous interruption scenario, so that users can perceive the execution progress and intermediate steps of the agent in real time. This solves the problems of black box execution process, inability of users to perceive progress and difficulty of manual intervention in traditional integration solutions.
[0099] (3) Dynamic Capability Expansion and Zero Residual Credentials: The dynamic capability expansion module uses skill file packages as the smallest capability unit to achieve runtime hot loading of business capabilities. It supports two modes: explicit activation by user slash commands and on-demand autonomous loading by intelligent agents. Adding or changing business capabilities does not require modifying the core code or redeploying the system. Credentials are injected into the sandbox environment with a request-level security context and are naturally cleared after the request ends and the child process is destroyed, ensuring zero residual of sensitive credential information. This solves the problems of business capability solidification and weak credential security management in traditional solutions.
[0100] (4) Long-term memory and cross-conversation knowledge continuation: A two-level system of summary compression and persistent memory is constructed through the memory management module. When the message volume exceeds the limit, the summary compression generates a structured summary with an independent model to replace the original message and retain the most recent dialogue round, solving the problem of long dialogue context window overflow. The persistent memory is extracted asynchronously through the debouncing queue, which contains structured memory containing entity, event, preference and decision dimensions. Combined with the obsolescence review and memory merging mechanism, the memory bank is kept concise and timely. Cross-conversation knowledge continuation and personalized response are realized through cosine similarity retrieval.
[0101] (5) Pluggable Middleware Pipeline with Separated Concerns: Based on the principle of separation of concerns, the declarative middleware pipeline module decouples cross-cutting concerns such as input validation, read / write gating, token budget control, and persistent context injection from the core logic of the agent into independent middleware. Each middleware follows a unified abstract interface and executes at six standard hook points in the agent's lifecycle. There is no state coupling or sequential dependency between middleware, and they can be configured to be enabled or disabled independently. When adding a cross-cutting concern, only a new middleware class needs to be written and inserted into the pipeline. Existing code is not affected, which solves the problems of mixed security validation, resource control, and business logic code and poor maintainability in traditional solutions.
[0102] (6) A security system with depth of defense: By using the tag blacklist escaping and boundary mark encapsulation of the input verification middleware, the SHA-256 hash version verification and thread lock serialization of the read and write gating middleware, the POSIX variable name verification of the environment policy controller, and the intersection semantic injection of the credential security binding unit, a multi-layer security defense system is constructed from user input to model invocation, from tool execution to credential management, which effectively defends against a variety of security threats such as prompt injection attacks, file conflict writing, command injection and credential leakage. Attached Figure Description
[0103] The present invention will be further described in detail below with reference to the accompanying drawings and specific embodiments, and the advantages of the present invention in the above and / or other aspects will become clearer.
[0104] Figure 1 This is a structural diagram of the system of the present invention.
[0105] Figure 2 This is a flowchart of the system of the present invention. Detailed Implementation
[0106] This invention provides a multi-agent business integration system that supports secure isolation and dynamic expansion, including a streaming event bridging module, a hierarchical orchestration engine module, a secure sandbox operation module, a memory management module, a dynamic capability expansion module, and a declarative middleware pipeline module.
[0107] The streaming event bridging module is based on RedisStream to build a cross-process event channel, supporting the publication and subscription of three types of events: metadata events, step events, and streaming content events. It realizes the reconnection of the subscriber and event replay through the XREAD start ID positioning mechanism and the Last-Event-ID protocol header.
[0108] The hierarchical orchestration engine module adopts a two-level architecture of main agent and sub-agent. The main agent, as the only entry point for user interaction, is responsible for task decomposition and decision-making. The sub-agents execute in parallel in an independent checkpoint space. The steps and events during the execution process are pushed to the front end in real time to show the progress. The execution results are written into the delegation ledger in a structured summary for the main agent to refer to in subsequent reasoning.
[0109] The security sandbox operation module provides a unified sandbox abstraction interface, supports three backend forms: local process sandbox, container sandbox, and cloud sandbox, limits file access scope through path regular expressions, and prevents command injection by verifying injected variable names through environment policy controller.
[0110] The memory management module includes a two-level system of summary compression and persistent memory. When the session length exceeds the limit, the summary compression generates a structured summary using an independent summary model to replace the original message and retains the most recent dialogue rounds. After the dialogue ends, the persistent memory asynchronously extracts the structured memory containing entities, events and preferences through a debouncing queue for subsequent sessions to retrieve based on semantic similarity.
[0111] The dynamic capability extension module uses skill file packages as the smallest capability unit to achieve runtime hot loading of business capabilities. The skill files describe the purpose and constraints in Markdown format and declare the required credentials and tool whitelist in YAML header. It supports two modes: explicit activation by user slash commands and on-demand self-loading by the agent. When activated, the credentials are injected with request-level security context and automatically destroyed after the request ends, achieving zero residue of sensitive information.
[0112] The declarative middleware pipeline module linearly orchestrates cross-cutting concerns such as input validation, read / write gating, token budget control, and persistent context injection as pluggable middleware. Each middleware follows a unified interface and executes at standard hook points before and after model calls. There are no state dependencies between middleware, and they can be enabled or disabled independently.
[0113] In the streaming event bridging module, the cross-process bridge creates an independent RedisStream data structure for each agent instance, using the instance identifier prefixed with a fixed name as the Stream key. Events are written to the Stream in key-value pairs using the XADD command. Each event's fields include kind (event type, value either event or end), event (event name), and data (JSON serialized event data). The Stream's TTL expiration time (default 86400 seconds) is also set via Redis transaction pipelines, and events are automatically cleaned up after expiration. The Stream is limited to a maximum of 256 events by the maxlen parameter; any exceeding this limit is automatically pruned to ensure manageable memory usage. Frontend subscription is implemented using the XREAD command, supporting blocking reads with the block parameter. The blocking duration is controlled by the heartbeat interval parameter (default 15 seconds). When a connection is unexpectedly lost, the frontend reconnects by sending the last received event ID in the Last-Event-ID request header of the HTTP protocol. The bridge uses this to pinpoint the breakpoint and continue reading subsequent events. When a Redis connection is momentarily interrupted, the subscriber employs an exponential backoff retry strategy, with retry latency satisfying the following:
[0114] ,
[0115] in, For the initial retry delay, The interval between heartbeats. This represents the number of retries, up to a maximum of 3. Upon successful retry, the subscription cursor is restored using the event ID successfully read last time, ensuring no events are lost. If the retries reach the limit, an exception is thrown to the upper layer to terminate the subscription.
[0116] In the hierarchical orchestration engine module, the sub-agent executor maintains an execution state machine with six states: waiting, running, completed, failed, canceled, and timed out. The sub-agent executor allocates thread resources in the global thread pool, with a configurable maximum concurrency (default 3). Delegation requests exceeding the concurrency limit enter a waiting queue and are processed in a first-in-first-out order. During sub-agent construction, an independent checkpoint storage space, an independent token consumption counter, and an independent sandbox environment are created. The sub-agent's checkpoint space is completely isolated from the main agent's dialogue history, preventing internal inference messages from the sub-agent from polluting the main agent's context window. During execution, the step event capture mechanism extracts step descriptions and key data from newly added messages, truncating each step event to a maximum of 8192 characters; any excess is marked as truncated and discarded. The result after execution is written to the main agent's delegation ledger in a structured summary format. The summary includes a task description, sub-agent type, execution state, result summary text, and reference identifiers for the result data. The delegation ledger has a maximum number of entries (50 by default), and automatically prunes the earliest terminated record when this limit is exceeded. Token consumption by sub-agents is injected into the main agent's token budget middleware after execution, enabling end-to-end token tracking.
[0117] In the security sandbox runtime module, the sandbox abstract interface layer defines unified operation primitives, including `execute_command` (receives a command string), `read_file` (receives a relative path, offset, and line count limit), `write_file` (receives a relative path and content string), and `search_files` (receives a search mode and search directory). The multi-backend adaptation layer supports three forms: local process sandbox, container sandbox, and cloud sandbox. The local process sandbox is implemented based on operating system child processes, starting as a child process and limiting the child process's working directory to the sandbox root directory. The default maximum execution time for command timeout control is 600 seconds. The child process's standard output and standard error are captured through bounded pipes, with a capture limit of 10MB. The file system mapping mechanism supports mapping host machine directories to paths within the sandbox and restricts the accessible host machine path range using path regular expressions. The path validation rules are as follows:
[0118] ,
[0119] in, For the set of paths that are allowed to be accessed, The file path to be verified. This is a collection of mounted host machine directories. Regular expressions are used to match paths; out-of-range path access requests are intercepted at the sandbox abstraction layer to prevent the sandbox from accessing unauthorized directories without authorization.
[0120] The environment policy controller performs defensive security checks when injecting environment variables, verifying whether the variable names conform to the POSIX (Portable Operating System Interface) naming convention; variable names that do not conform to the convention are directly rejected and an exception is thrown.
[0121] In the memory management module, the summary middleware is triggered when the number of session messages exceeds a preset threshold; the trigger condition is the total number of messages. Or total number of tokens Any value exceeding the configured threshold:
[0122] ,
[0123] in, and This is a configurable trigger threshold. Once triggered, the dialogue history is divided into messages awaiting summary. and reserved messages Two parts, retaining the most recent message. Proceed with the dialogue. Invoke the dedicated large language model. Generate structured summary text for summary messages :
[0124] ,
[0125] in, Independent of the main task model, it can be configured for different providers or a lighter-weight model. Before summary generation, a pre-hook is triggered to notify other middleware that the message is about to be removed. The `RemoveMessage` directive removes the original historical message from the state and replaces it with the summary text. In subsequent conversations, the summary text is injected as a hidden message, with a character limit set during injection (default 8192 characters); any excess characters are truncated.
[0126] In the memory management module, the memory middleware asynchronously retrieves persistent memory after each round of dialogue. User messages are extracted from the dialogue state. And the final assistant's reply , forming message pairs Messages are fed into a memory queue, and a debouncing strategy is used to merge multiple conversation fragments within the same time window.
[0127] ,
[0128] in, This is the debounce time window (default 60 seconds). After the window expires, the large language model is called to extract dialogue fragments from the queue and generate a structured memory record.
[0129] ,
[0130] in, Memory categories (entities / events / preferences / decisions / knowledge / behaviors). For memorizing content, The confidence level is between 0 and 1. This represents the number of memory entries extracted in this batch. Memory entries are persistently stored in an external storage system, indexed by the user identifier and an optional agent name. At the start of subsequent sessions, relevant historical memories are retrieved based on semantic similarity according to the current dialogue topic. Cosine similarity is used for similarity calculation.
[0131] ,
[0132] in, This is the embedding vector of the current query text. For the embedding vectors of the stored memory entries, select the top ones with the highest similarity. The memory is injected as context into the reasoning process of the agent.
[0133] The memory management module also includes a memory obsolescence review and memory merging mechanism. Each memory fact is assigned an expected number of valid days upon creation. This value is automatically assigned by the large language model during extraction based on the timeliness of the facts, and is subject to an upper limit constraint during writing:
[0134] ,
[0135] in, The number of effective days recommended for the large language model. The base number of days for the degree of obsolescence (default 90 days). This is the maximum lifetime multiplier (default 20x). An obsoleteness review is triggered when the following conditions are met:
[0136] ,
[0137] in, For the current set of facts, For the facts The number of days of existence, This is the minimum number of candidate options (default 3). During review, the large language model determines each candidate fact as KEEP, REMOVE, or EXTEND, with a maximum deletion count per cycle. (Default 10). The memory merging mechanism is activated when the number of similar memory entries exceeds [a certain threshold]. (Default 8) Triggered, the large language model semantically summarizes and merges multiple facts under the same category to generate synthetic facts. The maximum number of merged groups per cycle is [number missing]. (Default 3), the maximum number of source facts per group is (Default 8).
[0138] The memory management module's update strategy employs a complete chain of "enqueueing-debouncing-extraction-deduplication-atomic writing-cache invalidation." The memory middleware is triggered after each round of agent responses, extracting only user messages and the final assistant response message from the dialogue state (excluding tool call intermediate messages), identified by the user. and optional agent names Used as an index key to form a message pair The data is then sent to a memory queue. The queue employs a debouncing strategy, implemented using a thread-safe Timer, with each user configured with a fixed debouncing window. (Default 60 seconds) Multiple consecutive dialogue segments within the same window are merged into a single batch processing. After the debouncing window expires, the dialogue segments in the queue are sent in batches to the large language model for memory retrieval, generating a structured set of memory facts. After extraction, execute the deduplication logic: for The `content` field of each fact is normalized for whitespace characters (leading and trailing whitespace characters are removed), and then compared one by one with the normalized `content` field of existing facts in storage. If they are completely identical, the fact is considered a duplicate and is skipped from the write process. Let the set of existing facts be... The set of new facts actually added after deduplication is:
[0139] ,
[0140] in, This function normalizes whitespace characters (removing leading and trailing whitespace). Persistent writing to memory employs an atomic file update strategy: first, the current memory data is compared with... The data is merged and written to a temporary file. After writing, the original file is replaced by an atomic rename operation of the operating system, ensuring that the writing process is unaffected by process crashes or concurrent access, and maintaining data consistency at all times. Immediately after writing, the memory cache corresponding to the current user and agent is invalidated, so that the next read forces the loading of the latest data from the file system.
[0141] Memory injection occurs at the start of a subsequent session or the initiation of a new dialogue turn. The system generates a query embedding vector based on the current dialogue topic. All stored memory entries are sorted by cosine similarity. Token budget control is performed before injection: retrieved memory facts are sorted in descending order of similarity, and the token count is incremented for each entry until the configured maximum number of injection tokens is reached. (Default 2000), any value exceeding this will be truncated and not injected. Memory facts, after budget control, are injected into the agent context in the form of system prompts. The injection operation is controlled by the persistent context middleware, and is injected only once per round of dialogue, determined by the running instance identifier. The injection status is tracked. The memory middleware supports two operating modes: Middleware mode—memory retrieval and injection are both executed asynchronously in the background as middleware, transparent to the user; Tool mode—memory query, add, update, and delete operations are exposed as tools (memory_search, memory_add, memory_update, memory_delete) that can be invoked by the agent, allowing the model to autonomously decide when to read and write memories. Both modes share the same storage backend and deduplication, obsolescence review, and merging logic to ensure consistency in update strategies.
[0142] The memory management module supports the following configurable parameters:
[0143] a. Anti-shake window time (default 60 seconds);
[0144] b. Maximum number of facts (default 100);
[0145] c. Fact confidence threshold (default 0.7);
[0146] d. Maximum number of injection tokens (default 2000);
[0147] e. Baseline number of days for age review (default 90 days);
[0148] f. Minimum number of candidates for obsolescence (default 3);
[0149] In the dynamic capability extension module, skills are organized in independent file directories, with the core being the SKILL.md skill description file. The file header declares metadata in YAML format, including the skill name, skill description, license information, list of required credentials, whitelist of allowed tools, and whether automatic activation is allowed. Skill sources are divided into two categories:
[0150] a. Public Skills (PUBLIC) – Universal capability units built into the platform, read-only and not editable;
[0151] b. Custom Skills (CUSTOM) – Personalized skill units created and managed by users, which can be edited and deleted; the skill registry automatically scans the skill catalog when the system starts up to identify newly added, modified and deleted skill files, without the need for manual registration.
[0152] In the dynamic capability extension module, the slash instruction parser supports two complementary activation modes. Explicit activation mode: The user explicitly references the skill in the input message using the format " / category / skill name" or " / skill name". The parser extracts the slash instruction portion and precisely searches for it in the skill registry by name and category. It then reads the SKILL.md content and calculates the content hash for subsequent change detection. The activated content hash is calculated as follows:
[0153] ,
[0154] in, The hash value of the skill file content. This is the complete text content of the skill description file; each time a model is invoked, the current file hash is compared with the activated hash, and if they do not match, the file is reloaded. To prevent the same slash instruction from being activated repeatedly in the tool invocation loop, the parser records the activated slash message identifier in the runtime instance context. Check during subsequent model calls Has it been processed to avoid duplicate injection? In automatic activation mode, the system automatically loads and injects the matching skill description text into the agent's system prompt based on the list of enabled skills in the session configuration.
[0155] In the dynamic capability extension module, the credential security binding unit retrieves the actual credential value corresponding to the credential name required for the skill declaration from the request-level credential storage when the skill is activated. The injection of credential values follows intersection semantics:
[0156] ,
[0157] in, For the set of credential names of the skill declaration, A set of credential names provided to the requester is injected only if the credential name appears in both contexts. The credential value is injected into the child process in the sandbox environment as an environment variable, valid only within the context of this request. The sandbox process terminates after the request ends, and the environment variable is naturally destroyed with the process's lifecycle, ensuring zero residue of sensitive credential information.
[0158] In the declarative middleware pipeline module, each middleware follows a unified AgentMiddleware abstract interface and registers the following standard hook points during the agent's lifecycle:
[0159] The before_agent hook is executed before the agent starts running and is used for one-time pre-processing before the start of the entire round (such as dynamic context injection and file upload organization).
[0160] The before_model hook is executed before each model call and is used to process the message list before the request is sent to the model (such as summary trigger checks and image injection).
[0161] The wrap_model_call hook wraps the entire model call process, allowing you to modify the request message, inject additional messages, or directly intercept it (returning a preset response without calling the model).
[0162] The wrap_tool_call hook wraps the entire tool call process, allowing you to intercept, verify, or modify tool call requests (such as version verification for read / write gating and tool error capture).
[0163] The after_model hook is executed after each model call and can be used to process, modify, or record the model response (such as token consumption accumulation and loop detection).
[0164] The `after_agent` hook executes after the agent completes its current round of inference (including all tool call loops) and is used to trigger asynchronous post-processing tasks. The execution order of middleware is determined by its position in the pipeline chain; the wrapper output of the previous middleware automatically becomes the input of the next middleware, forming a linear processing chain.
[0165] The input validation middleware maintains a system-reserved tag blacklist. It contains over twenty XML-formatted tag names, including memory, analysis, instruction, system, role, function, context, and summary. It performs HTML entity escaping on blacklist tags appearing in user messages.
[0166] ,
[0167] in, The original user message text, To verify the conversion function, This is for string replacement operations; at the same time, plain text boundary markers are added to the beginning and end of the user message to form an encapsulated structure of "boundary marker + user content + boundary marker", which constitutes a two-layer semantic barrier for preventing injection.
[0168] The read / write gating middleware enforces a "read-verify-write" version verification process before each file write operation. Read records are marked using the SHA-256 hash of the entire file content.
[0169] ,
[0170] in, The SHA-256 hash read tag for the file content. To read the entire contents of the time file; The data is stored in the metadata of the message returned by the read_file tool. Before a write operation, the current content of the target file is read through a sandbox and the hash value is calculated. ,and Comparison:
[0171] ,
[0172] in, This is the SHA-256 hash value of the current file content read through the sandbox before the write operation. The hash value of the read tag in the most recently read record; when When write operations are allowed, it means the file content has not been modified since the last read; when Write operations are rejected and an error message is returned, requiring the agent to reread the file before making modifications. Read mark checks and write operations on the same file path are serialized using thread locks. For cases where file content cannot be checked (the sandbox returns an "Error:" prefix or binary content), a "fault-free" strategy is used to allow write operations.
[0173] The token budgeting middleware accumulates token consumption across multiple tool call loops. After each model call, the usage_metadata is extracted to statistically analyze the input tokens. and output token Calculate the consumption percentage across the three dimensions and take the maximum value as the stress indicator:
[0174] ,
[0175] in, , , These represent the budget caps for each dimension. When (Default 0.70) Inject warning messages; when (Default 0.95) Remove the tool_calls field to force the generation of the final response.
[0176] The persistent context middleware merges and renders two types of persistent context data—summary text and delegation ledger—into a hidden message injection request message list before each model invocation. Messages carry specific hidden tag keys that are automatically identified and skipped during message history processing and streaming. An execution flag is maintained for "inject only once per round" to run instance identifiers. Injecting state for key tracking:
[0177] ,
[0178] in, For the instance identifier, This is an injection determination function (injection is performed when it returns true). A status query function has been injected for the current round. To negate the logic; ensure that in each user round, persistent context messages are only injected into the first model call and not repeatedly injected into subsequent model calls in the tool call loop;
[0179] The delegated ledger limits the number of characters in the result summary of each subtask during rendering. If the limit is exceeded, it is truncated and an ellipsis is added. At the same time, the maximum number of entries in the delegated ledger is maintained. If the limit is exceeded, the earliest completed entry is pruned to maintain the compactness of the injection context.
[0180] In another embodiment of the present invention, a multi-agent service integration system supporting secure isolation and dynamic expansion is provided. For example... Figure 1 As shown, the overall system architecture includes a streaming event bridging module, a layered orchestration engine module, a secure sandbox operation module, a memory management module, a dynamic capability extension module, and a declarative middleware pipeline module.
[0181] The streaming event bridging module is deployed between the gateway layer and the agent execution layer. It builds a cross-process event channel based on RedisStream, supports the publication and subscription of three types of events: metadata events, step events, and streaming content events. It realizes real-time writing and subscription of events through XADD / XREAD commands, and realizes reconnection and event playback of subscribers through the Last-Event-ID protocol header.
[0182] The hierarchical orchestration engine module adopts a two-level architecture of main agent and sub-agent. The main agent, as the only entry point for user interaction, is responsible for task decomposition and decision scheduling. The sub-agents execute in parallel in an independent checkpoint space. The steps and events during the execution process are pushed to the front end in real time to show the progress. The execution results are written into the delegation ledger in a structured summary for the main agent to refer to in subsequent reasoning.
[0183] The secure sandbox operation module provides each agent with an isolated command execution and file system interaction environment. It defines unified command execution, file reading and writing, and file search operation primitives through the abstract interface layer. The multi-backend adaptation layer supports two forms: local process sandbox and container sandbox (AIO). It also verifies whether the injected variable name conforms to the POSIX (Portable Operating System Interface) naming standard through the environment policy controller to prevent command injection.
[0184] The memory management module includes a two-level system of summary compression and persistent memory. When the number of conversation messages exceeds the limit, the summary compression generates a structured summary using an independent summary model to replace the original message and retains the most recent conversation round. After the conversation ends, the persistent memory asynchronously extracts the structured memory containing entities, events and preferences through a debouncing queue, and persists it using an atomic file update strategy. Subsequent conversations can retrieve and reuse it based on cosine similarity.
[0185] The dynamic capability extension module uses skill file packages as the smallest capability unit to achieve runtime hot loading of business capabilities. The skill files describe the purpose and constraints in Markdown (a lightweight markup language) format, and declare the required credentials and tool whitelist in YAML header. It supports two modes: explicit activation by user slash commands and on-demand self-loading by the agent. When activated, the credentials are injected with request-level security context and automatically destroyed after the request ends, achieving zero residue of sensitive information.
[0186] The declarative middleware pipeline module linearly orchestrates cross-cutting concerns such as input validation, read / write gating, token budget control, and persistent context injection in the form of pluggable middleware based on the separation of concerns principle. Each middleware follows a unified AgentMiddleware abstract interface and is executed at standard hook points before and after model calls. There are no state dependencies between middlewares, and they can be enabled or disabled independently.
[0187] The following example illustrates the enterprise business integration scenario of "new employee onboarding approval." This scenario involves the collaborative operation of three heterogeneous business systems: the HR personnel system, the IT asset management system, and the access control and security system. The system is deployed in the enterprise's internal network environment. The intelligent agent runs in a local process sandbox mode, and the streaming event bridge uses RedisStream (maxlen=256, TTL=86400s). The maximum concurrency of the thread pool is configured to 3, the token budget warning threshold is 70%, the stop threshold is 95%, and the memory management debouncing window is configured to 30 seconds.
[0188] like Figure 2 This is a flowchart of the system of the present invention, which specifically includes the following steps:
[0189] Step 1-1, System Initialization and Skill Configuration. Upon system startup, the skill registry automatically scans the skills / public / and skills / custom / directories, identifies the SKILL.md file of all skill packages, parses the YAML header metadata, and establishes an index of skill name, category, source, and file path. For the onboarding scenario in this embodiment, the administrator pre-creates a skill package in the skills / custom / hr / onboarding / directory. Its SKILL.md file header declares the following: name: onboarding, description: Handling new employee onboarding procedures, including HR file creation, IT equipment allocation, domain account activation, and access control activation, license: MIT, required-secrets: [HR_API_KEY, IT_ADMIN_TOKEN, ACCESS_CONTROL_KEY], allowed-tools: [bash, read_file, write_file, task]. This skill is set to enabled: true in extensions_config.json. When the registry starts scanning, it identifies the newly added skill, establishes an index entry, and calculates a content hash for subsequent change detection.
[0190] Steps 1-2: User request access and slash command parsing. The user sends a message in a group chat via an enterprise instant messaging application (such as Lark or WeChat Work): " / hr / onboarding is processing the onboarding procedures for new employee Zhang San. His position is Development Engineer, department is Technology Department. Office equipment is being allocated and a system account is being activated." The message is converted into a unified message format within the system via the instant messaging channel adapter and then routed through the gateway layer to the agent execution layer.
[0191] Steps 1-3: Slash Command Parsing and Credential Security Binding. After receiving the message, the gateway layer's slash command parser identifies the " / hr / onboarding" skill reference in the message text, extracts the skill category "hr" and the skill name "onboarding," and precisely searches for it in the skill registry by category and name, finding the skill file located at skills / custom / hr / onboarding / . The parser reads the entire contents of SKILL.md, calculates the content hash, and compares it with the hash stored during registration to confirm that the skill file has not been tampered with. Skill declarations require three credentials: HR_API_KEY, IT_ADMIN_TOKEN, and ACCESS_CONTROL_KEY. The credential security binding unit extracts the corresponding credential values from the request-level credential storage and mounts them to the sandbox environment as environment variables. Simultaneously, the skill file directory is mounted to the / mnt / skills / hr / onboarding / path inside the sandbox.
[0192] Steps 1-4: Run instance creation and event stream channel establishment. The gateway layer creates a run instance at the execution layer, assigning a unique run_id (e.g., run_20240722_a1b2c3d4). A RedisStream event stream channel is established for this run instance via the streaming event bridging module, with the Stream key name "qcdoc_agent:stream_bridge:run_20240722_a1b2c3d4". Simultaneously, a frontend SSE (Server-SentEvents) long connection is established for this run instance, subscribing to the corresponding Stream in blocking mode (block=15000ms) using the XREAD command, ready to receive real-time event pushes.
[0193] Steps 1-5: Middleware pipeline pre-processing. Before the model is called, the declarative middleware pipeline executes the wrap_model_call hook in sequence:
[0194] Step 1-5-1: The input validation middleware performs a security scan on the user message, maintaining a system-reserved tag blacklist (containing over twenty XML tag names such as memory, analysis, instruction, system, and role), and checks whether the message contains any tags from the blacklist. In this example, the user message does not contain any system-reserved tags, so the security scan passes. The middleware adds plain text boundary markers to the beginning and end of the user message to form an encapsulation structure.
[0195] Step 1-5-2: The persistent context middleware checks for the existence of historical conversation summaries and delegation ledger records. In this example, it is the first session, and there is no historical context, so the injection step is skipped.
[0196] Step 1-5-3: The token budget middleware checks the cumulative token consumption. In this example, it's the first model call, so the cumulative consumption is zero, and it's allowed to proceed normally.
[0197] Steps 1-6: Main Agent Task Decomposition and Subtask Creation. After receiving the request, the main agent decomposes the task based on the injected skill description information. The skill description pre-defines three standard steps for onboarding, and the main agent creates three subtasks accordingly:
[0198] First sub-task: Create employee files in the HR system and allocate appropriate office equipment;
[0199] Second sub-task: Activate domain accounts and email addresses in the IT system;
[0200] The third subtask: Enter employee information and activate access control permissions in the access control system. The main agent calls the delegate tool (task tool) three times, passing in the subtask description and the sub-agent type "general-purpose" respectively. The task tool call is checked by the middleware; if the currently active skill "onboarding" is included in the allowed-tools whitelist, the call is allowed.
[0201] Steps 1-7: Sub-agents execute in parallel. The sub-agent executor receives three delegation requests and allocates thread resources for each within the global rate limiter (maximum concurrency = 3), executing the following sub-steps:
[0202] Step 1-7-1: Build an independent execution context for each subtask: an independent checkpoint storage space (completely isolated from the main agent's dialogue history), independent system hints and available toolsets, and an independent token consumption counter.
[0203] Step 1-7-2: Activate the sandbox environment. Activate the secure sandbox runtime module for each sub-agent, mapping the task working directory and skill resource directory from the host machine to internal sandbox paths (e.g., / mnt / user-data / workspace and / mnt / skills / ). The environment policy controller verifies that the injected environment variable names (HR_API_KEY, IT_ADMIN_TOKEN, ACCESS_CONTROL_KEY) conform to POSIX (Portable Operating System Interface) naming conventions and allows them to proceed normally. The user identities of the three sub-agents are inherited from the autonomous agent through the authorization attribute transfer mechanism, the state machine changes from pending to running, and parallel execution begins.
[0204] Taking the first subtask (HR file creation and equipment allocation) as an example, the sub-agent reads environmental variables in the sandbox environment. Obtain API credentials and perform the following operations: Using the credentials, call the HR system API to send an employee information creation request (Name: Zhang San, Position: Development Engineer, Department: Technical Department). The HR system returns employee number E20240015. Based on the returned employee number, call the equipment inventory API to query the list of available office equipment. Combining the preset equipment configuration standards in the skill description (one 14-inch laptop and one 27-inch external monitor for Development Engineers), automatically match the ThinkPad T14 (serial number SN-LT-20240701) and DELL 27-inch monitor (serial number SN-MN-20240703) in inventory. Call the equipment allocation API to submit an allocation request: {"employee_id":"E20240015", "assets":["SN-LT-20240701", "SN-MN-20240703"]}, and obtain allocation confirmation.
[0205] The second sub-agent uses environmental variables. Obtain IT system management credentials and call the IT system API to create a domain account named zhangsan and an email address zhangsan@company.com. Sub-agent ③ uses environment variables... Obtain access control system credentials, call the access control system API to enter employee information and activate access control permissions (valid from 2024-07-22).
[0206] Step 1-7-3, Sub-agent Step Event Capture and Push. Each operation step in the sub-agent's execution process generates a structured step event through the step event capture mechanism. Each step event is truncated (maximum 8192 characters). The truncated step events are written to a RedisStream via the XADD command of the streaming event bridge module, stored as key-value pairs of kind=event, event=step. The gateway layer front-end SSE connection receives step events in real time via XREAD, and users see real-time progress prompts on the front-end interface, such as "[First Subtask] Call the HR system to create a file... Employee number E20240015 returned", "[First Subtask] Query equipment inventory... Matching equipment found", "[First Subtask] Submit equipment allocation application... Allocation successful". Simultaneously, step events are persisted to the subagent.step category of RunEventStore, and historical step information can be loaded via the list_events interface after the front-end page is refreshed.
[0207] Step 1-7-4: Delegation Ledger Writing. After all three sub-agents have completed their execution (status changes to completed), their respective token consumption counters will accumulate the token budget middleware injected into the main agent (the first sub-agent consumes 12850 input tokens and 3200 output tokens; the second sub-agent consumes 5100 input tokens and 1800 output tokens; sub-agent ③ consumes 4200 input tokens and 1500 output tokens). The sub-agent executors will write the execution results into the main agent's delegation ledger in the form of a structured summary: First entry: Employee file created (number E20240015), ThinkPad T14 laptop (SN-LT-20240701) and DELL 27-inch monitor (SN-MN-20240703) assigned, status completed; Second entry: Domain account zhangsan and email zhangsan@company.com activated, status completed; Third entry: Access control permissions activated (valid from 2024-07-22), status completed. The total number of entries in the ledger is 3, which does not exceed the maximum number of entries (50).
[0208] Steps 1-8: The main agent summarizes and provides the final response. The main agent proceeds to the next round of model inference. The persistent context middleware renders the three entries in the delegation ledger as hidden HumanMessages (carrying the durable_context_data flag) and injects them into the request message list. The main agent reads the contents of the delegation ledger, confirms that all subtasks have been successfully completed, and generates a summary response to return to the user: "The onboarding process for Zhang San (Development Engineer, Technical Department) has been completed: HR system file created (employee number E20240015), one ThinkPad T14 laptop (SN-LT-20240701) and one DELL 27-inch monitor (SN-MN-20240703) have been assigned; domain account zhangsan and email zhangsan@company.com have been activated; access control permissions have been activated (valid from 2024-07-22)."
[0209] Steps 1-9: Streaming Event Push and Token Statistics. During the main agent's response generation process, streaming content events (kind=event, event=message) are pushed to the front end in real time through the streaming event bridging module. The front end then renders the response content token by token. After the response is completed, an end marker (kind="end") is appended to the RedisStream. The front end releases the connection upon detecting the end marker. The token budget middleware calculates the total consumption across the entire chain: the main agent consumes 8500 input tokens and 2200 output tokens; the three sub-agents consume a total of 22150 input tokens and 6500 output tokens, for a total of 39350 tokens across the entire chain, all of which are within the budget limit. The sandbox processes of each sub-agent terminate naturally upon the end of the request. The environment variables HR_API_KEY, IT_ADMIN_TOKEN, and ACCESS_CONTROL_KEY are destroyed upon the end of the process lifecycle, ensuring zero residual sensitive credentials.
[0210] Steps 1-10: Memory Persistence and Cross-Session Reuse. After this round of dialogue is completed, the memory middleware triggers the memory retrieval process in the after_agent hook, executing the following sub-steps:
[0211] Step 1-10-1: Extract user messages and the final assistant reply from the dialogue state (excluding intermediate messages from tool calls) and send them to the memory queue. The memory queue uses a debouncing strategy (30-second debouncing window) to merge dialogue fragments within the same window.
[0212] Step 1-10-2: After the debounce window expires, the large language model is called to extract dialogue fragments from the queue and generate structured memory facts: Fact 1 (Entity class, confidence 0.95): Employee Zhang San, ID E20240015, position: Development Engineer, department: Technical Department; Fact 2 (Event class, confidence 0.92): Onboarding completed on July 22, 2024, and equipped with a ThinkPad T14 (SN-LT-20240701) and a DELL 27-inch monitor (SN-MN-20240703); Fact 3 (Decision class, confidence 0.88): Development Engineer's equipment configuration standard: 14-inch laptop + 27-inch external monitor; Fact 4 (Preference class, confidence 0.85): Onboarding was completed automatically through the / hr / onboarding skill.
[0213] Step 1-10-3: Execute deduplication logic: Normalize the whitespace characters in the content field of the four facts and compare them one by one with the existing facts in storage. In this example, it is the initial onboarding process, and there are no relevant historical facts in storage. All four new facts pass the deduplication check. The memory is persistently stored in the user's isolated directory using atomic file updates: first write to a temporary file, then replace the original file with an atomic rename by the operating system, and immediately invalidate the memory cache after the write is completed.
[0214] Step 1-10-4: When the user queries "Zhang San's device configuration" or applies for a development engineer's onboarding, the system generates an embedding vector based on the current query topic, retrieves relevant historical memories based on cosine similarity, and injects the agent context with a budget less than the maximum number of injection tokens (2000) to achieve cross-session knowledge continuation and personalized response.
[0215] In its specific implementation, this application provides a computer storage medium and a corresponding data processing unit. The computer storage medium is capable of storing a computer program, which, when executed by the data processing unit, can run the invention's content and some or all of the steps in various embodiments regarding a multi-agent service integration method system supporting secure isolation and dynamic expansion. The storage medium can be a magnetic disk, optical disk, read-only memory (ROM), or random access memory (RAM), etc.
[0216] Those skilled in the art will clearly understand that the technical solutions in the embodiments of the present invention can be implemented using computer programs and their corresponding general-purpose hardware platforms. Based on this understanding, the technical solutions in the embodiments of the present invention, or the parts that contribute to the prior art, can be embodied in the form of computer programs, i.e., software products. These computer program software products can be stored in a storage medium and include several instructions to cause a device containing a data processing unit (which may be a personal computer, server, microcontroller, MCU, or network device, etc.) to execute the methods described in various embodiments or certain parts of the embodiments of the present invention.
[0217] This invention provides a multi-agent service integration system that supports secure isolation and dynamic expansion. Many methods and approaches exist for implementing this technical solution; the above description is merely a preferred embodiment. It should be noted that those skilled in the art can make various improvements and modifications without departing from the principles of this invention, and these improvements and modifications should also be considered within the scope of protection of this invention. All components not explicitly stated in this embodiment can be implemented using existing technologies.
Claims
1. A multi-agent service integration system supporting secure isolation and dynamic expansion, characterized in that, It includes a streaming event bridging module, a hierarchical orchestration engine module, a secure sandbox operation module, a memory management module, a dynamic capability extension module, and a declarative middleware pipeline module; The streaming event bridging module is deployed between the gateway layer and the agent execution layer. It builds a cross-process event stream channel based on the publish-subscribe pattern, and pushes metadata events, execution step events and streaming content events generated during the operation of the agent to the front end in real time. It supports a disconnection reconnection mechanism based on event ID breakpoint resume. The hierarchical orchestration engine module includes a main agent unit and sub-agent units. The main agent unit receives user instructions and decomposes tasks, delegating sub-tasks to sub-agent executors. The sub-agent unit manages a thread pool, creates an independent execution context for each sub-task, and runs in an independent checkpoint space. During execution, step events are captured in real time and pushed to the front end through an event stream to display the execution progress of the sub-agent. After execution, the structured results are returned to the delegation ledger of the main agent. The secure sandbox runtime module provides an isolated command execution environment for each agent, including a sandbox abstract interface layer and a multi-backend adaptation layer. The sandbox abstract interface layer defines unified command execution, file reading and writing, environment variable injection, and file search. The multi-backend adaptation layer supports three forms: local process sandbox, container sandbox, and cloud sandbox, and automatically selects the appropriate one based on the deployment scenario. The secure sandbox runtime module also includes an environment policy controller, which verifies whether the injected environment variable names conform to security specifications to prevent command injection. The memory management module includes a summarization middleware and a memory middleware. The summarization middleware is triggered when the number of conversation messages exceeds a preset threshold. It divides the conversation history into a part to be summarized and a part to be retained. It calls a large language model to generate structured summary text for the part to be summarized, using the summary to replace the original historical messages to control the context length, while retaining the most recent conversation rounds to ensure the integrity of the recent context. After each round of conversation, the memory middleware sends the user input and the agent's response to the memory queue. After debouncing, it merges two or more conversation segments within the same time window and asynchronously extracts the structured memory containing entities, events, and preferences through a large language model. The memory is then persistently stored for reuse in subsequent conversations based on semantic similarity. The dynamic capability extension module includes a skill registry center, a slash command parser, and a credential security binding unit. The skill registry center maintains public skills and user-defined skills in the form of structured file packages. Each skill unit contains a skill description file, an optional tool whitelist, and a declaration of required credentials. The slash instruction parser identifies the slash skill reference format in the user message, parses the target skill by name and category, and reads the skill description content. When a skill is activated, the credential security binding unit extracts the corresponding credential value from the request-level credential storage and injects it into the sandbox process as an environment variable. After the request ends, the credential value is destroyed along with the lifecycle of the child process. The declarative middleware pipeline module decouples cross-cutting concerns into independent middleware in the form of a middleware chain based on the principle of separation of concerns. These middleware include input validation middleware, read / write gating middleware, token budgeting middleware, and persistent context middleware. Each middleware follows a unified abstract interface and registers standard hook points for execution during the agent's lifecycle. These hook points include request modification interception before model invocation, response processing after model invocation, and post-processing after the agent completes its current round of inference.
2. The system according to claim 1, characterized in that, The streaming event bridging module includes a RedisStream-based cross-process bridge, which performs the following steps: Step 1-1: Create an independent RedisStream data structure for each agent running instance, using the running instance identifier concatenated with a fixed prefix as the Stream key name; Steps 1-2: Events generated during the execution of the intelligent agent are written to the Stream in key-value pairs, and the expiration time of the Stream is set through the Redis transaction pipeline to achieve automatic cleanup of the Stream after the running instance ends. Steps 1-3: The gateway layer frontend subscribes to the Stream, supporting the input of the last received event ID as the starting reading position. When the connection is unexpectedly disconnected and the frontend reconnects, the last received event ID is carried in the last event ID header. The bridge locates the breakpoint position based on the received last event ID and continues reading, realizing breakpoint replay of the event. Steps 1-4: Append an end marker when each Stream write ends. After the subscriber detects the end marker during the event reading process, it completes the subscription and releases the connection resources.
3. The system according to claim 2, characterized in that, The cross-process bridge uses a batch read strategy for subscription; the cross-process bridge uses an exponential backoff retry strategy when the Redis connection is interrupted, and the retry latency satisfies: , in, The retry delay time, For the initial retry delay, The heartbeat interval is n, and the number of retries is n. After a successful retry, the subscription cursor position is restored using the event ID of the last successful read. After the retries reach the limit, an exception is thrown to the caller to terminate the subscription, thus implementing degradation processing.
4. The system according to claim 3, characterized in that, The sub-agent unit in the hierarchical orchestration engine module includes an execution state machine, which includes the following states: waiting, indicating that the subtask has been created but execution resources have not yet been allocated; running, indicating that the sub-agent is executing. Completed, indicating that the subtask has ended normally; This indicates that the subtask failed to execute. "Cancelled" indicates that the subtask was actively cancelled externally; "Timeout" indicates that the subtask was terminated after exceeding the preset time limit. The sub-agent unit captures new messages as step events during the operation of the sub-agent, performs character truncation processing on each step event to control the event payload size, and marks the part exceeding the truncation limit as truncated and discards it; The truncated step events are pushed to the front end through the streaming event bridging module and persisted as runtime instance event records, so that the front end can still load historical step information after the page is refreshed.
5. The system according to claim 4, characterized in that, The sub-agent unit constructs an independent execution context when creating the sub-agent, including an independent checkpoint storage space and an independent token consumption counter; the checkpoint space of the sub-agent is isolated from the dialogue history of the main agent; the token counter of the sub-agent independently accumulates the input and output tokens during the tool call process, and injects the token consumption into the token count of the main agent after execution, thereby realizing full-link token tracking. The results of the sub-agents after execution are written to the main agent in the form of a structured summary. The summary includes a task description, sub-agent type, execution status, result summary text, and reference identifiers for the result data. The delegation ledger has a maximum number of entries, and when this limit is exceeded, the oldest completed record is automatically pruned. During each subsequent model inference, the delegation ledger is injected into the main agent in the form of a hidden message through a persistent context middleware, enabling the main agent to know the completion status of all historical delegated tasks.
6. The system according to claim 5, characterized in that, The secure sandbox runtime module's sandbox abstract interface layer defines a file system mapping mechanism, mounting the host machine's task working directory and tool resource directory to different paths within the sandbox. This enables bidirectional secure data exchange between the host file system and the sandbox environment. Simultaneously, it restricts the range of accessible host machine paths within the sandbox using path regular expressions. The path validation rules are as follows: , in, For the set of paths that are allowed to be accessed, The file path to be verified. This is a collection of mounted host machine directories. Regular expressions are used to match paths; out-of-range path access requests are intercepted at the sandbox abstraction layer to prevent the sandbox from accessing unauthorized directories without authorization.
7. The system according to claim 6, characterized in that, The local process sandbox is implemented based on operating system subprocesses, limiting the working directory to the specified sandbox root directory. Command execution is completed by starting subprocesses, and environment variable dictionaries can be passed in. The built-in command timeout controller sets the default maximum execution time for a single command and supports overwriting on a per-command basis. After the timeout, a termination signal is sent to the subprocess to force it to exit. The standard output and standard error output of the subprocess are captured through bounded pipes. The part exceeding the capture limit is discarded and marked with a truncation prompt. The container sandbox is implemented based on the AIO sandbox backend, which sends structured commands to the container via an HTTP interface and supports custom image, port mapping and mount directory configuration. Before injecting environment variables, the environment policy controller verifies whether the variable name conforms to the POSIX environment variable naming convention. Variable names that do not conform to the convention are directly rejected and an exception is thrown.
8. The system according to claim 7, characterized in that, The summary middleware of the memory management module performs the following steps: Step 2-1: Count the total number of messages in the current session. Total number of tokens The summary process is triggered when any metric exceeds the configured threshold. The triggering condition is as follows: , in, As a triggering condition, and The trigger threshold is configurable; Step 2-2: Divide the dialogue history into messages to be summarized. and reserved messages The message consists of two parts: the most recent K rounds of dialogue are retained; system messages and hidden context messages marked as non-streamable are not affected by the digest. Steps 2-3: Invoke the dedicated large language model Treating summary messages Generate structured summary text S: , in, For dedicated large language models, This is an earlier dialogue message awaiting a summary; the summary includes the key topics of the dialogue, completed steps, pending matters, and important decision-making criteria. Steps 2-4: Before the summary is generated, trigger the pre-hook to notify other middleware that the message is about to be removed, allowing the message content to be backed up to external storage before the removal operation is performed; Steps 2-5: Remove the original historical messages from the state and replace them with summary text, while saving the retained messages; in subsequent dialogues, the summary text is injected into the agent's input as a hidden persistent context data message through the persistent context middleware, and a character limit is set to truncate excessively long summaries.
9. The system according to claim 8, characterized in that, The memory middleware performs the following steps: Step 3-1: After each round of agent responses, extract user messages from the dialogue state. And the final assistant's reply This excludes intermediate messages during the tool invocation process; Step 3-2: Send the message pairs into the memory queue. The memory queue adopts a debouncing strategy and is configured with a fixed debouncing time window. Multiple consecutive dialogue segments within the same window are merged into a single batch processing step: , in, This is a collection of batch dialogue segments merged within the debounce window. For the first User messages in a round-robin conversation For the first The assistant in the conversation eventually replied to the message. For the first The user messages in the round-robin dialogue and the assistant's final reply message pair. For the first The timestamp of the round-robin conversation The start time of the stabilization window; Step 3-3: After the debounce window expires, the large language model is invoked to extract dialogue fragments from the queue and generate structured memory records. : , in, For memory categories, For memorizing content, The confidence level is given by m, which represents the number of memory entries extracted in this batch. After extraction, deduplication logic is executed: the content field of the newly extracted facts is normalized by removing whitespace characters, and then compared with the existing facts in storage one by one. The actual set of new facts added after deduplication is determined. for: , in, This represents an additional set of new facts. Represents a set of existing facts. For memory record collection, for Memory elements in for Memory elements in A function to normalize whitespace characters. For new memory elements The original memory content text, Memorizing elements in an existing set of facts The original memory content text is persistently stored in an external storage system using atomic file updates; Steps 3-4: At the start of subsequent conversations, relevant historical memory records are retrieved based on semantic similarity according to the current dialogue topic, and the top k memories with the highest similarity are used as context for the agent's reasoning process.
10. The system according to claim 9, characterized in that, The public skills and user-defined skills are organized in a separate file directory, including skill description files in Markdown format. The file header declares skill metadata in YAML format, including: skill name, skill description, license information, list of required credentials, list of allowed tools, and whether automatic activation is allowed. Each skill unit is an independent capability carrier that can be copied, shared, and version managed. The public skills mentioned are general capabilities built into the platform, and are read-only and cannot be edited; The user-defined skills are personalized abilities created and managed by the user, and can be edited and deleted; The slash instruction parser supports the following two complementary activation modes: Explicit activation mode: The user explicitly references the skill in the input message. The parser searches for matching skill files in the skill registry by name and category, reads the skill description content, and calculates the content hash. Automatic activation mode: During the inference process, the system automatically loads and injects the matching skill description text into the agent's system prompts based on the list of enabled skills in the current session configuration. The agent can then autonomously determine whether to use the skill based on the current task requirements. The input validation middleware in the declarative middleware pipeline module performs the following steps: Step 4-1: Obtain the content of the most recent real user message before calling the large language model; Step 4-2: Maintain an XML-formatted tag name with special semantics in system prompts and internal frame messages; perform HTML entity escaping on blacklist tags appearing in user messages to defend against prompt injection attacks from the source, serving as the first semantic protection barrier against structured prompt injection. Step 4-3: Add plain text boundary markers at the beginning and end of the user message to form an encapsulated structure of boundary markers, original user content, and boundary markers, serving as the second semantic protection barrier for structured prompt injection. The read-write gated middleware in the declarative middleware pipeline module performs the following steps: Step 5-1: Intercept the agent's request to call the file modification tool and extract the target file path; Step 5-2: Retrieve the most recent read record of the target file path in the dialogue message history. The read record is marked with the SHA-256 hash of the entire file content: , in, A SHA-256 hash tag representing the content of a file. To read the entire contents of the time file; The data is stored in the metadata of the message returned by the read_file tool; if the message history is compressed due to the digest, resulting in the loss of read records, the read mark is also lost, and the gating determines that it has not been read. Step 5-3, if a valid read tag is found Then, the current content of the target file is read through the sandbox and the SHA-256 hash value is calculated. ,and Comparison: , in, represent and The comparison results This is the SHA-256 hash value of the current file content read through the sandbox before the write operation. The hash value of the read tag in the most recently read record; when When write operations are allowed, it means the file content has not been modified since the last read; when The write operation is rejected and an error message is returned, requiring the agent to reread the file before making any modifications; Step 5-4: Immediately after the write operation is completed, invalidate the read marker of the file path, forcing any subsequent modification operation on the same file to be read again. Step 5-5: Serialize read mark checks and write operations on the same file path using thread locks; The read / write gating middleware adopts a fault-based open strategy for cases where file content cannot be checked: when the sandbox backend returns an Error: prefix string or the target file is binary content, the read / write gating middleware allows the write operation and generates error information by itself. The token budgeting middleware in the declarative middleware pipeline module accumulates the consumption of input and output tokens in a multi-round tool call loop, specifically by performing the following steps: Step 6-1: After each model call, extract token usage metadata and statistical input tokens from the model response. Output token Total number of tokens This is added to the cumulative consumption of this running instance; Step 6-2: Calculate the consumption percentage of the three dimensions—input tokens, output tokens, and total tokens—and take the maximum value as the current budget pressure indicator. : , in, This represents the current token budget pressure. , , These are the budget limits for input tokens, output tokens, and total tokens, respectively. Step 6-3, when Before the next round of model calls, a budget warning message is injected into the agent to inform it of the current usage and remaining quota for each dimension; Indicates the alarm threshold; Step 6-4, when At that time, directly remove the tool call request from the agent message, force the large language model to generate a final response without tool calls, and record the reason for stopping for the upper-layer caller to read and determine whether the termination was triggered by budget. Indicates the stopping threshold; Before the large model is called, the persistent context middleware in the declarative middleware pipeline module merges and renders the two types of persistent context data, namely summary text and delegation ledger, into a hidden user message HumanMessage and injects it into the request message list. HumanMessage carries a specific hidden tag key, which is automatically identified and skipped during message history processing and streaming. The persistent context middleware also maintains a single-execution flag for the persistent context injection: to run the instance identifier. Injecting state for key tracking: , in, To inject the decision function, A status query function has been injected for the current round. To negate the logic; The delegated ledger limits the number of characters in the result summary of each subtask during rendering. If the limit is exceeded, the result is truncated and an ellipsis is added. At the same time, the maximum number of entries in the delegated ledger is maintained. If the limit is exceeded, the earliest completed entry is pruned.
