evolcore 0.0.43-test.1 → 0.0.43-test.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +22 -0
  3. package/dist/agents/claude-runner.js +26 -2
  4. package/dist/agents/codex/app-server-client.js +12 -0
  5. package/dist/agents/codex-runner.js +49 -8
  6. package/dist/agents/ecagent-runner.js +26 -9
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/menu/client.js +1 -1
  10. package/dist/aun/model-headers.js +17 -0
  11. package/dist/aun/msg/p2p.js +3 -0
  12. package/dist/channels/aun.js +484 -43
  13. package/dist/channels/builtin-plugins.js +16 -11
  14. package/dist/channels/dingtalk.js +83 -31
  15. package/dist/channels/feishu.js +29 -13
  16. package/dist/channels/qqbot.js +32 -11
  17. package/dist/channels/wechat.js +13 -3
  18. package/dist/channels/wecom.js +67 -27
  19. package/dist/cli/agent-command.js +3 -86
  20. package/dist/cli/agent-create.js +22 -6
  21. package/dist/cli/agent.js +1 -79
  22. package/dist/cli/aun-commands.js +1 -0
  23. package/dist/cli/config.js +1 -1
  24. package/dist/cli/daemon-commands.js +47 -2
  25. package/dist/cli/data-command.js +9 -1
  26. package/dist/cli/debug-mode.js +1 -1
  27. package/dist/cli/diag.js +1 -1
  28. package/dist/cli/directory.js +77 -64
  29. package/dist/cli/getmeta-command.js +1 -1
  30. package/dist/cli/index.js +79 -22
  31. package/dist/cli/init.js +1 -23
  32. package/dist/cli/link-rules.js +1 -1
  33. package/dist/cli/managed-command-guard.js +0 -1
  34. package/dist/cli/pa-workspace-command.js +36 -2
  35. package/dist/cli/peer.js +1 -1
  36. package/dist/cli/restart-monitor.js +17 -3
  37. package/dist/cli/role.js +1 -1
  38. package/dist/cli/session-command.js +1 -1
  39. package/dist/cli/stats.js +2 -2
  40. package/dist/cli/thread-command.js +1 -1
  41. package/dist/cli/watch-msg.js +1 -1
  42. package/dist/config/access-policy.js +1 -0
  43. package/dist/config/config-field-policy.js +2 -2
  44. package/dist/config/config-manager.js +7 -0
  45. package/dist/config/role-schema.js +4 -3
  46. package/dist/config/role-service.js +3 -3
  47. package/dist/config-store.js +75 -4
  48. package/dist/core/agent-ipc-registration.js +16 -59
  49. package/dist/core/auth/authorization-audit.js +52 -14
  50. package/dist/core/auth/operation-authorizer.js +0 -11
  51. package/dist/core/auth/operation-catalog.js +0 -18
  52. package/dist/core/channel-loader.js +152 -16
  53. package/dist/core/command/agent-control.js +2 -1
  54. package/dist/core/command/cli-intent-parser.js +0 -8
  55. package/dist/core/command/command-handler.js +17 -46
  56. package/dist/core/command/connect-menu.js +7 -3
  57. package/dist/core/command/menu-catalog.js +3 -2
  58. package/dist/core/command/menu-handler.js +51 -8
  59. package/dist/core/command/menu-protocol.js +20 -0
  60. package/dist/core/command/slash-handler.js +101 -40
  61. package/dist/core/daemon-file-cache.js +3 -3
  62. package/dist/core/evolagent-registry.js +5 -4
  63. package/dist/core/evolagent.js +5 -8
  64. package/dist/core/handoff/argv-parse.js +115 -0
  65. package/dist/core/handoff/ipc-registration.js +1 -1
  66. package/dist/core/ipc-registration.js +19 -2
  67. package/dist/core/memory/consolidation.js +8 -1
  68. package/dist/core/memory/relation-sweep.js +20 -8
  69. package/dist/core/message/aun-ipc-sender.js +28 -1
  70. package/dist/core/message/contact-admission.js +548 -0
  71. package/dist/core/message/im-renderer.js +69 -10
  72. package/dist/core/message/message-admission.js +28 -3
  73. package/dist/core/message/message-bridge.js +46 -5
  74. package/dist/core/message/message-utils.js +0 -5
  75. package/dist/core/message/peer-mode.js +44 -10
  76. package/dist/core/message/response-engine.js +268 -69
  77. package/dist/core/message/retry-scheduler.js +4 -0
  78. package/dist/core/permission/ec-command-parser.js +1 -28
  79. package/dist/core/permission/readonly-shell-query.js +34 -8
  80. package/dist/core/permission/tool-policy.js +50 -5
  81. package/dist/core/role/runtime-policy.js +14 -2
  82. package/dist/core/session/session-manager.js +9 -1
  83. package/dist/core/soul.js +66 -0
  84. package/dist/core/system-session/memory.js +2 -2
  85. package/dist/directory/contact-admission-paths.js +9 -0
  86. package/dist/directory/owner-directory-admission.js +128 -29
  87. package/dist/directory/owner-directory-cache.js +364 -50
  88. package/dist/directory/owner-directory-identity.js +60 -0
  89. package/dist/directory/owner-directory-markdown.js +120 -47
  90. package/dist/directory/owner-directory-policy.js +108 -0
  91. package/dist/directory/owner-directory-query-operation.js +219 -32
  92. package/dist/directory/owner-directory-remarks.js +29 -2
  93. package/dist/directory/owner-directory-search.js +50 -18
  94. package/dist/directory/owner-directory-store.js +150 -30
  95. package/dist/eck/kit-renderer.js +12 -5
  96. package/dist/eck/manifest-engine.js +55 -6
  97. package/dist/eck/message-renderer.js +5 -2
  98. package/dist/eck/paactive-context.js +45 -0
  99. package/dist/ecweb/basic-settings-service.js +2 -2
  100. package/dist/ecweb/message-context-service.js +24 -16
  101. package/dist/index.js +9 -5
  102. package/dist/ipc.js +1 -1
  103. package/dist/paths.js +26 -0
  104. package/dist/response-system/config-resolver.js +1 -1
  105. package/dist/response-system/engines/v1/index.js +4 -1
  106. package/dist/response-system/engines/v1/paactive-flow.js +18 -0
  107. package/dist/response-system/modes/single-session/index.js +7 -2
  108. package/dist/trigger/scheduler.js +3 -5
  109. package/dist/trigger/validation.js +4 -0
  110. package/dist/utils/error-utils.js +5 -2
  111. package/dist/utils/logger.js +13 -4
  112. package/dist/utils/npm-ops.js +2 -2
  113. package/dist/utils/windows-autostart.js +1 -1
  114. package/ecagent/dist/agent-loop.js +43 -1
  115. package/kits/docs/INDEX.md +1 -0
  116. package/kits/docs/context-assembly.md +21 -6
  117. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  118. package/kits/docs/evolcore/INDEX.md +1 -1
  119. package/kits/docs/evolcore/agent-create.md +5 -5
  120. package/kits/docs/evolcore/agent.md +4 -9
  121. package/kits/docs/evolcore/directory.md +137 -0
  122. package/kits/docs/evolcore/menu-protocol.md +55 -0
  123. package/kits/docs/evolcore/response.md +7 -1
  124. package/kits/docs/evolcore/tool-authorization.md +1 -1
  125. package/kits/docs/evolcore/trigger.md +4 -0
  126. package/kits/docs/prompt-loading-architecture.md +6 -2
  127. package/kits/eck_manifest.auxiliary.json +1 -0
  128. package/kits/eck_manifest.json +57 -4
  129. package/kits/eck_manifest.memory.json +67 -3
  130. package/kits/eck_manifest.paactive.json +528 -0
  131. package/kits/eck_message_manifest.paactive.json +233 -0
  132. package/kits/rules/01-overview.md +2 -2
  133. package/kits/rules/03-identity.md +10 -9
  134. package/kits/rules/05-venue.md +2 -4
  135. package/kits/rules/06-channel.md +1 -1
  136. package/kits/schemas/_meta.json +31 -3
  137. package/kits/schemas/agent-config.schema.18.json +5 -0
  138. package/kits/schemas/agent-config.schema.19.json +924 -0
  139. package/kits/schemas/relation-config.schema.12.json +289 -0
  140. package/kits/schemas/role-config.schema.2.json +215 -0
  141. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  142. package/kits/skills/ec-trigger/SKILL.md +4 -4
  143. package/kits/skills/personal-assistant/SKILL.md +109 -53
  144. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  145. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  146. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  147. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  148. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  149. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  150. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  151. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  152. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  153. package/kits/templates/message-fragments/paactive/item.md +3 -0
  154. package/kits/templates/soul/00-GUIDE.md +61 -0
  155. package/kits/templates/soul/01-identity.md +5 -0
  156. package/kits/templates/soul/02-persona.md +11 -0
  157. package/kits/templates/soul/03-duties.md +5 -0
  158. package/kits/templates/soul/04-working-style.md +5 -0
  159. package/kits/templates/system-fragments/bootstrap.md +7 -7
  160. package/kits/templates/system-fragments/commands.md +3 -2
  161. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  162. package/kits/templates/system-fragments/memory.md +1 -1
  163. package/kits/templates/system-fragments/paactive/channel.md +25 -0
  164. package/kits/templates/system-fragments/paactive/reply.md +25 -0
  165. package/kits/templates/system-fragments/paactive/session.md +32 -0
  166. package/kits/templates/system-fragments/personal-assistant.md +65 -0
  167. package/package.json +3 -2
  168. package/dist/cli/handoff-command.js +0 -353
  169. package/dist/directory/owner-directory-remark-operation.js +0 -147
  170. package/kits/docs/evolcore/self-summary.md +0 -29
package/CHANGELOG.md CHANGED
@@ -5,7 +5,30 @@
5
5
 
6
6
  ## Unreleased
7
7
 
8
- ## 0.0.43 (2026-11-02)
8
+ ## 0.0.43 (2026-11-04)
9
+
10
+ ### 身份、名录与联系人准入
11
+
12
+ - Agent 常驻自我设定改用 `personal/soul/` 分册,自动将旧 `persona.md` 并入性格分册;指南和未填写的模板不注入提示词。
13
+ - 移除 `ec agent persona` 命令,常驻设定改为直接维护 Soul 分册文件。
14
+ - 修复创建 Agent 时指定人格文本与 Soul 占位模板冲突的问题,保留对已有设定的覆盖保护。
15
+ - 新增 App 联系人准入协议,按当前 Owner 共识和名录范围处理陌生消息、临时授权和黑名单;未准入的出站联系仅向本端 Owner 申请。
16
+ - 完善 Owner 名录授权范围、缓存同步、查询、搜索和未知字段保留;名录备注支持直接编辑文件。
17
+
18
+ ### 对话、任务与自动化
19
+
20
+ - 新增 `paactive` 模式,用于已激活 AUN Agent 与人类 Owner/Admin 的私聊主会话,通过独立上下文和可靠 activity 投递展示助理活动。
21
+ - AUN 消息增加受保护模型信息和模型切换通知;Slash 正常回执改用 notice,并新增 Slash 指令清单 Menu 查询。
22
+ - Trigger 成功结果以 `[[NOOP]]` 开头时静默处理,支持前导空白和流式拆分,同时保留原始执行记录。
23
+ - 完善 Fullaccess 提示范围、工具授权审计和只读命令解析;取消任务后停止后续模型请求,记忆整理失败时停止后续步骤并回报失败。
24
+ - 将网关请求超时、输入未消费和空成功协议故障纳入可恢复错误处理。
25
+
26
+ ### 渠道、安装与管理
27
+
28
+ - 隔离非 AUN 渠道依赖和实例故障,统一生命周期、绑定路由和状态查询,阻止断线或取消后的迟到回调。
29
+ - 修复 EC Web 脱管进程恢复、Provider 操作入口及受管服务运行信息校验;npm 元数据查询优先联网刷新。
30
+ - 完善 Windows 安装器中文编码、Node.js 安装后的 PATH 刷新和初始化检查,并明确计划任务权限不足时的自启动回退提示。
31
+ - 裸跑 `ec` 改为显示帮助;移除 `ec handoff` CLI 入口,跨话题协作继续使用话题与消息命令。
9
32
 
10
33
  ### AUN SDK
11
34
 
package/README.md CHANGED
@@ -371,6 +371,28 @@ evolcore/
371
371
 
372
372
  ## 斜杠命令
373
373
 
374
+ ### 程序获取指令清单
375
+
376
+ 发送 `/evolhelp`,沿用现有 JSON 响应:`{ commands, categories }`。清单仍按现有权限与聊天场景生成。
377
+ 部分指令条目新增 `common: true`,`categories` 首位新增 `常用`;每条指令的原 `category`、顺序和参数保持不变,不重复条目。
378
+
379
+ 客户端可按以下方式展示:
380
+
381
+ - 常用:`commands.filter(entry => entry.common === true)`。
382
+ - 普通:`commands.filter(entry => entry.common !== true)`;缺少 `common` 时视为普通。
383
+ - 全部:完整 `commands`。
384
+ - 原有分类:继续按 `entry.category` 筛选;`常用` 分类按 `common` 筛选。
385
+
386
+ 常用指令包括新建会话、状态、暂停/继续/停止、压缩、模型/推理强度,以及话题列表、更名和摘要。
387
+ 旧客户端可继续忽略 `common`。Evol App 也可通过只读 Menu 查询拉取清单:
388
+
389
+ ```json
390
+ {"type":"menu.query","id":"slash-1","name":"slash-commands","args":{"view":"commands","level":"common"}}
391
+ ```
392
+
393
+ `level` 可选 `common`、`normal`、`all`,省略默认 `common`;响应的 `data` 仍是 `{ commands, categories }`。
394
+ 直接向目标 Agent AID 查询;通过 Control AID 查询时必须增加顶层 `agent`。完整约定见 [Menu Protocol](kits/docs/evolcore/menu-protocol.md)。
395
+
374
396
  ### 用户级命令(所有用户可用)
375
397
 
376
398
  **会话管理**:
@@ -21,6 +21,7 @@ import { requestDangerousCommandPermission } from '../core/permission/approval-g
21
21
  import { checkBashDescription, checkDangerousCommand, checkReadonly, evaluateToolPreflight } from '../core/permission/tool-policy.js';
22
22
  import { sanitizeShellExecutionEnvironment } from '../core/permission/shell-environment.js';
23
23
  import { summarizeToolInput, summarizeToolInputForAudit } from '../utils/tool-summary.js';
24
+ import { renderToolTime } from './tool-time-context.js';
24
25
  import { encodePath } from '../utils/cross-platform.js';
25
26
  import { getPackageRoot, resolvePaths } from '../paths.js';
26
27
  import { resolveEffective } from '../config/config-manager.js';
@@ -2282,6 +2283,7 @@ export class AgentRunner {
2282
2283
  taskId: ctx?.taskId,
2283
2284
  matchedPath: matchedPath ?? (preflight?.behavior === 'deny' ? preflight.matchedPath : undefined),
2284
2285
  matchedRule: preflight?.behavior === 'deny' ? preflight.matchedRule : undefined,
2286
+ parsedSegments: preflight?.behavior === 'deny' ? preflight.parsedSegments : undefined,
2285
2287
  });
2286
2288
  try {
2287
2289
  await ctx?.recordExecutionAnomaly?.({
@@ -2515,6 +2517,18 @@ export class AgentRunner {
2515
2517
  }
2516
2518
  return {};
2517
2519
  };
2520
+ // PostToolBatch Hook - 工具调用时间感知
2521
+ // 一批工具全部 resolve、下一次模型请求之前恰好触发一次,对应模型唯一能"感知时间"的
2522
+ // 自然停顿点:串行调用时每轮工具后一次,并行调用时整批结束后一次。
2523
+ // 注入内容是独立上下文行,不污染工具输出本身。
2524
+ // 用 additionalContext 而不是 updatedToolOutput:后者会与其它改写钩子 last-write-wins
2525
+ // 冲突(并行钩子在原始输出上运行),也不该把时间混进工具结果里。
2526
+ const postToolBatchHook = async () => ({
2527
+ hookSpecificOutput: {
2528
+ hookEventName: 'PostToolBatch',
2529
+ additionalContext: renderToolTime(),
2530
+ },
2531
+ });
2518
2532
  // SDK-level canUseTool 回调:接入 PermissionGateway 的用户审批入口
2519
2533
  // 黑名单已在 PreToolUse hook 拦截,危险命令在此处进入审批流程
2520
2534
  const canUseToolCallback = async (toolName, input, options) => {
@@ -2770,8 +2784,9 @@ export class AgentRunner {
2770
2784
  const bootstrapWritePaths = modelOverride?.bootstrapAgentMdPath
2771
2785
  ? [path.resolve(modelOverride.bootstrapAgentMdPath)]
2772
2786
  : [];
2773
- const personalWritePaths = modelOverride?.personalMdPath
2774
- ? [path.resolve(modelOverride.personalMdPath)]
2787
+ // soul 目录整体可写:里面每个非空 .md 都会注入系统提示词,由 agent 自己维护。
2788
+ const personalWritePaths = modelOverride?.personalSoulDir
2789
+ ? [path.resolve(modelOverride.personalSoulDir), path.join(path.resolve(modelOverride.personalSoulDir), '**')]
2775
2790
  : [];
2776
2791
  const allowedWritePaths = [...new Set([...runtimeWritePaths, ...bootstrapWritePaths, ...personalWritePaths])];
2777
2792
  await assertClaudeSettingSourcesHaveLiteralSandboxPaths(projectPath, [...settingSources], managedSettings);
@@ -2848,6 +2863,7 @@ export class AgentRunner {
2848
2863
  hooks: {
2849
2864
  PreCompact: [{ matcher: '.*', hooks: [preCompactHook] }],
2850
2865
  PreToolUse: [{ matcher: '.*', hooks: [preToolUseHook] }],
2866
+ PostToolBatch: [{ matcher: '.*', hooks: [postToolBatchHook] }],
2851
2867
  PermissionDenied: [{ matcher: '.*', hooks: [permissionDeniedHook] }]
2852
2868
  },
2853
2869
  ...(enableSummaries ? { agentProgressSummaries: true } : {}),
@@ -2900,6 +2916,12 @@ export class AgentRunner {
2900
2916
  systemPrompt: {
2901
2917
  type: 'preset',
2902
2918
  preset: 'claude_code',
2919
+ // 每轮都按当前 append 重新下发:SDK 默认 snapshot=true 会把首次渲染的
2920
+ // 系统提示词写进会话记录,之后 resume 一律原样重发,忽略新 append——
2921
+ // ECK 重算出的 chatMode/permissionMode/角色等慢变参数因此在续接会话里
2922
+ // 永远停在建会话那一刻。关掉记录,让 ECK 成为唯一事实来源;vars 不变时
2923
+ // 渲染结果逐字相同,前缀依旧稳定,缓存不受影响。
2924
+ snapshot: false,
2903
2925
  ...(excludeDynamic ? { excludeDynamicSections: true } : {}),
2904
2926
  ...(systemPromptAppend ? { append: systemPromptAppend } : {})
2905
2927
  },
@@ -2953,6 +2975,8 @@ export class AgentRunner {
2953
2975
  systemPrompt: {
2954
2976
  type: 'preset',
2955
2977
  preset: 'claude_code',
2978
+ // 同上:不记录,每轮按最新 append 下发。
2979
+ snapshot: false,
2956
2980
  append: fullAppend
2957
2981
  }
2958
2982
  } : {}),
@@ -268,6 +268,18 @@ export class CodexAppServerClient {
268
268
  await this.request('thread/compact/start', { threadId });
269
269
  return true;
270
270
  }
271
+ /**
272
+ * 直接往 thread 的模型可见历史里追加 Responses API item。
273
+ *
274
+ * 用于工具调用后的时间感知:Codex 的 turn loop 由 app-server 内部驱动,客户端拿不到
275
+ * "下一批工具开始前"的钩子时机(PostToolUse 是独立进程,每次工具都要再起一个 node,
276
+ * 且需要管理员安装托管钩子);inject_items 走同一条 app-server 连接,成本极低。
277
+ */
278
+ async threadInjectItems(threadId, items) {
279
+ if (items.length === 0)
280
+ return;
281
+ await this.request('thread/inject_items', { threadId, items });
282
+ }
271
283
  async threadTurnsList(threadId, limit, cursor) {
272
284
  return this.request('thread/turns/list', {
273
285
  threadId,
@@ -15,6 +15,7 @@ import { logger } from '../utils/logger.js';
15
15
  import { resolveProviderService } from '../config/providers.js';
16
16
  import { catalogHash } from '../core/model/catalog-service.js';
17
17
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
18
+ import { renderToolTime } from './tool-time-context.js';
18
19
  import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
19
20
  import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
20
21
  import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
@@ -1464,7 +1465,7 @@ export class CodexRunner {
1464
1465
  }
1465
1466
  return Object.fromEntries([...paths].map(candidate => [candidate, 'write']));
1466
1467
  }
1467
- buildPermissionProfileConfig(sessionId, mode, projectPath, bootstrapAgentMdPath, personalMdPath) {
1468
+ buildPermissionProfileConfig(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir) {
1468
1469
  const profileName = this.permissionProfileName(sessionId);
1469
1470
  const managedTempDir = ensureSessionRuntimeDir(sessionId);
1470
1471
  const network = {
@@ -1494,8 +1495,9 @@ export class CodexRunner {
1494
1495
  ...(bootstrapAgentMdPath ? {
1495
1496
  [path.resolve(bootstrapAgentMdPath)]: mode === 'readonly' ? 'read' : 'write',
1496
1497
  } : {}),
1497
- ...(personalMdPath ? {
1498
- [path.resolve(personalMdPath)]: mode === 'readonly' ? 'read' : 'write',
1498
+ ...(personalSoulDir ? {
1499
+ [path.resolve(personalSoulDir)]: mode === 'readonly' ? 'read' : 'write',
1500
+ [path.join(path.resolve(personalSoulDir), '**')]: mode === 'readonly' ? 'read' : 'write',
1499
1501
  } : {}),
1500
1502
  ...relationAttachmentDenies,
1501
1503
  ...(mode !== 'readonly' && managedTempDir ? {
@@ -1521,7 +1523,7 @@ export class CodexRunner {
1521
1523
  },
1522
1524
  };
1523
1525
  }
1524
- buildExecutionSandboxOptions(sessionId, mode, projectPath, bootstrapAgentMdPath, personalMdPath, permissionContext = this.permissionContexts.get(sessionId) ?? {}) {
1526
+ buildExecutionSandboxOptions(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir, permissionContext = this.permissionContexts.get(sessionId) ?? {}) {
1525
1527
  const decision = resolvePhaseOneExecutionSandbox(mode, permissionContext.role);
1526
1528
  // 系统会话明确声明不要沙箱:Codex 的 permission profile 以项目目录为中心,
1527
1529
  // 而系统会话的读写边界($EVOLCORE_HOME 下的批次目录与记忆目录)与 cwd 无关,
@@ -1532,7 +1534,7 @@ export class CodexRunner {
1532
1534
  decision,
1533
1535
  permissionProfileConfig: sandboxOff
1534
1536
  ? undefined
1535
- : this.buildPermissionProfileConfig(sessionId, decision.permissionMode, projectPath, bootstrapAgentMdPath, personalMdPath),
1537
+ : this.buildPermissionProfileConfig(sessionId, decision.permissionMode, projectPath, bootstrapAgentMdPath, personalSoulDir),
1536
1538
  sandbox: sandboxOff ? 'danger-full-access' : undefined,
1537
1539
  sessionSandboxOff,
1538
1540
  };
@@ -1706,6 +1708,7 @@ export class CodexRunner {
1706
1708
  taskId: context?.taskId,
1707
1709
  matchedPath: details?.matchedPath,
1708
1710
  matchedRule: details?.matchedRule,
1711
+ parsedSegments: details?.parsedSegments,
1709
1712
  });
1710
1713
  try {
1711
1714
  context?.recordPreflightDenial?.({
@@ -1820,6 +1823,7 @@ export class CodexRunner {
1820
1823
  errorDetailCode: preflight.errorDetailCode,
1821
1824
  matchedPath: preflight.matchedPath,
1822
1825
  matchedRule: preflight.matchedRule,
1826
+ parsedSegments: preflight.parsedSegments,
1823
1827
  });
1824
1828
  return { ok: true, applicable: true, decision: 'deny', reason };
1825
1829
  }
@@ -2254,7 +2258,7 @@ export class CodexRunner {
2254
2258
  }
2255
2259
  this.chatModes.set(sessionId, callMode);
2256
2260
  const callApprovalPolicy = this.toApprovalPolicy(callMode);
2257
- const executionSandbox = this.buildExecutionSandboxOptions(sessionId, callMode, projectPath, modelOverride?.bootstrapAgentMdPath, modelOverride?.personalMdPath, undefined);
2261
+ const executionSandbox = this.buildExecutionSandboxOptions(sessionId, callMode, projectPath, modelOverride?.bootstrapAgentMdPath, modelOverride?.personalSoulDir, undefined);
2258
2262
  const appServer = this.getAppServerClient(callMode === 'fullaccess', modelOverride?.provider);
2259
2263
  this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
2260
2264
  const effectiveApprovalPolicy = callApprovalPolicy;
@@ -4761,7 +4765,7 @@ export class CodexRunner {
4761
4765
  }
4762
4766
  return 'allow';
4763
4767
  }
4764
- const recordBlockedOperation = async (policyCode, operationInput = toolInput, denialReason = 'policy denied', matchedPath, matchedRule) => {
4768
+ const recordBlockedOperation = async (policyCode, operationInput = toolInput, denialReason = 'policy denied', matchedPath, matchedRule, parsedSegments) => {
4765
4769
  const summary = summarizeToolInputForAudit(toolName, operationInput).slice(0, 512);
4766
4770
  auditToolPreflightDenial({
4767
4771
  toolName,
@@ -4782,6 +4786,7 @@ export class CodexRunner {
4782
4786
  taskId: permissionContext?.taskId,
4783
4787
  matchedPath,
4784
4788
  matchedRule,
4789
+ parsedSegments,
4785
4790
  });
4786
4791
  try {
4787
4792
  await permissionContext?.recordExecutionAnomaly?.({
@@ -4826,7 +4831,7 @@ export class CodexRunner {
4826
4831
  logger.warn(`[CodexRunner] tool preflight denied: session=${sessionKey} tool=${toolName} ` +
4827
4832
  `policy=${preflight.policyCode ?? 'unknown'} reason=${preflight.message ?? 'policy denied'}`);
4828
4833
  if (preflight.policyCode) {
4829
- await recordBlockedOperation(preflight.policyCode, toolInput, preflight.message ?? 'tool preflight denied', preflight.matchedPath, preflight.matchedRule);
4834
+ await recordBlockedOperation(preflight.policyCode, toolInput, preflight.message ?? 'tool preflight denied', preflight.matchedPath, preflight.matchedRule, preflight.parsedSegments);
4830
4835
  }
4831
4836
  return {
4832
4837
  decision: 'deny',
@@ -5684,9 +5689,45 @@ export class CodexRunner {
5684
5689
  return;
5685
5690
  if (event.type === 'tool_use') {
5686
5691
  state.openToolCalls.set(event.callId, event.name);
5692
+ // 批次起点:本批第一个工具开始执行时记一次,后续并行工具不覆盖。
5693
+ if (state.toolBatchStartedAt === undefined)
5694
+ state.toolBatchStartedAt = Date.now();
5687
5695
  }
5688
5696
  else if (event.type === 'tool_result') {
5689
5697
  state.openToolCalls.delete(event.callId);
5698
+ if (state.openToolCalls.size === 0)
5699
+ this.injectToolTime(state);
5700
+ }
5701
+ }
5702
+ /**
5703
+ * 工具批次结束后把时间行注入 Codex thread 的模型可见历史。
5704
+ *
5705
+ * Codex 的时间感知没有 Claude PostToolBatch 那种同步钩子:turn loop 在 app-server 内部,
5706
+ * 客户端只能在收到 item/completed、且本批 openToolCalls 清空后主动追加一条 item。
5707
+ * 用 Responses API 的 user message + input_text,模型下一次推理即可读到。
5708
+ *
5709
+ * 失败不影响主流程(注入是增值能力,不是正确性依赖),只记 debug 日志。
5710
+ */
5711
+ injectToolTime(state) {
5712
+ state.toolBatchStartedAt = undefined;
5713
+ if (!state.threadId)
5714
+ return;
5715
+ const items = [{
5716
+ type: 'message',
5717
+ role: 'user',
5718
+ content: [{ type: 'input_text', text: renderToolTime() }],
5719
+ }];
5720
+ try {
5721
+ const client = this.getAppServerClientForThread(state.threadId);
5722
+ state.toolTimeInjectedBatches = (state.toolTimeInjectedBatches ?? 0) + 1;
5723
+ void client.threadInjectItems(state.threadId, items).catch(error => {
5724
+ logger.debug(`[CodexRunner] tool time injection failed: thread=${state.threadId} `
5725
+ + `error=${error instanceof Error ? error.message : String(error)}`);
5726
+ });
5727
+ }
5728
+ catch (error) {
5729
+ logger.debug(`[CodexRunner] tool time injection skipped: thread=${state.threadId} `
5730
+ + `error=${error instanceof Error ? error.message : String(error)}`);
5690
5731
  }
5691
5732
  }
5692
5733
  *reconcileOpenAppServerToolCalls(state, turnId) {
@@ -15,6 +15,7 @@ import { checkBashDescription, checkDangerousCommand, checkReadonly, evaluateToo
15
15
  import { logger } from '../utils/logger.js';
16
16
  import { ErrorType } from '../utils/error-utils.js';
17
17
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
18
+ import { appendToolTimeToMessages } from './tool-time-context.js';
18
19
  import { auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
19
20
  import { resolveEcagentConfig, resolveRuntimeBaseagentModelSelection } from './baseagent.js';
20
21
  import { resolveProviderServiceForBaseagent } from '../config/providers.js';
@@ -247,9 +248,13 @@ function createOpenAiTransport(config) {
247
248
  let retryScheduled = false;
248
249
  const controller = new AbortController();
249
250
  const onAbort = () => controller.abort(options?.signal?.reason);
250
- options?.signal?.addEventListener('abort', onAbort, { once: true });
251
+ if (options?.signal?.aborted)
252
+ onAbort();
253
+ else
254
+ options?.signal?.addEventListener('abort', onAbort, { once: true });
251
255
  const timeout = setTimeout(() => controller.abort(new Error(`Gateway request timed out after ${config.timeoutMs}ms`)), config.timeoutMs);
252
256
  try {
257
+ controller.signal.throwIfAborted();
253
258
  let payload = {
254
259
  model: model.id,
255
260
  messages: openAiMessages(context),
@@ -266,6 +271,7 @@ function createOpenAiTransport(config) {
266
271
  const replacement = await options?.onPayload?.(payload, model);
267
272
  if (replacement !== undefined)
268
273
  payload = replacement;
274
+ controller.signal.throwIfAborted();
269
275
  response = await fetch(appendRequestPath(model.baseUrl, 'chat/completions', config.queryParams), {
270
276
  method: 'POST',
271
277
  headers: {
@@ -279,6 +285,7 @@ function createOpenAiTransport(config) {
279
285
  signal: controller.signal,
280
286
  });
281
287
  await options?.onResponse?.({ status: response.status, headers: responseHeaders(response.headers) }, model);
288
+ controller.signal.throwIfAborted();
282
289
  if (!response.ok) {
283
290
  const body = truncate(await response.text(), 2_000);
284
291
  const kind = response.status === 401 || response.status === 403 ? 'auth' : 'network';
@@ -486,14 +493,15 @@ function isWithin(root, candidate) {
486
493
  function isWithinAny(candidate, roots) {
487
494
  return roots.some(root => isWithin(path.resolve(root), candidate));
488
495
  }
489
- export function resolveEcagentToolPath(projectPath, candidate, forWrite = false, bootstrapAgentMdPath, fullaccess = false, personalMdPath, sessionGrants) {
496
+ export function resolveEcagentToolPath(projectPath, candidate, forWrite = false, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants) {
490
497
  const root = fs.realpathSync(projectPath);
491
498
  const resolved = path.resolve(root, candidate || '.');
492
499
  const allowedBootstrapFile = bootstrapAgentMdPath
493
500
  ? path.resolve(bootstrapAgentMdPath)
494
501
  : undefined;
495
- const allowedPersonalFile = personalMdPath ? path.resolve(personalMdPath) : undefined;
496
- const isManagedIdentityFile = resolved === allowedBootstrapFile || resolved === allowedPersonalFile;
502
+ const allowedSoulDir = personalSoulDir ? path.resolve(personalSoulDir) : undefined;
503
+ const isManagedIdentityFile = resolved === allowedBootstrapFile
504
+ || (!!allowedSoulDir && fs.existsSync(allowedSoulDir) && isWithin(allowedSoulDir, resolved));
497
505
  // 系统会话:模块声明的可读根整体放行,可写文件逐个精确匹配(不含目录)。
498
506
  // 声明之外、项目之外的路径仍然拒绝。声明里的路径可能在多个根之间借符号链接互串,
499
507
  // 所以放行前统一按真实路径复核,确认真实位置仍落在同一个被授予的边界内。
@@ -604,7 +612,7 @@ async function walkFiles(root, signal) {
604
612
  function textResult(text, details = {}) {
605
613
  return { content: [{ type: 'text', text: truncate(text) }], details };
606
614
  }
607
- function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullaccess = false, personalMdPath, sessionGrants) {
615
+ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants) {
608
616
  const read = {
609
617
  name: 'Read', label: 'Read', description: 'Read a UTF-8 text file from the project.',
610
618
  parameters: Type.Object({
@@ -613,7 +621,7 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
613
621
  limit: Type.Optional(Type.Number({ minimum: 1 })),
614
622
  }),
615
623
  async execute(_id, params, signal) {
616
- const file = resolveEcagentToolPath(projectPath, params.file_path, false, bootstrapAgentMdPath, fullaccess, personalMdPath, sessionGrants);
624
+ const file = resolveEcagentToolPath(projectPath, params.file_path, false, bootstrapAgentMdPath, fullaccess, personalSoulDir, sessionGrants);
617
625
  const stat = await fs.promises.stat(file);
618
626
  if (stat.size > MAX_READ_BYTES)
619
627
  throw new Error(`File exceeds ${MAX_READ_BYTES} byte read limit`);
@@ -679,7 +687,7 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
679
687
  name: 'Write', label: 'Write', description: 'Create or completely overwrite a project file.',
680
688
  parameters: Type.Object({ file_path: Type.String(), content: Type.String() }), executionMode: 'sequential',
681
689
  async execute(_id, params, signal) {
682
- const file = resolveEcagentToolPath(projectPath, params.file_path, true, bootstrapAgentMdPath, fullaccess, personalMdPath, sessionGrants);
690
+ const file = resolveEcagentToolPath(projectPath, params.file_path, true, bootstrapAgentMdPath, fullaccess, personalSoulDir, sessionGrants);
683
691
  await fs.promises.mkdir(path.dirname(file), { recursive: true });
684
692
  await fs.promises.writeFile(file, params.content, { encoding: 'utf8', signal });
685
693
  return textResult(`Wrote ${Buffer.byteLength(params.content)} bytes to ${path.relative(projectPath, file)}`, { file });
@@ -692,7 +700,7 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
692
700
  replace_all: Type.Optional(Type.Boolean()),
693
701
  }), executionMode: 'sequential',
694
702
  async execute(_id, params, signal) {
695
- const file = resolveEcagentToolPath(projectPath, params.file_path, true, bootstrapAgentMdPath, fullaccess, personalMdPath, sessionGrants);
703
+ const file = resolveEcagentToolPath(projectPath, params.file_path, true, bootstrapAgentMdPath, fullaccess, personalSoulDir, sessionGrants);
696
704
  const value = await fs.promises.readFile(file, { encoding: 'utf8', signal });
697
705
  if (!params.old_string)
698
706
  throw new Error('old_string must not be empty');
@@ -995,7 +1003,7 @@ export class EcagentRunner {
995
1003
  models,
996
1004
  model,
997
1005
  thinkingLevel: normalizeThinkingLevel(effort),
998
- tools: createTools(nodeEnv, request.projectPath, request.runtimeEnv, request.modelOverride?.bootstrapAgentMdPath, fullaccess, request.modelOverride?.personalMdPath, this.permissionContexts.get(request.sessionId)?.systemSessionGrants),
1006
+ tools: createTools(nodeEnv, request.projectPath, request.runtimeEnv, request.modelOverride?.bootstrapAgentMdPath, fullaccess, request.modelOverride?.personalSoulDir, this.permissionContexts.get(request.sessionId)?.systemSessionGrants),
999
1007
  systemPrompt: [DEFAULT_SYSTEM_PROMPT, request.systemPromptAppend].filter(Boolean).join('\n\n'),
1000
1008
  streamOptions: {
1001
1009
  timeoutMs: connection.timeoutMs,
@@ -1035,6 +1043,13 @@ export class EcagentRunner {
1035
1043
  });
1036
1044
  return result;
1037
1045
  });
1046
+ // 工具调用时间感知:ecagent 的 agent-loop 在每次模型请求前调用 transformContext,
1047
+ // 此时本批工具结果已全部进入消息列表——这就是与 Claude PostToolBatch 对齐的停顿点。
1048
+ // 末尾不是 toolResult(首轮 / 纯文本轮)时返回 undefined,不改写消息。
1049
+ harness.on('context', (event) => {
1050
+ const messages = appendToolTimeToMessages(event.messages);
1051
+ return messages ? { messages } : undefined;
1052
+ });
1038
1053
  let inputAccepted = false;
1039
1054
  const unsubscribe = harness.subscribe(event => {
1040
1055
  if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
@@ -1358,6 +1373,7 @@ export class EcagentRunner {
1358
1373
  callId,
1359
1374
  matchedPath: details.matchedPath,
1360
1375
  matchedRule: details.matchedRule,
1376
+ parsedSegments: details.parsedSegments,
1361
1377
  });
1362
1378
  try {
1363
1379
  await permissionContext?.recordExecutionAnomaly?.({
@@ -1422,6 +1438,7 @@ export class EcagentRunner {
1422
1438
  if (preflight.policyCode) {
1423
1439
  await recordBlockedOperation(preflight.policyCode, input, {
1424
1440
  reason: preflight.message, matchedPath: preflight.matchedPath, matchedRule: preflight.matchedRule,
1441
+ parsedSegments: preflight.parsedSegments,
1425
1442
  });
1426
1443
  }
1427
1444
  return { block: true, reason: preflight.message, details: { policyCode: preflight.policyCode } };
@@ -142,7 +142,6 @@ const GEMINI_EC_COMMAND_PATTERNS = [
142
142
  // quoted arguments.
143
143
  String.raw `\x00"command":"[ ]*ec[ ]+(?:[^"\x00;&|$()<>\x60\r\n\\]|\\(?:\\|"))*"\x00`,
144
144
  ];
145
- const GEMINI_BOOTSTRAP_PERSONA_COMMAND_PATTERN = String.raw `^\{\x00"command":"[ ]*ec[ ]+agent[ ]+persona(?:[ ]+show|[ ]+--(?:text|file)[ ]+(?:[^"\x00;&|$()<>\x60\r\n\\]|\\(?:\\|"))+)[ ]*"\x00\}$`;
146
145
  // A single-quoted shell argument can safely carry multiline Markdown, backticks,
147
146
  // dollar signs and semicolons. Outside that argument only --format json is legal.
148
147
  const GEMINI_WELCOME_ESCAPED_QUOTE = escapeGeminiArgsRegex(JSON.stringify("'\\''").slice(1, -1));
@@ -207,6 +206,11 @@ function geminiExactShellCommandPattern(command) {
207
206
  function geminiManagedIdentityPathPattern(filePath) {
208
207
  return geminiJsonFieldEqualsPattern(['file_path'], path.resolve(filePath));
209
208
  }
209
+ /** soul 目录下任意层级的 .md 文件(含目录本身之外的实际文件路径)。 */
210
+ function geminiManagedIdentityDirPattern(dirPath) {
211
+ const prefix = escapeGeminiArgsRegex(JSON.stringify(path.resolve(dirPath))).slice(0, -1);
212
+ return `\\x00"file_path":${prefix}[\\\\/][^"]*"\x00`;
213
+ }
210
214
  function appendGeminiPolicyRule(lines, toolName, decision, priority, argsPattern) {
211
215
  lines.push('[[rule]]');
212
216
  lines.push(`toolName = ${Array.isArray(toolName) ? JSON.stringify(toolName) : JSON.stringify(toolName)}`);
@@ -215,7 +219,7 @@ function appendGeminiPolicyRule(lines, toolName, decision, priority, argsPattern
215
219
  lines.push(`decision = "${decision}"`);
216
220
  lines.push(`priority = ${priority}`, '');
217
221
  }
218
- export function buildGeminiAdminPolicy(profile, bootstrapAgentMdPath, personalMdPath, scope = {}) {
222
+ export function buildGeminiAdminPolicy(profile, bootstrapAgentMdPath, personalSoulDir, scope = {}) {
219
223
  const lines = [];
220
224
  const hClassPatterns = geminiHClassPatterns(scope);
221
225
  if (bootstrapAgentMdPath) {
@@ -234,10 +238,9 @@ export function buildGeminiAdminPolicy(profile, bootstrapAgentMdPath, personalMd
234
238
  appendGeminiPolicyRule(lines, GEMINI_BOOTSTRAP_FILE_TOOLS, 'allow', 990, writePathPattern);
235
239
  appendGeminiPolicyRule(lines, 'run_shell_command', 'allow', 990, geminiExactShellCommandPattern(`ec aid agentmd put ${bootstrap.aid}`));
236
240
  appendGeminiPolicyRule(lines, 'run_shell_command', 'allow', 990, geminiExactShellCommandPattern(`ec agent ready ${bootstrap.aid}`));
237
- appendGeminiPolicyRule(lines, 'run_shell_command', 'allow', 990, GEMINI_BOOTSTRAP_PERSONA_COMMAND_PATTERN);
238
241
  appendGeminiPolicyRule(lines, 'run_shell_command', 'allow', 990, GEMINI_BOOTSTRAP_WELCOME_COMMAND_PATTERN);
239
- if (personalMdPath) {
240
- const personalPathPattern = geminiManagedIdentityPathPattern(personalMdPath);
242
+ if (personalSoulDir) {
243
+ const personalPathPattern = geminiManagedIdentityDirPattern(personalSoulDir);
241
244
  appendGeminiPolicyRule(lines, 'read_file', 'allow', 989, personalPathPattern);
242
245
  appendGeminiPolicyRule(lines, GEMINI_BOOTSTRAP_FILE_TOOLS, 'allow', 989, personalPathPattern);
243
246
  }
@@ -260,8 +263,8 @@ export function buildGeminiAdminPolicy(profile, bootstrapAgentMdPath, personalMd
260
263
  for (const pattern of GEMINI_L_CLASS_PATTERNS) {
261
264
  appendGeminiPolicyRule(lines, GEMINI_L_CLASS_WRITE_TOOLS, 'deny', 997, pattern);
262
265
  }
263
- if (personalMdPath) {
264
- const personalPathPattern = geminiManagedIdentityPathPattern(personalMdPath);
266
+ if (personalSoulDir) {
267
+ const personalPathPattern = geminiManagedIdentityDirPattern(personalSoulDir);
265
268
  appendGeminiPolicyRule(lines, 'read_file', 'allow', 989, personalPathPattern);
266
269
  appendGeminiPolicyRule(lines, GEMINI_BOOTSTRAP_FILE_TOOLS, 'allow', 989, personalPathPattern);
267
270
  }
@@ -441,8 +444,8 @@ export class GeminiRunner {
441
444
  const bootstrapAgentMdPath = modelOverride?.bootstrapAgentMdPath
442
445
  ? normalizeGeminiBootstrapAgentMdPath(modelOverride.bootstrapAgentMdPath).filePath
443
446
  : undefined;
444
- const personalMdPath = modelOverride?.personalMdPath
445
- ? path.resolve(modelOverride.personalMdPath)
447
+ const personalSoulDir = modelOverride?.personalSoulDir
448
+ ? path.resolve(modelOverride.personalSoulDir)
446
449
  : undefined;
447
450
  const permissionProfile = resolveGeminiPermissionProfile(requestedPermissionMode, !!bootstrapAgentMdPath);
448
451
  const callModel = modelOverride?.model || this.model;
@@ -463,7 +466,7 @@ export class GeminiRunner {
463
466
  ...(runtimeDir ? [runtimeDir] : []),
464
467
  ...(runtimeLockDir ? [runtimeLockDir] : []),
465
468
  ...(bootstrapAgentMdPath ? [bootstrapAgentMdPath] : []),
466
- ...(personalMdPath ? [personalMdPath] : []),
469
+ ...(personalSoulDir ? [personalSoulDir] : []),
467
470
  ],
468
471
  });
469
472
  if (executionPermissionMode !== 'fullaccess' && !sandboxProbe && workspaceContainsHClassPaths(projectPath, resolveRoot(), { selfAid })) {
@@ -492,7 +495,7 @@ export class GeminiRunner {
492
495
  }
493
496
  else {
494
497
  const policyPath = path.join(managedTmpDir, `evolcore-gemini-permission-${crypto.randomUUID()}.toml`);
495
- fs.writeFileSync(policyPath, buildGeminiAdminPolicy(permissionProfile, bootstrapAgentMdPath, personalMdPath, { root: resolveRoot(), selfAid }), { mode: 0o600, flag: 'wx' });
498
+ fs.writeFileSync(policyPath, buildGeminiAdminPolicy(permissionProfile, bootstrapAgentMdPath, personalSoulDir, { root: resolveRoot(), selfAid }), { mode: 0o600, flag: 'wx' });
496
499
  tempFiles.push(policyPath);
497
500
  args.push(...buildGeminiPermissionArgs(permissionProfile, policyPath, !!sandboxProbe));
498
501
  }
@@ -534,7 +537,7 @@ export class GeminiRunner {
534
537
  ...(runtimeDir ? [runtimeDir] : []),
535
538
  ...(runtimeLockDir ? [runtimeLockDir] : []),
536
539
  ...(bootstrapAgentMdPath ? [bootstrapAgentMdPath] : []),
537
- ...(personalMdPath ? [personalMdPath] : []),
540
+ ...(personalSoulDir ? [personalSoulDir] : []),
538
541
  ],
539
542
  readonlyPaths: tempFiles,
540
543
  });
@@ -0,0 +1,55 @@
1
+ // Tool-call time awareness: stamp the wall clock into the conversation at every
2
+ // natural tool-call pause point.
3
+ //
4
+ // 为什么需要:入站消息渲染层(eck/message-renderer.ts)只在消息到达时打时间戳,
5
+ // 工具调用期间模型完全不知道过去了多久。连续调用十几分钟的工具时,模型无法感知
6
+ // 时间推移,也就无从判断"该向 owner 报一声进度了"。
7
+ //
8
+ // 各 base agent 的注入通道不同,但渲染文本统一走这里,保证三个基座口径一致:
9
+ // - Claude Code:PostToolBatch hook 的 additionalContext(每批一次)
10
+ // - ecagent:harness 'context' hook,在下次请求前给末尾 toolResult 追加一段 text
11
+ // - Codex:app-server 无 PostToolUse hook,走 turn/steer 的 additionalContext
12
+ //
13
+ // 批次语义(与 PostToolBatch 定义一致):模型一次请求里可能并行发出多个 tool_use,
14
+ // 全部 resolve 后才是一次停顿。串行调用时每轮都会停顿一次,因此"每批一次"在串行
15
+ // 场景下等价于"每次工具一次"。
16
+ //
17
+ // 只注入时间点、不注入耗时:模型看到相邻停顿点的时间戳即可自行推算间隔,首条用户
18
+ // 消息也带时间戳,起点同样可得。省掉耗时字段后单行长度压到 20 字符以内。
19
+ /**
20
+ * 形如 "[⏱ 11-03 01:02:21]":本机时间,去掉年份与时区偏移,只为让模型感知"现在几点"。
21
+ * timeZone 仅测试用;生产走本机时区(不传即取进程默认)。
22
+ */
23
+ export function renderToolTime(now = Date.now(), timeZone) {
24
+ const parts = new Intl.DateTimeFormat('en-US', {
25
+ ...(timeZone ? { timeZone } : {}),
26
+ month: '2-digit',
27
+ day: '2-digit',
28
+ hour: '2-digit',
29
+ minute: '2-digit',
30
+ second: '2-digit',
31
+ hour12: false,
32
+ }).formatToParts(new Date(now));
33
+ const get = (type) => parts.find(part => part.type === type)?.value ?? '';
34
+ const hour = get('hour') === '24' ? '00' : get('hour'); // hour12:false may yield "24" at midnight
35
+ return `[⏱ ${get('month')}-${get('day')} ${hour}:${get('minute')}:${get('second')}]`;
36
+ }
37
+ /**
38
+ * ecagent 专用:在模型请求前给末尾的 toolResult 追加一段时间文本。
39
+ *
40
+ * 返回 null 表示不注入(末尾不是工具结果,即本轮还没跑过工具)。调用方据此跳过改写。
41
+ * 原消息不改动——它已进会话持久化,改写会污染历史;这里返回一个浅拷贝。
42
+ */
43
+ export function appendToolTimeToMessages(messages, now = Date.now()) {
44
+ const last = messages[messages.length - 1];
45
+ if (!last || last.role !== 'toolResult')
46
+ return null;
47
+ // toolResult 的 content 一定是 (TextContent | ImageContent)[];这里只按结构访问,
48
+ // 避免本模块反向依赖 ecagent 的运行时类型。
49
+ const content = last.content;
50
+ const stamped = {
51
+ ...last,
52
+ content: [...content, { type: 'text', text: renderToolTime(now) }],
53
+ };
54
+ return [...messages.slice(0, -1), stamped];
55
+ }
@@ -126,7 +126,7 @@ export class ManagedMenuClient {
126
126
  const sent = this.send({
127
127
  to: options.targetAid, payload: request, encrypt: true,
128
128
  ttl: MENU_MESSAGE_TTL_SECONDS, protected_headers: headers,
129
- })
129
+ }, options.beforeSend)
130
130
  .then(result => {
131
131
  if (!(result?.message_id ?? result?.message?.message_id))
132
132
  throw new MenuClientError('SEND_FAILED', 'message.send returned no message_id');
@@ -0,0 +1,17 @@
1
+ /** Per-message authenticated metadata. Never read the Agent's mutable model here:
2
+ * an in-flight turn must keep its model even after a configuration change. */
3
+ export function aunProtectedHeaders(context) {
4
+ const headers = {};
5
+ const raw = context?.metadata?.protectedHeaders;
6
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
7
+ for (const [key, value] of Object.entries(raw)) {
8
+ const name = key.trim().toLowerCase();
9
+ if (/^[a-z0-9_-]+$/.test(name) && typeof value === 'string')
10
+ headers[name] = value;
11
+ }
12
+ }
13
+ const model = context?.model?.trim();
14
+ if (model)
15
+ headers.model = model;
16
+ return Object.keys(headers).length > 0 ? headers : undefined;
17
+ }
@@ -173,6 +173,9 @@ async function daemonMsgSendResult(args, payload, runtimeContext, daemonResult)
173
173
  target_session_id: daemonResult.target_session_id,
174
174
  request_id: daemonResult.request_id,
175
175
  request_state: daemonResult.request_state,
176
+ sent: daemonResult.sent,
177
+ retryable: daemonResult.retryable,
178
+ contact_request: daemonResult.contact_request,
176
179
  };
177
180
  }
178
181
  const completedRequest = args.returnPolicy === 'required' && !!daemonResult.request_id