鸿蒙HarmonyOS Agent 记忆与子 Agent 实战 —— 上下文压缩、episodic memory、任务委派

发布时间:2026/9/13 23:26:31

鸿蒙HarmonyOS Agent 记忆与子 Agent 实战 —— 上下文压缩、episodic memory、任务委派 一、前言长对话和复杂任务的两个天花板Agent 跑久了会遇到两个天花板天花板一上下文溢出。每轮对话都在累积消息历史50 轮后 prompt tokens 可能超过模型的上下文窗口比如 64000。此时模型要么报错、要么截断早期消息丢失关键信息。你需要的是压缩——把早期对话摘要成简短的 episodic memory只保留最近几轮的完整消息。天花板二任务复杂度。一个调研并写报告的任务Agent 可能需要先搜索、再分析、最后写作。如果所有工作都在一个 Agent 里做上下文会迅速膨胀且不同阶段的工具和提示词互相干扰。你需要的是委派——把这个任务的一部分交给一个子 Agent子 Agent 用独立的上下文和工具集完成工作把结果汇报给父 Agent。但这两个能力都有自己的陷阱压缩失败不能丢历史事务式委派不能无限递归失控子 Agent 不能执行危险工具安全。ArkAgent 用 ContextCompressor SubAgent SubAgentPolicy 解决这些问题。二、ContextCompressor事务式压缩ContextCompressormemory/ContextCompressor.ets是一个 SPI 接口负责把长对话历史压缩成 episodic memory。2.1 SPI 契约事务式/** * SPI: compress long conversation history into episodic memory. * Implementations must be transactional: no partial history mutation on failure. */ export interface ContextCompressor { compress(state: AgentState, context: CompressContext): PromiseCompressResult }最关键的约束Implementations must be transactional: no partial history mutation on failure.——压缩失败时历史不能被部分修改。要么完整压缩成功要么历史原封不动。2.2 CompressResult三种结果export enum CompressOutcome { skipped skipped, // 跳过不需要压缩 compressed compressed, // 成功压缩 failed failed // 压缩失败历史不变 }skipped的常见原因没有 usage 数据、历史太短、token 数低于阈值、上一次就是压缩调用。2.3 触发条件constructor( client: LLMClient, modelConfig: ModelConfig, totalTokenThreshold: number 64000, // token 阈值 keepRecentMessageCount: number 10, // 保留最近 10 条 summaryPrompt: string DEFAULT_SUMMARY_PROMPT, minMessagesToSummarize: number 3 )压缩触发的判断逻辑// 没有 usage → skip if (state.usages.length 0) return CompressResult.skipped(no_usage) // 历史太短 → skip if (state.history.messages.length this.keepRecentMessageCount) return CompressResult.skipped(history_too_short) // token 数低于阈值 → skip const promptTokens lastUsage.promptTokens if (promptTokens undefined || promptTokens this.totalTokenThreshold) return CompressResult.skipped(below_threshold) // 上一次就是压缩调用 → skip防止压缩循环 if (lastUsage.raw?.get(source)?.asString() context_compression) return CompressResult.skipped(last_usage_is_compression)最后一条很关键——防止压缩循环。压缩本身也会消耗 token调用 LLM 生成摘要如果不跳过压缩生成的 usage 又会触发下一次压缩陷入无限循环。2.4 安全切分点压缩需要把历史切成两部分前面的压缩成摘要后面的保留原样。切分点不能在 Tool Call/Result 中间切开——否则两侧都有不配对的 Call/Result。export function computeSafeSplitIndex(messages: AgentMessage[], keepRecentMessageCount: number): number { if (messages.length keepRecentMessageCount) { return -1 } let splitIndex messages.length - keepRecentMessageCount while (splitIndex 0) { const compressPart messages.slice(0, splitIndex) const keepPart messages.slice(splitIndex) // 两侧都必须配对完整 if (HistoryInvariants.toolCallsPaired(compressPart) HistoryInvariants.toolCallsPaired(keepPart)) { return splitIndex } splitIndex-- // 不安全就往前挪 } return -1 // 找不到安全切分点 }2.5 原子提交// --- Atomic commit (history first; usage attribution only after success) --- state.history.episodicMemories.push(episode) state.history.messages newMessages if (!HistoryInvariants.toolCallsPaired(newMessages)) { return CompressResult.failed(post_commit_pairing_violation, usage) } // 只有 history 提交成功后才归因 usage if (usage ! undefined context.onUsage ! undefined) { context.onUsage(usage) }usage 归因的顺序先提交历史后归因 usage。如果压缩失败LLM 返回空摘要/畸形 JSONusage 不归因——CompressContext.onUsage只在成功路径调用。Runtime 侧也做了暂存stagedUsage只在CompressOutcome.compressed时写入state.usagesfailed/skipped 全量回滚 history usages。2.6 Runtime 侧的压缩调度与全量回滚Runtime 的maybeCompressContext方法是压缩的调度入口。它在每轮 Agent Loop 结束后判断是否需要压缩并负责全量回滚// runtime/AgentRuntime.ets — maybeCompressContext private async maybeCompressContext(ctx: RunContext): Promisevoid { if (this.config.contextCompressor undefined) return // 暂存当前状态的快照失败时全量回滚 const before this.state.history.clone() const usagesBefore this.state.usages.slice() let stagedUsage: ModelUsage | undefined undefined const onUsage (usage: ModelUsage): void { stagedUsage usage } const result await this.config.contextCompressor.compress(this.state, new CompressContext(this.config.idGenerator, ctx.signal, onUsage)) if (result.outcome ! CompressOutcome.compressed || result.episodeId undefined) { // failed | skipped: 全量回滚 history 和 usages this.state.history before this.state.usages usagesBefore.slice() stagedUsage undefined return } // 成功路径提交暂存的 usage const usageToRecord stagedUsage ! undefined ? stagedUsage : result.usage if (usageToRecord ! undefined) { this.state.usages.push(usageToRecord) } }这段代码体现了事务式的核心——暂存staging 条件提交conditional commit。before和usagesBefore是回滚快照stagedUsage是暂存的 usage不直接写入 state.usages。只有CompressOutcome.compressed时才真正提交。2.7 DEFAULT_SUMMARY_PROMPT结构化摘要压缩调用的 LLM 不是随便总结一下而是要求输出结构化的 XML 摘要DEFAULT_SUMMARY_PROMPT 要求 LLM 输出 state_snapshot XML overall_goal任务的总体目标/overall_goal key_knowledge关键事实和约束/key_knowledge file_system_state文件系统状态/file_system_state recent_actions最近的操作/recent_actions current_plan当前计划/current_plan这个结构化摘要被存入EpisodicMemory.summary模型可以通过retrieve_memory工具检索它。结构化的好处是摘要不会丢失关键信息比如用户要的是法棍的失重率不是吐司的模型恢复时有明确的上下文锚点。三、MemoryService窄接口MemoryServicememory/MemoryService.ets提供对 episodic memory 的只读访问。3.1 窄接口设计export interface MemoryService extends ToolService { listEpisodes(): EpisodicMemory[] findEpisode(snapshotId: string): EpisodicMemory | undefined }注释Session-scoped read access to episodic memories.Tools never receive a mutable AgentState handle (ADR-0013).只读——工具通过 MemoryService 读取历史 episodic memory但不能修改 Agent 状态。RuntimeMemoryService通过 getter 函数获取 live episodes保证 resume/compress 后能读到最新数据。3.2 retrieve_memory 工具RETRIEVE_MEMORY_TOOL_NAME retrieve_memory DEFAULT_MEMORY_LIMIT 20 MAX_MEMORY_LIMIT 100模型可以调用retrieve_memory工具搜索历史 episodic memory参数支持snapshot_id、offset、limit。每个参数都有严格校验snapshot_id不能空、offset非负整数、limit不超过 100。四、SubAgent任务委派SubAgentmemory/SubAgent.ets实现了任务委派——父 Agent 可以把一部分工作交给子 Agent。4.1 委派模型DELEGATE_TASK_TOOL_NAME delegate_task CLONE_ASSIGNEE clone SUB_AGENT_SERVICE_ID arkagent.sub_agent父 Agent 通过delegate_task工具委派任务参数包含assignee执行者clone表示克隆父 Agent或命名 workertask_description任务描述delegate_task的工具定义JSON Schemafunction delegateTaskDefinition(): ToolDefinition { const assigneeProp new JsonObject() .set(type, JsonValue.string(string)) .set(description, JsonValue.string( Worker name or clone. clone reuses the parent config.)) const taskProp new JsonObject() .set(type, JsonValue.string(string)) .set(description, JsonValue.string(Natural-language task description.)) const props new JsonObject() .set(assignee, JsonValue.object(assigneeProp)) .set(task_description, JsonValue.object(taskProp)) return new ToolDefinition( delegate_task, Delegate a sub-task to a worker sub-agent with isolated context., new JsonObject() .set(type, JsonValue.string(object)) .set(properties, JsonValue.object(props)) .set(required, JsonValue.array([ JsonValue.string(assignee), JsonValue.string(task_description) ])) ) }4.2 SubAgentDefinition命名 worker 的工厂命名 worker 通过SubAgentDefinition注册每个 worker 有一个SubAgentFactory——由宿主 App 提供的工厂函数负责创建 worker 的AgentRuntimeConfigexport class SubAgentDefinition { readonly name: string readonly description: string readonly factory: SubAgentFactory static create(name: string, description: string, factory: SubAgentFactory): ResultSubAgentDefinition, ArkAgentError { const trimmed name.trim() if (trimmed.length 0) { return Result.failure(ArkAgentError.config(subagent_name_empty, ...)) } // clone 是保留名称不能用作 worker 名 if (trimmed.toLowerCase() CLONE_ASSIGNEE) { return Result.failure(ArkAgentError.config(subagent_name_reserved, Sub-agent name clone is reserved)) } return Result.success(new SubAgentDefinition(trimmed, description, factory)) } }关键约束clone是保留名称——不能注册一个叫 clone 的 worker因为它和克隆父 Agent的 assignee 冲突。4.2 SubAgentPolicy委派上限ADR-0013 冻结了委派的预算策略export class SubAgentPolicy { readonly maxDepth: number // 默认 1 readonly maxDelegationsPerRun: number // 默认 4 readonly maxConcurrentChildren: number // 默认 2 readonly parentContextMessageCount: number // 默认 10 constructor( maxDepth: number 1, maxDelegationsPerRun: number 4, maxConcurrentChildren: number 2, parentContextMessageCount: number 10 ) }参数默认含义maxDepth1最大递归深度子 Agent 不能再委派maxDelegationsPerRun4单次 run 最多委派次数maxConcurrentChildren2最大并发子 AgentparentContextMessageCount10注入多少条父消息作为上下文4.3 预算检查委派前检查预算超出则拒绝if (depth policy.maxDepth) { return delegateError(subagent_depth_exceeded, ...) } if (this.delegationsThisRun policy.maxDelegationsPerRun) { return delegateError(subagent_run_budget_exceeded, ...) } if (this.activeChildren.size policy.maxConcurrentChildren) { return delegateError(subagent_concurrent_budget_exceeded, ...) }五、⚠️ 踩坑malicious factory delegate_task 安全加固5.1 症状阶段 7 Codex 首轮发现的 P1 安全问题Worker 基座 Registry 仍然可能包含delegate_task——恶意的 SubAgentFactory 可以自定义执行器在 worker 的 Registry 里重新注册 delegate_task绕过子 Agent 不能再委派的限制。5.2 根因forceWorkerConfig虽然过滤了delegate_task但如果 factory 在创建后重新注册了它过滤就被绕过了。5.3 修复双重拦截export function buildWorkerToolRegistry(source: ToolRegistry): ToolRegistry { const tools new ToolRegistry() source.copyIntoExcluding(tools, [DELEGATE_TASK_TOOL_NAME]) // 复制时排除 tools.unregister(DELEGATE_TASK_TOOL_NAME) // 防御性二次 unregister return tools }forceWorkerConfig中也硬性剥离// Hard strip: even a malicious factory registering delegate_task is removed. const tools buildWorkerToolRegistry(source.toolRegistry) if (tools.has(DELEGATE_TASK_TOOL_NAME)) { tools.unregister(DELEGATE_TASK_TOOL_NAME) // 绝对保证 }加上 Runtime 执行入口的isSubAgent检查子 Agent 再调 delegate_task 直接拒绝subagent_worker_cannot_delegate形成双重拦截。回归测试malicious_factory_delegate_task断言evil.callCount0——恶意执行器永远不会被调用。5.4 压缩 Usage 触发压缩循环阶段 7 报告还记录了另一个压缩相关的踩坑压缩调用本身会消耗 token 并产生 usage这个 usage 如果进入state.usages下次检查阈值时会发现token 数还是很高又触发压缩——形成无限循环。修复方案压缩产生的 usage 在raw字段标记source: context_compression触发检查时跳过这个来源// 触发条件的最后一道检查 if (lastUsage.raw?.get(source)?.asString() context_compression) { return CompressResult.skipped(last_usage_is_compression) }5.5 ArkTS 禁止对象字面量类型阶段 7 报告踩坑一现象validateEpisodicMemoryIds返回类型、bridge Observer 字面量编译失败根因arkts-no-obj-literals-as-types/no-structural-typing方案显式 classEpisodeIdValidation、SubAgentBridgeObserverArkTS 不允许用对象字面量类型{ id: string, valid: boolean }作为返回类型也不允许结构类型duck typing。所有看起来像接口的数据结构都必须用显式 class 定义。这和第五篇博客讲的arkts-no-untyped-obj-literals是同一组约束的变体。六、事件桥接与 usage 聚合6.1 子 Agent 事件桥接子 Agent 的事件通过SubAgentBridgeObserver桥接到父 Controller携带完整关联字段this.parent.publishControllerPublic(new SubAgentChildEvent( this.parentSessionId, this.parentRunId, this.childSessionId, event.runId, this.assignee, this.taskDescription, this.depth, event))每个 child 事件都带 parent session/run、child session/run、task/assignee、depth——让父 Agent 的观察者能完整追踪子 Agent 的行为。6.2 usage 只汇总不合并历史ADR-0013 决策 5 的关键约束child Usage 形成结构化汇总并进入 delegate ToolResult metadata是否计入父级聚合统计必须只有一个确定入口禁止同时复制到父state.usages造成重复计费。child 消息历史不合并进父历史。const usages childRuntime.getUsages() const usageSummary ChildUsageSummary.fromUsages(usages) // Never merge child usages into parent state.usages (ADR-0013).子 Agent 的 usage 聚合成一个ChildUsageSummaryprompt/completion/total/callCount放入 delegate ToolResult 的 metadata。绝不把子 Agent 的每条 usage 都追加到父 Agent 的state.usages——那会造成重复计费。ChildUsageSummary的结构export class ChildUsageSummary { readonly promptTokens: number // 子 Agent 所有调用的 prompt 总和 readonly completionTokens: number // 子 Agent 所有调用的 completion 总和 readonly totalTokens: number readonly callCount: number // 子 Agent 总共调了多少次 LLM static fromUsages(usages: ModelUsage[]): ChildUsageSummary { // 聚合所有 usage 的 prompt/completion/total/callCount } toJson(): JsonObject { // 序列化进 ToolResult metadata } }6.3 子 Agent 失败的安全处理子 Agent 执行失败时失败信息只暴露错误码不回传原始异常文本。阶段 7 报告的实施心得记录了这条子 Agent 失败消息只暴露 code不回传原始异常文本防密钥泄露。为什么因为原始异常文本可能包含 Provider 返回的完整错误 body里面可能有 Authorization Header 片段或其他敏感信息。只暴露结构化的错误码如subagent_depth_exceeded既让父 Agent 知道发生了什么又不会泄漏敏感数据。6.4 allocateIsolatedSessionId子 session ID 隔离子 Agent 必须有独立的 sessionId不能和父 Agent 或其他子 Agent 冲突export function allocateIsolatedSessionId( parentSessionId: string, requested: string, activeIds: string[], nextId: () string ): string { const parentId parentSessionId.trim() const trimmed requested.trim() const active new Setstring() for (let i 0; i activeIds.length; i) { active.add(activeIds[i]) } // 请求的名称有效且空闲 → 使用它 if (trimmed.length 0 trimmed ! parentId !active.has(trimmed)) { return trimmed } // 否则强制生成{parentId}_w_{nextId()} let candidate ${parentId}_w_${nextId()} let guard 0 while ((candidate.length 0 || candidate parentId || active.has(candidate)) guard 16) { candidate ${parentId}_w_${nextId()} guard } return candidate }三层保护不能等于 parentId防止子父冲突、不能在 active 集合中防止兄弟冲突、guard 限制最多重试 16 次防止无限循环。七、最佳实践清单7.1 压缩✅ 压缩必须事务式——失败不部分修改历史。✅ 切分点不能切开 Tool Call/Result 配对。✅ 压缩自身产生的 usage 标记 source防止压缩循环。✅ usage 只在历史提交成功后归因。7.2 子 Agent✅ maxDepth 默认 1子 Agent 不能再委派。✅ buildWorkerToolRegistry 过滤 delegate_task 防御性 unregister。✅ Runtime 入口检查 isSubAgent双重拦截递归委派。✅ 子 Agent 事件带完整关联字段。✅ usage 只汇总不合并历史。7.3 Memory✅ MemoryService 是只读窄接口。✅ 工具不直接操作 AgentState。八、常见错误对照表错误做法问题正确做法压缩失败部分修改历史历史不一致事务式失败全量回滚切分点切开 Tool 配对两侧都有孤儿 Call/ResultcomputeSafeSplitIndex压缩 usage 不标记 source压缩循环sourcecontext_compression子 Agent 能再委派无限递归maxDepth1 isSubAgent 检查Worker Registry 含 delegate_task恶意 factory 绕过buildWorkerToolRegistry 双重过滤合并子 Agent usage 到父重复计费只汇总 ChildUsageSummary合并子 Agent 历史到父上下文膨胀子历史不合并九、验证清单压缩超过阈值触发压缩压缩成功后历史缩短压缩失败后历史不变安全切分点不切断 Tool 配对压缩 usage 不触发循环子 Agentdelegate_task 正确委派maxDepth 超出拒绝maxDelegations 超出拒绝maxConcurrent 超出拒绝恶意 factory 不执行callCount0子 Agent 事件带关联字段usage 只汇总不合并十、构建验证NODE_HOME/Applications/DevEco-Studio.app/Contents/tools/node \ DEVECO_SDK_HOME/Applications/DevEco-Studio.app/Contents/sdk \ /Applications/DevEco-Studio.app/Contents/tools/hvigor/bin/hvigorw assembleHar --no-daemonCompileArkTS passed BUILD SUCCESSFUL测试覆盖MemorySubAgent.test.ets压缩/子 Agent/安全隔离/usage 聚合。十一、写在最后压缩事务不丢史切分点要保配对。 委派上限四参数深度一并发二。 Worker 剥离 delegate双重拦截递归。 子 Agent usage 只汇总历史不合并计费不重。 Memory 窄接口只读看工具不碰 State 事。
延伸阅读

更多相关文章

2026/9/12 20:39:25

模板驱动型文档自动化:让业务人员零代码生成合规PDF

1. 项目概述:当文档生产变成“填空题”,而不是“写作文”你有没有经历过这种场景:每周一早上,市场部同事准时把一份《月度客户反馈摘要》模板发到群里,要求销售、客服、产品三个部门各自填入数据,再汇总成P…

2026/9/13 18:03:34

芯片设计中的LVS检查:原理、流程与实战技巧

1. 初识Layout versus Schematic(LVS)的本质在芯片设计领域,Layout versus Schematic(LVS)检查就像电路世界的"照妖镜"。想象一下,你精心绘制了电路原理图(Schematic)&…

2026/9/13 11:45:20

部署Qwen2-VL-2B进行图片OCR识别及VLM推理

1、配置相关环境首先需要建立一个conda虚拟环境,我这里新建了一个名字为qwen2vl_cpu_env的虚拟环境。python -m venv qwen2vl_cpu_env之后激活虚拟环境,激活后,命令行前缀会显示qwen2vl_cpu_env。qwen2vl_cpu_env\Scripts\activate我使用CPU进…

2026/9/14 22:20:41

2026年9月6日GitHub热榜深度盘点:从趋势解读到项目跑通

早上七点多,我照例打开 GitHub Trending,扫了一眼 2026 年 9 月 6 日的日榜。这个习惯我坚持了快五年,比看早间新闻还准时。很多人问我,为什么每天都要刷一遍热榜项目?因为日榜是过去 24 小时内全球开发者用 star、for…

2026/9/14 22:20:41

Codex换肤实战:从默认模型切换到DeepSeek的完整指南

最近后台收到一堆关于Codex的提问,其中问得最多的不是“怎么用”,而是“怎么给Codex换肤”。这里说的换肤,不是换软件界面,而是把Codex默认绑定的那一套官方模型后端,换成你想用的第三方模型服务。比如让Codex CLI直接…

2026/9/14 22:20:41

网站制作公从零搭建避坑指南:选对技术栈流量翻倍

网站制作公从零搭建避坑指南:选对技术栈流量翻倍 网站做好了没人访问,这是很多老板和开发者最头疼的事。你以为上线了就是终点,其实那只是开始。很多项目死在半路上,不是代码写得烂,而是 从零搭建 的底层逻辑就错了。SEO…

2026/9/14 2:17:50

拯救者Y7000黑屏故障排查与维修实战指南

1. 项目概述:一台黑屏的拯救者Y7000,到底卡在哪一步? 联想拯救者Y7000系列笔记本,从2018年第一代搭载i5-8300H开始,到后来的i7-9750H、i7-10750H、i5-11400H,再到2023年款的R7-7840HS,它始终是学…

2026/9/14 0:03:22

KCF目标跟踪算法与OTB工程实现:毕业设计实战解析

简介:这是一份基于KCF核相关滤波算法、融合尺度池与抗遮挡处理的目标检测跟踪MATLAB完整源码,主要面向计算机相关专业准备毕业设计、课程设计或期末大作业的学生,也适合需要项目实战练习的初学者。源码在OTB数据集上完成验证,能够…

2026/9/14 0:03:22

语音情感识别实战:Keras实现LSTM、CNN、SVM与MLP多模型对比

简介:面向语音情感识别入门与进阶开发者,这份基于Keras的项目源码完整实现了LSTM、CNN、SVM、MLP四种模型,兼容Python3.8与Keras/TensorFlow2环境。压缩包内含49个文件,大小约70.31MB,主体包括Python脚本、yaml/json配…

2026/9/14 11:59:31

USB Type-C PCB布局分区设计:电源、高速信号与PD协议全攻略

做硬件这行,Type-C接口算是典型的“看着简单,做起来全坑”的东西。光引脚就24个,高低速信号、电源、控制线全部塞在一个小小的连接器里,如果PCB布局不做规划,打样回来基本就是“插上没反应”、“高速掉线”、“静电一打…

2026/9/14 13:53:59

系统编程学习原型如何补齐稳定性边界

系统编程学习原型如何补齐稳定性边界预算有限时&#xff0c;我先优化明显多余的复制&#xff0c;而不是猜测性地换容器。用借用传递只读数据通常就能减少分配&#xff1a; fn parse(line: &str) -> Result<Item, Error> { /* ... */ }用基准确认热点确实在分配&am…

2026/9/14 11:22:57

雨花区哪家财务公司代理记账比较好?

在雨花区&#xff0c;企业处理财税事务常常面临诸多挑战&#xff0c;选择一家靠谱的财务公司至关重要。湖南巨勤财务管理咨询有限公司就是本地正规实体财税服务机构&#xff0c;深耕本地工商财税行业多年&#xff0c;熟悉当地工商局、税务局最新政策与申报流程。主营公司注册、…

还想了解更多?直接咨询顾问

免费诊断 + 免费方案 + 透明报价。

全国咨询热线400-8866-253
免费获取方案
咨询二维码