evolcore 0.0.42-test.0 → 0.0.43-test.0

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 (187) hide show
  1. package/CHANGELOG.md +31 -2
  2. package/bin/ec-safe-output.js +4 -1
  3. package/dist/ability/application-service.js +882 -0
  4. package/dist/ability/authorization.js +70 -0
  5. package/dist/ability/command-contract.js +105 -0
  6. package/dist/ability/daemon.js +137 -0
  7. package/dist/ability/development.js +450 -0
  8. package/dist/ability/environment.js +75 -0
  9. package/dist/ability/interop-v1.js +547 -0
  10. package/dist/ability/management.js +79 -0
  11. package/dist/ability/package.js +264 -0
  12. package/dist/ability/provider.js +73 -0
  13. package/dist/ability/publication.js +107 -0
  14. package/dist/ability/resources.js +106 -0
  15. package/dist/ability/runtime.js +212 -0
  16. package/dist/ability/secrets.js +47 -0
  17. package/dist/ability/store.js +112 -0
  18. package/dist/ability/toolchain.js +69 -0
  19. package/dist/ability/types.js +14 -0
  20. package/dist/ability/versions.js +32 -0
  21. package/dist/agents/baseagent.js +2 -2
  22. package/dist/agents/claude-runner.js +4 -0
  23. package/dist/agents/codex-runner.js +81 -17
  24. package/dist/agents/ecagent-plugin-lazy.js +41 -0
  25. package/dist/agents/ecagent-runner.js +18 -11
  26. package/dist/aun/ability-device-routing.js +12 -1
  27. package/dist/aun/aid/agentmd.js +2 -2
  28. package/dist/aun/aid/identity.js +45 -0
  29. package/dist/aun/aid/index.js +1 -0
  30. package/dist/aun/aid/managed-operation.js +73 -2
  31. package/dist/channels/aun.js +64 -18
  32. package/dist/channels/builtin-plugins.js +14 -0
  33. package/dist/channels/dingtalk.js +78 -26
  34. package/dist/channels/feishu.js +89 -14
  35. package/dist/channels/qqbot.js +84 -19
  36. package/dist/channels/wechat.js +77 -19
  37. package/dist/channels/wecom.js +67 -22
  38. package/dist/cli/ability-command.js +92 -0
  39. package/dist/cli/aun-commands.js +124 -85
  40. package/dist/cli/daemon-commands.js +37 -85
  41. package/dist/cli/index.js +14 -0
  42. package/dist/cli/init.js +11 -13
  43. package/dist/cli/managed-command-guard.js +6 -0
  44. package/dist/cli/model.js +101 -104
  45. package/dist/cli/provider-command.js +6 -4
  46. package/dist/cli/restart-monitor.js +52 -11
  47. package/dist/cli/upgrade-command.js +102 -0
  48. package/dist/cli/version.js +1 -1
  49. package/dist/config/access-policy.js +4 -2
  50. package/dist/config/builtin-roles.js +1 -0
  51. package/dist/config/config-field-policy.js +4 -0
  52. package/dist/config/config-manager.js +7 -0
  53. package/dist/config/provider-ipc-service.js +10 -0
  54. package/dist/config/providers-config.js +12 -3
  55. package/dist/config/providers-management.js +45 -9
  56. package/dist/config/schema-migration.js +40 -22
  57. package/dist/contracts/ecweb-service-protocol.js +2 -1
  58. package/dist/core/auth/agent-delegation.js +21 -5
  59. package/dist/core/auth/auth-gateway.js +31 -9
  60. package/dist/core/auth/authorization-audit.js +52 -4
  61. package/dist/core/auth/delegation-authorization.js +140 -4
  62. package/dist/core/auth/operation-authorizer.js +114 -13
  63. package/dist/core/auth/operation-catalog.js +118 -4
  64. package/dist/core/baseagent-loader.js +14 -1
  65. package/dist/core/channel-loader.js +47 -9
  66. package/dist/core/channel-runtime.js +1 -1
  67. package/dist/core/command/agent-storage-menu.js +1 -1
  68. package/dist/core/command/cli-intent-parser.js +26 -13
  69. package/dist/core/command/command-handler.js +232 -76
  70. package/dist/core/command/connect-menu.js +10 -4
  71. package/dist/core/command/daemon-diagnostics.js +3 -3
  72. package/dist/core/command/data-root-resolver.js +2 -3
  73. package/dist/core/command/menu-catalog.js +10 -3
  74. package/dist/core/command/menu-handler.js +321 -46
  75. package/dist/core/command/menu-protocol.js +53 -7
  76. package/dist/core/command/pa-workspace-calendar.js +1 -2
  77. package/dist/core/command/pa-workspace-items.js +486 -0
  78. package/dist/core/command/pa-workspace-store.js +10 -1
  79. package/dist/core/command/slash-gate.js +2 -2
  80. package/dist/core/command/slash-handler.js +67 -25
  81. package/dist/core/contact-bind-registry.js +27 -0
  82. package/dist/core/daemon-control.js +3 -3
  83. package/dist/core/daemon-lifecycle.js +2 -1
  84. package/dist/core/event-bus.js +9 -2
  85. package/dist/core/handoff/ipc-registration.js +1 -0
  86. package/dist/core/host-snapshot.js +1 -2
  87. package/dist/core/initialization/service.js +32 -11
  88. package/dist/core/ipc-registration.js +18 -5
  89. package/dist/core/memory/consolidation-context.js +2 -2
  90. package/dist/core/message/aun-request-registry.js +99 -18
  91. package/dist/core/message/im-renderer.js +16 -11
  92. package/dist/core/message/message-admission.js +25 -20
  93. package/dist/core/message/message-bridge.js +21 -47
  94. package/dist/core/message/message-queue.js +3 -0
  95. package/dist/core/message/response-engine.js +7 -5
  96. package/dist/core/model/catalog-service.js +1 -1
  97. package/dist/core/permission/ec-command-parser.js +41 -9
  98. package/dist/core/permission/permission-result.js +1 -0
  99. package/dist/core/permission/protected-paths.js +25 -14
  100. package/dist/core/permission/tool-policy.js +108 -107
  101. package/dist/core/plugin-lifecycle.js +133 -0
  102. package/dist/core/runner-reload-transaction.js +4 -1
  103. package/dist/core/system-session/memory.js +16 -3
  104. package/dist/core/task/task-activity-store.js +50 -0
  105. package/dist/core/task/task-image-resources.js +140 -0
  106. package/dist/core/thread/ipc-operation.js +1 -1
  107. package/dist/core/thread/thread-service.js +0 -1
  108. package/dist/directory/canonical-digest.js +5 -3
  109. package/dist/directory/owner-directory-admission.js +22 -2
  110. package/dist/directory/owner-directory-cache.js +394 -60
  111. package/dist/directory/owner-directory-markdown.js +29 -2
  112. package/dist/directory/owner-directory-scope.js +35 -16
  113. package/dist/ecweb/basic-settings-service.js +4 -1
  114. package/dist/ecweb/pairing.js +41 -0
  115. package/dist/ecweb/providers-service.js +8 -1
  116. package/dist/{utils/ecweb-utils.js → ecweb/runtime/launch.js} +3 -27
  117. package/dist/ecweb/runtime/lifecycle.js +184 -0
  118. package/dist/{utils/ecweb-supervisor.js → ecweb/runtime/supervisor.js} +32 -27
  119. package/dist/index.js +34 -25
  120. package/dist/ipc.js +124 -7
  121. package/dist/response-system/engines/v1/proactive-flow.js +1 -1
  122. package/dist/trigger/authorization.js +2 -2
  123. package/dist/utils/atomic-write.js +24 -0
  124. package/dist/utils/avatar-upload.js +3 -1
  125. package/dist/utils/cross-platform.js +31 -2
  126. package/dist/utils/host-info.js +36 -0
  127. package/dist/utils/instance-registry.js +38 -11
  128. package/dist/utils/logger.js +9 -0
  129. package/dist/utils/{process-tree-stats.js → process-tree.js} +29 -0
  130. package/dist/utils/tool-summary.js +9 -1
  131. package/dist/utils/upgrade-jobs.js +96 -15
  132. package/dist/utils/windows-autostart.js +1 -1
  133. package/ecagent/README.md +19 -0
  134. package/ecagent/dist/harness/agent-harness.js +9 -0
  135. package/ecagent/dist/harness/env/nodejs.js +71 -11
  136. package/ecagent/dist/harness/env/windows-shell.d.ts +7 -0
  137. package/ecagent/dist/harness/env/windows-shell.js +132 -0
  138. package/kits/docs/aun/ABILITY_CALLING.md +38 -9
  139. package/kits/docs/evolcore/INDEX.md +5 -1
  140. package/kits/docs/evolcore/ability.md +181 -0
  141. package/kits/docs/evolcore/aid.md +20 -0
  142. package/kits/docs/evolcore/config.md +10 -6
  143. package/kits/docs/evolcore/menu-protocol.md +40 -1
  144. package/kits/docs/evolcore/provider.md +2 -2
  145. package/kits/docs/evolcore/tool-authorization.md +270 -0
  146. package/kits/runtime/ability-job.ps1 +41 -0
  147. package/kits/runtime/ability-runner.mjs +67 -0
  148. package/kits/runtime/ability-secret.ps1 +59 -0
  149. package/kits/runtime/ability-templates/go/main.go +59 -0
  150. package/kits/runtime/ability-templates/java/Json.java +67 -0
  151. package/kits/runtime/ability-templates/java/Runner.java +42 -0
  152. package/kits/runtime/ability-templates/python/runner.py +48 -0
  153. package/kits/runtime/ability-templates/rust/json.rs +87 -0
  154. package/kits/runtime/ability-templates/rust/runner.rs +35 -0
  155. package/kits/schemas/_meta.json +12 -1
  156. package/kits/schemas/ability-plugin.schema.1.json +107 -0
  157. package/kits/schemas/ability-project.schema.1.json +31 -0
  158. package/kits/schemas/agent-config.schema.16.json +20 -0
  159. package/kits/schemas/agent-config.schema.17.json +20 -0
  160. package/kits/schemas/agent-config.schema.18.json +917 -0
  161. package/kits/skills/.switches.json +4 -0
  162. package/kits/skills/aid-ability/SKILL.md +5 -4
  163. package/kits/skills/ec-ability/SKILL.md +67 -0
  164. package/kits/skills/ec-ability/references/contract-checklist.md +37 -0
  165. package/kits/skills/ec-ability/references/development.md +104 -0
  166. package/kits/skills/ec-ability/references/management.md +117 -0
  167. package/kits/skills/ec-ability/references/recovery.md +27 -0
  168. package/kits/skills/ec-ability/references/runtime-protocol.md +109 -0
  169. package/kits/skills/ec-ability/references/workflows.md +15 -0
  170. package/kits/skills/ec-service-proxy/SKILL.md +12 -0
  171. package/kits/skills/personal-assistant/SKILL.md +240 -6
  172. package/kits/skills/personal-assistant/references/02-bootstrap.md +78 -4
  173. package/kits/skills/personal-assistant/scripts/clean.mjs +397 -0
  174. package/kits/skills/personal-assistant/scripts/init.mjs +113 -25
  175. package/kits/skills/personal-assistant/scripts/lock.mjs +189 -0
  176. package/kits/skills/personal-assistant/scripts/migrate.mjs +35 -10
  177. package/kits/skills/personal-assistant/scripts/verify.mjs +2 -1
  178. package/kits/skills/personal-assistant/templates/persona-section.md +54 -0
  179. package/kits/skills/personal-assistant/triggers/ingest-daily.json +1 -1
  180. package/kits/templates/memory-consolidation/notes.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +2 -1
  182. package/kits/templates/system-fragments/commands.md +1 -0
  183. package/package.json +4 -2
  184. package/dist/core/command/data-root-error.js +0 -10
  185. package/dist/utils/machine-info.js +0 -46
  186. package/dist/utils/process-tree-worker.js +0 -31
  187. package/dist/utils/windows-output.js +0 -36
@@ -0,0 +1,133 @@
1
+ export class PluginHandle {
2
+ owner;
3
+ teardown;
4
+ resources = new Map();
5
+ pending = new Map();
6
+ intervals = new Map();
7
+ timeouts = new Map();
8
+ controller = new AbortController();
9
+ disposal;
10
+ currentState = 'active';
11
+ constructor(owner, teardown) {
12
+ this.owner = owner;
13
+ this.teardown = teardown;
14
+ }
15
+ get state() { return this.currentState; }
16
+ get signal() { return this.controller.signal; }
17
+ get resourceCount() { return this.resources.size + this.pending.size; }
18
+ assertActive() {
19
+ if (this.currentState !== 'active')
20
+ throw new Error(`Plugin ${this.owner} is ${this.currentState}`);
21
+ }
22
+ defer(disposer, label = 'resource') {
23
+ this.assertActive();
24
+ let disposal;
25
+ const release = () => {
26
+ if (disposal)
27
+ return disposal;
28
+ this.resources.delete(release);
29
+ let resolve;
30
+ let reject;
31
+ disposal = new Promise((done, fail) => { resolve = done; reject = fail; });
32
+ const pending = disposal;
33
+ this.pending.set(pending, label);
34
+ pending.then(() => this.pending.delete(pending), () => this.pending.delete(pending));
35
+ try {
36
+ Promise.resolve(disposer()).then(resolve, reject);
37
+ }
38
+ catch (error) {
39
+ reject(error);
40
+ }
41
+ return disposal;
42
+ };
43
+ this.resources.set(release, label);
44
+ return release;
45
+ }
46
+ subscribe(eventBus, eventType, handler) {
47
+ return this.listen(eventBus, eventType, handler);
48
+ }
49
+ listen(emitter, event, listener) {
50
+ this.assertActive();
51
+ const ownedListener = (...args) => {
52
+ if (this.currentState === 'active')
53
+ listener(...args);
54
+ };
55
+ emitter.on(event, ownedListener);
56
+ return this.defer(() => { emitter.off(event, ownedListener); }, `event:${String(event)}`);
57
+ }
58
+ setInterval(callback, delayMs) {
59
+ this.assertActive();
60
+ const timer = setInterval(() => {
61
+ if (this.currentState === 'active')
62
+ callback();
63
+ }, delayMs);
64
+ const release = this.defer(() => {
65
+ globalThis.clearInterval(timer);
66
+ this.intervals.delete(timer);
67
+ }, 'interval');
68
+ this.intervals.set(timer, release);
69
+ return timer;
70
+ }
71
+ clearInterval(timer) {
72
+ const release = this.intervals.get(timer);
73
+ if (release)
74
+ return Promise.resolve(release());
75
+ globalThis.clearInterval(timer);
76
+ return Promise.resolve();
77
+ }
78
+ clearTimeout(timer) {
79
+ const release = this.timeouts.get(timer);
80
+ if (release)
81
+ return Promise.resolve(release());
82
+ globalThis.clearTimeout(timer);
83
+ return Promise.resolve();
84
+ }
85
+ setTimeout(callback, delayMs) {
86
+ this.assertActive();
87
+ const timer = setTimeout(() => {
88
+ this.resources.delete(release);
89
+ this.timeouts.delete(timer);
90
+ if (this.currentState === 'active')
91
+ callback();
92
+ }, delayMs);
93
+ const release = this.defer(() => {
94
+ globalThis.clearTimeout(timer);
95
+ this.timeouts.delete(timer);
96
+ }, 'timeout');
97
+ this.timeouts.set(timer, release);
98
+ return timer;
99
+ }
100
+ dispose() {
101
+ if (this.disposal)
102
+ return this.disposal;
103
+ this.currentState = 'disposing';
104
+ const resources = [...this.resources].reverse();
105
+ const pending = [...this.pending];
106
+ this.disposal = Promise.resolve().then(async () => {
107
+ const errors = [];
108
+ const cleanup = async (operation, label) => {
109
+ try {
110
+ await (typeof operation === 'function' ? operation() : operation);
111
+ }
112
+ catch (cause) {
113
+ errors.push(new Error(`Plugin ${this.owner}: ${label}`, { cause }));
114
+ }
115
+ };
116
+ await Promise.all([
117
+ ...resources.map(([release, label]) => cleanup(release, label)),
118
+ ...pending.map(([operation, label]) => cleanup(operation, label)),
119
+ ]);
120
+ try {
121
+ await this.teardown?.();
122
+ }
123
+ catch (cause) {
124
+ errors.push(new Error(`Plugin ${this.owner}: teardown`, { cause }));
125
+ }
126
+ this.currentState = 'disposed';
127
+ if (errors.length)
128
+ throw new AggregateError(errors, `Plugin ${this.owner} cleanup failed`);
129
+ });
130
+ this.controller.abort();
131
+ return this.disposal;
132
+ }
133
+ }
@@ -1,7 +1,10 @@
1
1
  export async function disposeAgentInstances(instances, onError) {
2
2
  await Promise.allSettled(instances.map(async (instance) => {
3
3
  try {
4
- await instance.agent.dispose?.();
4
+ if (instance.lifecycle)
5
+ await instance.lifecycle.dispose();
6
+ else
7
+ await instance.agent.dispose?.();
5
8
  }
6
9
  catch (error) {
7
10
  onError?.(instance, error);
@@ -6,6 +6,7 @@
6
6
  *
7
7
  * B = 批次目录 R = relations/<peer>/memory A = personal/memory
8
8
  * O = memory/owner/<owner> M = 本对话 messages.jsonl(单文件)
9
+ * T = 当前会话 managed TMPDIR(只读)
9
10
  *
10
11
  * notes B, R/processing, R/consolidated, R/MEMORY.md, M
11
12
  * generalize B, A/consolidated, A/MEMORY.md, R/consolidated, M
@@ -29,7 +30,7 @@ const MEMORY_MANIFEST = 'eck_manifest.memory.json';
29
30
  const ALLOWED_MEMORY_SUBCOMMANDS = new Set(['create', 'update', 'archive']);
30
31
  const BASH_COMMAND_RULE = 'Bash 只允许两类命令:单条 `ec memory create|update|archive`(不能与其他命令拼接);'
31
32
  + '或路径落在可读根内、可证明只读的查询(如 ls / cat / grep),多条查询可用 `&&` 或 `;` 连接,最多 8 段。'
32
- + '有文件工具时用 Read / Glob / Grep;只有 Bash/Shell 时可用 cat,明确的 pwsh/powershell -NoProfile -Command 包装内只接受单条 Get-Content -LiteralPath <绝对路径> [-Raw](该包装内的 cat / ls 不接受)。'
33
+ + '有文件工具时用 Read / Glob / Grep;只有 Bash/Shell 时可用 cat;检测到 pwsh/powershell 包装时,唯一可用的 shell 读取形式是 `pwsh -NoProfile -Command "Get-Content -LiteralPath <绝对路径> [-Raw]"`,包装内不接受 `cat` / `ls`,也不接受用 `;` 连接的多段查询。'
33
34
  + '整理反馈用文件写入工具写到任务书指定的反馈文件。';
34
35
  function layerDir(layer, ctx) {
35
36
  const root = resolveRoot();
@@ -56,6 +57,7 @@ export function memoryReadRoots(ctx) {
56
57
  const messages = ctx.chatDir ? path.join(ctx.chatDir, 'messages.jsonl') : undefined;
57
58
  // 批次目录已覆盖反馈文件,不必单独列出
58
59
  add(ctx.batchDir);
60
+ add(ctx.managedTempDir);
59
61
  switch (ctx.subtype) {
60
62
  case 'notes':
61
63
  add(relation && path.join(relation, 'processing'), ...consolidated('relation'), messages);
@@ -183,6 +185,9 @@ function checkShell(input, ctx) {
183
185
  ? { allow: true }
184
186
  : deny('memory_session_command_forbidden', result.message);
185
187
  }
188
+ if (shellCarrier?.dialect === 'powershell' && parsed.ok) {
189
+ return deny('memory_session_command_forbidden', BASH_COMMAND_RULE);
190
+ }
186
191
  if (shellCarrier?.parseFailure || (shellCarrier && shellCarrier.dialect !== 'posix')) {
187
192
  return deny('memory_session_command_forbidden', BASH_COMMAND_RULE);
188
193
  }
@@ -218,12 +223,18 @@ function looksLikeEcCommand(command) {
218
223
  }
219
224
  /** 只读查询被拒的原因:与 checkReadonly 的判定分支一一对应。 */
220
225
  function readonlyDenialHint(command, policyCode, ctx) {
226
+ const shellCarrier = resolveCodexShellCarrierString(command);
227
+ const isPowerShell = shellCarrier?.dialect === 'powershell';
228
+ const shellReadExample = isPowerShell
229
+ ? '唯一可用的 shell 读取形式是 `pwsh -NoProfile -Command "Get-Content -LiteralPath <绝对路径> [-Raw]"`;包装内不接受 `cat` / `ls`,也不接受用 `;` 连接的多段查询。'
230
+ : '只有 Shell 时使用 cat;明确的 PowerShell 包装内则使用下方 Get-Content 形式。';
221
231
  switch (policyCode) {
222
232
  case 'readonly_workspace_escape':
223
233
  return '命令可证明只读,但读取的路径不在可读根内。用任务书「可读根」列出的绝对路径;相对路径按会话 cwd 解析,cwd 本身不可读。';
224
234
  case 'readonly_h_class_read':
225
235
  case 'readonly_l_class_read':
226
- return '命令读取了受保护路径,整理会话不能读。源码检索请把范围直接限定为 `src/`、`tests/` 等源码目录,不要从仓库根 `.` 递归扫描;PowerShell 查询请使用明确的 `pwsh -NoProfile -Command "Get-Content -LiteralPath <绝对路径> [-Raw]"`,不要用包装内的 `cat` / `ls`。';
236
+ return '命令读取了受保护路径,整理会话不能读。源码检索请把范围直接限定为 `src/`、`tests/` 等源码目录,例如 `rg ... src/`,并排除受保护目录:`--glob \'!agents/**\' --glob \'!memory/**\'`;不要从仓库根 `.` 递归扫描。'
237
+ + (isPowerShell ? shellReadExample : ' ' + shellReadExample);
227
238
  default:
228
239
  break;
229
240
  }
@@ -240,7 +251,9 @@ function readonlyDenialHint(command, policyCode, ctx) {
240
251
  + '静态确定不了会读哪些文件。列文件请用 Glob 并给绝对 path。';
241
252
  case 'unsupported-command-or-option':
242
253
  return '命令或选项不在只读查询白名单内。不需要 `cd`:把绝对路径直接写进命令里。'
243
- + '只有 Shell 时用 cat,或在明确的 pwsh/powershell -NoProfile -Command 包装内使用 Get-Content -LiteralPath <绝对路径> [-Raw];有文件工具时也可用 Read / Glob / Grep。';
254
+ + (isPowerShell
255
+ ? shellReadExample
256
+ : '只有 Shell 时用 cat;有文件工具时也可用 Read / Glob / Grep。');
244
257
  case 'unsupported-pipeline-filter':
245
258
  return '管道 `|` 后面的命令不是纯 stdin 过滤命令。';
246
259
  case 'pipeline-filter-must-use-stdin':
@@ -3,6 +3,8 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { agentTaskActivityDir } from '../../paths.js';
5
5
  import { MENU_RESPONSE_MAX_BYTES, MENU_RESPONSE_SAFETY_MARGIN_BYTES } from '../command/menu-protocol.js';
6
+ import { TaskImageResources } from './task-image-resources.js';
7
+ import { logger } from '../../utils/logger.js';
6
8
  const LIST_TEXT_BYTES = 1024;
7
9
  const LIST_LIMIT = 100;
8
10
  const MARKER = '[中间内容已省略]';
@@ -69,6 +71,8 @@ function projectItem(item, maxTextBytes) {
69
71
  const projected = clone(item);
70
72
  const truncatedFields = [];
71
73
  walkStrings(projected, '', (parent, key, fieldPath, value) => {
74
+ if (fieldPath.startsWith('resources.'))
75
+ return;
72
76
  const originalBytes = Buffer.byteLength(value, 'utf8');
73
77
  if (originalBytes <= maxTextBytes)
74
78
  return;
@@ -135,6 +139,34 @@ export class TaskActivityStore {
135
139
  createTask(input) {
136
140
  return this.ensureMeta(input);
137
141
  }
142
+ /** Capture before persistence/publication. Repeat results reuse the original resource. */
143
+ async appendWithImage(input, context) {
144
+ const item = input.item;
145
+ if (item.kind !== 'tool_result' || item.name !== 'ViewImage' || !item.ok)
146
+ return this.append(input);
147
+ const activityId = `activity-${crypto.createHash('sha256').update(JSON.stringify([input.taskId, item.call_id])).digest('hex')}`;
148
+ const previous = this.getActivity(input.taskId, activityId);
149
+ if (previous) {
150
+ if (previous.item.kind === 'tool_result')
151
+ item.resources = previous.item.resources;
152
+ return previous;
153
+ }
154
+ // Only the typed runner result is a source; never parse text for paths.
155
+ const sourcePath = item.result && typeof item.result === 'object'
156
+ ? item.result.path : undefined;
157
+ if (typeof sourcePath === 'string' && sourcePath.trim()) {
158
+ try {
159
+ const resource = await new TaskImageResources(this.selfAid).capture({
160
+ taskId: input.taskId, activityId, sourcePath, ...context,
161
+ });
162
+ item.resources = [resource];
163
+ }
164
+ catch (error) {
165
+ logger.warn(`[TaskActivityStore] image capture unavailable: ${error instanceof Error ? error.message : String(error)}`);
166
+ }
167
+ }
168
+ return this.append({ ...input, activityId });
169
+ }
138
170
  append(input) {
139
171
  const file = taskFile(this.selfAid, input.taskId);
140
172
  const existingLoaded = readJsonl(this.selfAid, input.taskId);
@@ -216,4 +248,22 @@ export class TaskActivityStore {
216
248
  getMeta(taskId) {
217
249
  return readJsonl(this.selfAid, taskId).meta;
218
250
  }
251
+ getActivity(taskId, activityId) {
252
+ return readJsonl(this.selfAid, taskId).records.find(record => record.activityId === activityId);
253
+ }
254
+ readResource(taskId, activityId, resourceId, offset = 0) {
255
+ const record = this.getActivity(taskId, activityId);
256
+ if (!record)
257
+ throw Object.assign(new Error('Activity not found'), { code: 'ACTIVITY_NOT_FOUND' });
258
+ const resource = record.item.kind === 'tool_result' && record.item.ok
259
+ ? record.item.resources?.find(resource => resource.resourceId === resourceId)
260
+ : undefined;
261
+ if (!resource)
262
+ throw Object.assign(new Error('Resource not found'), { code: 'RESOURCE_NOT_FOUND' });
263
+ return new TaskImageResources(this.selfAid).read(taskId, activityId, resource, offset);
264
+ }
265
+ deleteTask(taskId) {
266
+ fs.rmSync(taskFile(this.selfAid, taskId), { force: true });
267
+ new TaskImageResources(this.selfAid).deleteTask(taskId);
268
+ }
219
269
  }
@@ -0,0 +1,140 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import sharp from 'sharp';
5
+ import { agentDataDir } from '../../paths.js';
6
+ import { checkProtectedPathAccess, isSameOrDescendant } from '../permission/protected-paths.js';
7
+ export const TASK_IMAGE_CHUNK_BYTES = 192 * 1024;
8
+ export const TASK_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
9
+ const IMAGE_MIMES = {
10
+ png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif',
11
+ };
12
+ function failure(code, message) {
13
+ return Object.assign(new Error(message), { code });
14
+ }
15
+ function resourceDirectory(selfAid, taskId) {
16
+ if (!/^task-[A-Za-z0-9._:-]+$/.test(taskId))
17
+ throw failure('INVALID_ARGUMENT', 'Invalid taskId');
18
+ return path.join(agentDataDir(selfAid), 'task-resources', encodeURIComponent(taskId));
19
+ }
20
+ /** The activity record is the resource's authority; the caller never supplies a path. */
21
+ export class TaskImageResources {
22
+ selfAid;
23
+ constructor(selfAid) {
24
+ this.selfAid = selfAid;
25
+ }
26
+ async capture(input) {
27
+ const source = path.resolve(input.projectPath, input.sourcePath);
28
+ const realSource = await fs.promises.realpath(source);
29
+ const roots = await Promise.all(input.allowedRoots.map(async (root) => {
30
+ try {
31
+ return await fs.promises.realpath(root);
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }));
37
+ if (!roots.some(root => root && isSameOrDescendant(realSource, root))
38
+ || !checkProtectedPathAccess(source, 'content', { selfAid: this.selfAid }).allowed
39
+ || !checkProtectedPathAccess(realSource, 'content', { selfAid: this.selfAid }).allowed) {
40
+ throw failure('FORBIDDEN', 'Image source is outside this session');
41
+ }
42
+ const handle = await fs.promises.open(realSource, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
43
+ let bytes;
44
+ try {
45
+ const before = await handle.stat();
46
+ if (!before.isFile() || before.nlink !== 1 || before.size < 1 || before.size > TASK_IMAGE_MAX_BYTES) {
47
+ throw failure('INVALID_IMAGE', 'Image must be a regular file within the image size limit');
48
+ }
49
+ bytes = Buffer.alloc(before.size);
50
+ let read = 0;
51
+ while (read < bytes.length) {
52
+ const part = await handle.read(bytes, read, bytes.length - read, read);
53
+ if (!part.bytesRead)
54
+ break;
55
+ read += part.bytesRead;
56
+ }
57
+ const after = await handle.stat();
58
+ const current = await fs.promises.stat(realSource);
59
+ if (read !== bytes.length || before.size !== after.size || before.mtimeMs !== after.mtimeMs
60
+ || before.ctimeMs !== after.ctimeMs || before.ino !== current.ino || before.dev !== current.dev
61
+ || await fs.promises.realpath(source) !== realSource) {
62
+ throw failure('IMAGE_CHANGED', 'Image changed during capture');
63
+ }
64
+ }
65
+ finally {
66
+ await handle.close();
67
+ }
68
+ const metadata = await sharp(bytes, { limitInputPixels: 40_000_000 }).metadata();
69
+ const mimeType = IMAGE_MIMES[metadata.format ?? ''];
70
+ if (!mimeType || !metadata.width || !metadata.height)
71
+ throw failure('INVALID_IMAGE', 'Unsupported image format');
72
+ const sha256 = crypto.createHash('sha256').update(bytes).digest('hex');
73
+ const directory = resourceDirectory(this.selfAid, input.taskId);
74
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
75
+ const file = path.join(directory, sha256);
76
+ try {
77
+ fs.writeFileSync(file, bytes, { flag: 'wx', mode: 0o600 });
78
+ }
79
+ catch (error) {
80
+ if (error.code !== 'EEXIST')
81
+ throw error;
82
+ const stat = fs.lstatSync(file);
83
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size !== bytes.length
84
+ || crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex') !== sha256) {
85
+ throw failure('RESOURCE_CORRUPT', 'Stored image does not match its content identity');
86
+ }
87
+ }
88
+ return {
89
+ resourceId: `resource-${crypto.randomUUID().replace(/-/g, '')}`,
90
+ activityId: input.activityId,
91
+ kind: 'image',
92
+ fileName: path.basename(source),
93
+ mimeType,
94
+ size: bytes.length,
95
+ sha256,
96
+ width: metadata.width,
97
+ height: metadata.height,
98
+ immutable: true,
99
+ };
100
+ }
101
+ read(taskId, activityId, resource, offset = 0) {
102
+ if (resource.activityId !== activityId || !/^[a-f0-9]{64}$/.test(resource.sha256)) {
103
+ throw failure('RESOURCE_NOT_FOUND', 'Resource is not part of this activity');
104
+ }
105
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= resource.size) {
106
+ throw failure('INVALID_OFFSET', 'Image offset is outside the resource');
107
+ }
108
+ const file = path.join(resourceDirectory(this.selfAid, taskId), resource.sha256);
109
+ let fd;
110
+ try {
111
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
112
+ }
113
+ catch (error) {
114
+ if (error.code === 'ENOENT')
115
+ throw failure('RESOURCE_EXPIRED', 'Image content is no longer available');
116
+ throw error;
117
+ }
118
+ try {
119
+ const stat = fs.fstatSync(fd);
120
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size !== resource.size)
121
+ throw failure('RESOURCE_CORRUPT', 'Image content is invalid');
122
+ const bytes = Buffer.alloc(Math.min(TASK_IMAGE_CHUNK_BYTES, resource.size - offset));
123
+ const count = fs.readSync(fd, bytes, 0, bytes.length, offset);
124
+ if (count !== bytes.length)
125
+ throw failure('RESOURCE_CORRUPT', 'Image content is incomplete');
126
+ return {
127
+ view: 'resource', taskId, activityId, resourceId: resource.resourceId,
128
+ mimeType: resource.mimeType, sha256: resource.sha256, totalSize: resource.size,
129
+ offset, byteLength: bytes.length, encoding: 'base64', data: bytes.toString('base64'),
130
+ hasMore: offset + bytes.length < resource.size,
131
+ };
132
+ }
133
+ finally {
134
+ fs.closeSync(fd);
135
+ }
136
+ }
137
+ deleteTask(taskId) {
138
+ fs.rmSync(resourceDirectory(this.selfAid, taskId), { recursive: true, force: true });
139
+ }
140
+ }
@@ -93,7 +93,7 @@ export function createThreadOperationExecutor(dependencies) {
93
93
  const globalOperation = ['list-peers', 'check-index', 'rebuild-index'].includes(request.op);
94
94
  const decision = await authorizeOperation({
95
95
  source: 'agent-tool', subject,
96
- intent: { operation: `ec.thread.${request.op}`, scope: globalOperation && !(relationOnly && request.op === 'list-peers') ? 'agent' : 'relation', source: 'agent-tool', args: { self: request.selfAid, peer: request.peer ?? currentPeer, peerKey: grant.peerKey } },
96
+ intent: { operation: `ec.thread.${request.op}`, scope: globalOperation && !(relationOnly && request.op === 'list-peers') ? 'agent' : 'relation', source: 'agent-tool', args: { self: request.selfAid, targetAgentAid: request.selfAid, peer: request.peer ?? currentPeer, peerKey: grant.peerKey } },
97
97
  auditMetadata: { taskId: grant.taskId, messageId: grant.messageId },
98
98
  });
99
99
  if (!decision.allow)
@@ -337,7 +337,6 @@ export class ThreadService {
337
337
  entry.lastActiveAt = nameUpdatedAt;
338
338
  this.writeThreadIndex(selfAid, index);
339
339
  this.appendThreadSnapshot(selfAid, entry);
340
- // Sync to session
341
340
  const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, threadId, selfAid);
342
341
  if (session) {
343
342
  await this.sessionManager.renameSession(session.id, sanitized, nameUpdatedAt);
@@ -40,9 +40,9 @@ function serialize(value) {
40
40
  /**
41
41
  * 联系人快照的 `content_digest`。
42
42
  *
43
- * 摘要输入是 `{owner?, personal_assistant?, entries}`:身份对象存在才加入,
44
- * 缺失时不补 `null`。入参必须是文件里原样的值——不删可选字段、不删 null、
45
- * 不补默认值。归一化之后再算必然对不上。
43
+ * 摘要输入是 `{owner?, personal_assistant?, entries, groups, blocked_aids}`:
44
+ * 身份对象存在才加入,缺失时不补 `null`。入参必须是文件里原样的值——不删可选字段、
45
+ * 不删 null、不补默认值。归一化之后再算必然对不上。
46
46
  */
47
47
  export function directoryContentDigest(input) {
48
48
  const payload = { entries: input.entries };
@@ -50,5 +50,7 @@ export function directoryContentDigest(input) {
50
50
  payload.owner = input.owner;
51
51
  if (input.personalAssistant !== undefined)
52
52
  payload.personal_assistant = input.personalAssistant;
53
+ payload.groups = input.groups;
54
+ payload.blocked_aids = input.blockedAids;
53
55
  return createHash('sha256').update(canonicalJson(payload), 'utf8').digest('hex');
54
56
  }
@@ -29,6 +29,23 @@ export function liveOwnerDirectoryCache(selfAid) {
29
29
  }
30
30
  return live.cache;
31
31
  }
32
+ /**
33
+ * 外部联系开关变更后重算 `directory.md`。
34
+ *
35
+ * `allowExternalContacts` 是**唯一**会改变注入内容的开关:打开后外部四组才出现。
36
+ * 准入读的是 `config.json`(每次现读,立刻生效),而注入内容来自渲染产物,不重算
37
+ * 就会停在旧版本——Owner 打开开关后,来客能联系了,agent 却看不到是谁。
38
+ *
39
+ * 只读缓存、不写盘以外没有副作用;没有活缓存(channel 未连)时返回 false,
40
+ * 由下一次名录落地或备注改写顺带刷新。
41
+ */
42
+ export function refreshDirectoryMarkdown(selfAid) {
43
+ const cache = liveOwnerDirectoryCache(selfAid);
44
+ if (!cache)
45
+ return false;
46
+ cache.refreshMarkdown();
47
+ return true;
48
+ }
32
49
  /**
33
50
  * 触发一次有界同步:处理待办的 pending 标记(拉取 + 落盘),最多等
34
51
  * `OWNER_DIRECTORY_INITIAL_WAIT_MS`。超时后同步继续在后台跑。
@@ -150,14 +167,17 @@ export function readOwnerDirectoryMembership(selfAid, aid) {
150
167
  const entry = snapshot.entries.find(item => item.aid === aid);
151
168
  if (!entry)
152
169
  return { category: 'not_found', effectiveAllowExternalContacts };
153
- // 内外判据只有一个来源:Owner 身份块里的 aid;缺失时回落到根 owner_aid(协议要求两者相等)。
170
+ // 内外判据只有一个来源:Owner 身份块里的 aid。
154
171
  const ownerRef = ownerRefAid(snapshot, ownerAid);
155
172
  const internal = isInternalEntry(entry, ownerRef);
156
- const type = (entry.type ?? '').toLowerCase();
173
+ const type = entry.type;
157
174
  if (type === 'agent')
158
175
  return { category: 'agent', internal, entry, effectiveAllowExternalContacts };
159
176
  if (type === 'human')
160
177
  return { category: 'human', internal, entry, effectiveAllowExternalContacts };
178
+ // 协议外的 type(`ai`、`codeagent`、缺失…)落 `other`:它既不是会发消息的
179
+ // agent/human,也不是协议允许的 service/device/org/custom/host,用途未知。
180
+ // 准入仍按内外分档(与宿主类型一致),只是不假装知道它是什么。
161
181
  return { category: 'other', internal, entry, effectiveAllowExternalContacts };
162
182
  }
163
183
  catch {