evolcore 0.0.45 → 0.0.47

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 (228) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/bin/ecmsg.js +33 -23
  3. package/dist/ability/application-service.js +1 -2
  4. package/dist/ability/package.js +28 -0
  5. package/dist/agent-template/jobs.js +158 -36
  6. package/dist/agent-template/runtime.js +401 -34
  7. package/dist/agent-template/service.js +764 -369
  8. package/dist/agent-template/tool-runner.js +35 -17
  9. package/dist/agent-template/types.js +7 -4
  10. package/dist/agents/baseagent.js +10 -9
  11. package/dist/agents/claude-runner.js +22 -6
  12. package/dist/agents/codex/app-server-client.js +34 -27
  13. package/dist/agents/codex/diagnostics.js +18 -1
  14. package/dist/agents/codex-runner.js +3 -1
  15. package/dist/agents/ecagent-runner.js +3 -1
  16. package/dist/agents/gemini-runner.js +2 -1
  17. package/dist/aun/group/fs-download.js +1 -1
  18. package/dist/aun/menu/client.js +142 -182
  19. package/dist/aun/rpc/client.js +33 -17
  20. package/dist/aun/service-proxy.js +6 -23
  21. package/dist/channels/aun.js +675 -120
  22. package/dist/channels/daemon.js +1 -1
  23. package/dist/cli/agent-create.js +37 -10
  24. package/dist/cli/agent-template.js +105 -84
  25. package/dist/cli/agent.js +31 -18
  26. package/dist/cli/daemon-commands.js +42 -56
  27. package/dist/cli/daemon-lifecycle-client.js +55 -19
  28. package/dist/cli/directory.js +12 -4
  29. package/dist/cli/ecmsg-gateway.js +5 -2
  30. package/dist/cli/events-command.js +2 -1
  31. package/dist/cli/init-channel.js +2 -2
  32. package/dist/cli/init.js +57 -21
  33. package/dist/cli/integrity-command.js +2 -0
  34. package/dist/cli/managed-command-guard.js +20 -1
  35. package/dist/cli/menu-client.js +7 -5
  36. package/dist/cli/restart-monitor.js +135 -46
  37. package/dist/cli/services-command.js +28 -5
  38. package/dist/cli/task-context.js +83 -15
  39. package/dist/cli/upgrade-command.js +4 -2
  40. package/dist/config/config-field-policy.js +24 -0
  41. package/dist/config/config-manager.js +49 -19
  42. package/dist/config/peer-book-store.js +167 -127
  43. package/dist/config/peer-role-resolver.js +24 -4
  44. package/dist/config/provider-identity-migration.js +158 -6
  45. package/dist/config/provider-identity.js +10 -4
  46. package/dist/config/provider-ipc-service.js +10 -2
  47. package/dist/config/provider-local-sync.js +2 -2
  48. package/dist/config/providers-config.js +95 -10
  49. package/dist/config/providers-import.js +4 -6
  50. package/dist/config/providers.js +14 -3
  51. package/dist/config/role-store.js +1 -1
  52. package/dist/config/schema-migration.js +123 -16
  53. package/dist/config/schema-registry.js +6 -2
  54. package/dist/config-store.js +9 -1
  55. package/dist/core/agent-application-service.js +56 -29
  56. package/dist/core/agent-create-status.js +3 -1
  57. package/dist/core/agent-creation-claim.js +1 -0
  58. package/dist/core/agent-ipc-registration.js +2 -2
  59. package/dist/core/agent-reload-coordinator.js +38 -1
  60. package/dist/core/agent-runtime.js +91 -43
  61. package/dist/core/auth/agent-delegation.js +13 -3
  62. package/dist/core/auth/delegation-diagnostics.js +56 -15
  63. package/dist/core/auth/operation-authorizer.js +2 -2
  64. package/dist/core/auth/operation-catalog.js +3 -3
  65. package/dist/core/bootstrap-service.js +3 -0
  66. package/dist/core/capability/capability-manager.js +3 -1
  67. package/dist/core/channel-loader.js +29 -3
  68. package/dist/core/channel-runtime.js +1 -1
  69. package/dist/core/command/agent-control.js +6 -5
  70. package/dist/core/command/agent-template-menu.js +32 -97
  71. package/dist/core/command/eventcenter-menu.js +61 -13
  72. package/dist/core/command/menu-catalog.js +11 -4
  73. package/dist/core/command/menu-handler.js +39 -12
  74. package/dist/core/command/menu-protocol.js +8 -16
  75. package/dist/core/command/skill-slash.js +6 -2
  76. package/dist/core/command/slash-handler.js +4 -6
  77. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  78. package/dist/core/command/team-workspace-management-store.js +83 -0
  79. package/dist/core/command/team-workspace-management.js +1 -2
  80. package/dist/core/command/team-workspace-team.js +26 -3
  81. package/dist/core/daemon-bootstrap.js +11 -9
  82. package/dist/core/daemon-control.js +4 -7
  83. package/dist/core/daemon-lifecycle.js +189 -143
  84. package/dist/core/evolagent-registry.js +50 -2
  85. package/dist/core/evolagent.js +2 -1
  86. package/dist/core/file-integrity/read.js +9 -16
  87. package/dist/core/file-integrity/store.js +94 -34
  88. package/dist/core/handoff/dispatcher.js +33 -7
  89. package/dist/core/handoff/runtime.js +8 -0
  90. package/dist/core/host-snapshot.js +9 -4
  91. package/dist/core/inference/text-inference.js +12 -2
  92. package/dist/core/initialization/service.js +22 -4
  93. package/dist/core/invoke/invoke-service.js +24 -3
  94. package/dist/core/ipc-registration.js +7 -3
  95. package/dist/core/memory/consolidation.js +6 -6
  96. package/dist/core/message/aun-ipc-sender.js +109 -7
  97. package/dist/core/message/contact-admission.js +6 -2
  98. package/dist/core/message/message-bridge.js +13 -0
  99. package/dist/core/message/message-queue.js +131 -30
  100. package/dist/core/message/pending-hints.js +8 -0
  101. package/dist/core/message/response-engine.js +48 -2
  102. package/dist/core/message/send-routing.js +3 -12
  103. package/dist/core/model/catalog-service.js +13 -0
  104. package/dist/core/model/model-catalog.js +57 -18
  105. package/dist/core/ownership/owner-resolver.js +27 -10
  106. package/dist/core/pack-auth.js +163 -31
  107. package/dist/core/pack-install.js +42 -1
  108. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  109. package/dist/core/permission/ec-command-parser.js +3 -1
  110. package/dist/core/permission/shell-environment.js +23 -0
  111. package/dist/core/rate-window.js +6 -1
  112. package/dist/core/relation/peer-identity.js +5 -1
  113. package/dist/core/relation/same-owner-proof.js +2 -1
  114. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  115. package/dist/core/session/session-file-health.js +36 -7
  116. package/dist/core/session/session-idle-monitor.js +0 -1
  117. package/dist/core/session/session-manager.js +14 -0
  118. package/dist/core/session/session-title.js +26 -6
  119. package/dist/core/skill/index-generator.js +3 -4
  120. package/dist/core/task/task-image-resources.js +1 -1
  121. package/dist/core/thread/thread-service.js +0 -1
  122. package/dist/core/thread/topic-id.js +8 -0
  123. package/dist/directory/owner-directory-admission.js +17 -0
  124. package/dist/directory/owner-directory-cache.js +3 -1
  125. package/dist/directory/owner-directory-markdown.js +145 -23
  126. package/dist/directory/owner-directory-policy.js +23 -0
  127. package/dist/directory/owner-directory-query-operation.js +20 -6
  128. package/dist/directory/owner-directory-search.js +47 -0
  129. package/dist/eck/message-renderer.js +171 -32
  130. package/dist/ecweb/basic-settings-service.js +7 -3
  131. package/dist/ecweb/providers-service.js +17 -10
  132. package/dist/ecweb/runtime/lifecycle.js +65 -16
  133. package/dist/ecweb/runtime/supervisor.js +79 -50
  134. package/dist/event-center/admission-materializer.js +1 -1
  135. package/dist/event-center/bus-gate.js +48 -4
  136. package/dist/event-center/bus-host.js +3 -3
  137. package/dist/event-center/center-config.js +57 -28
  138. package/dist/event-center/dispatcher.js +8 -0
  139. package/dist/event-center/event-log.js +69 -27
  140. package/dist/event-center/index-generator.js +6 -1
  141. package/dist/event-center/ipc-operation.js +66 -25
  142. package/dist/event-center/pack-loader.js +12 -55
  143. package/dist/event-center/pack-manager.js +5 -3
  144. package/dist/event-center/registry.js +48 -52
  145. package/dist/event-center/runtime.js +219 -81
  146. package/dist/event-center/script-runner.js +18 -7
  147. package/dist/event-center/types.js +9 -1
  148. package/dist/event-center/validation.js +33 -4
  149. package/dist/index.js +132 -75
  150. package/dist/ipc.js +35 -8
  151. package/dist/product.js +1 -0
  152. package/dist/proxy/manager.js +52 -11
  153. package/dist/proxy/service-supervisor.js +265 -67
  154. package/dist/services/dispatcher.js +26 -3
  155. package/dist/services/idempotency.js +128 -0
  156. package/dist/services/identity.js +3 -27
  157. package/dist/services/index-generator.js +5 -1
  158. package/dist/services/index.js +244 -45
  159. package/dist/services/ipc-operation.js +164 -20
  160. package/dist/services/pack-manager.js +37 -9
  161. package/dist/services/router.js +100 -31
  162. package/dist/services/script-runner.js +15 -4
  163. package/dist/services/service-payload.js +50 -2
  164. package/dist/services/validation.js +107 -3
  165. package/dist/trigger/scheduler.js +18 -4
  166. package/dist/trigger/script-sandbox.js +39 -2
  167. package/dist/trigger/state.js +7 -0
  168. package/dist/utils/aid-bind.js +155 -18
  169. package/dist/utils/atomic-write.js +3 -3
  170. package/dist/utils/cross-platform.js +59 -16
  171. package/dist/utils/error-utils.js +26 -1
  172. package/dist/utils/instance-registry.js +94 -35
  173. package/dist/utils/process-introspect.js +187 -27
  174. package/dist/utils/project-path.js +47 -3
  175. package/dist/utils/upgrade-jobs.js +4 -4
  176. package/dist/utils/windows-shell-trust.js +174 -68
  177. package/kits/docs/context-assembly.md +3 -3
  178. package/kits/docs/evolcore/agent.md +28 -10
  179. package/kits/docs/evolcore/aid.md +3 -1
  180. package/kits/docs/evolcore/config.md +22 -0
  181. package/kits/docs/evolcore/directory.md +46 -12
  182. package/kits/docs/evolcore/event-center.md +6 -6
  183. package/kits/docs/evolcore/group-collaboration.md +1 -1
  184. package/kits/docs/evolcore/menu-client.md +7 -5
  185. package/kits/docs/evolcore/menu-protocol.md +5 -3
  186. package/kits/docs/evolcore/msg.md +10 -3
  187. package/kits/docs/evolcore/provider.md +17 -5
  188. package/kits/docs/evolcore/services.md +145 -12
  189. package/kits/docs/evolcore/thread-chain.md +17 -9
  190. package/kits/docs/prompt-loading-architecture.md +4 -4
  191. package/kits/eck_message_manifest.json +46 -3
  192. package/kits/rules/04-relation.md +10 -2
  193. package/kits/rules/06-channel.md +2 -1
  194. package/kits/schemas/providers.schema.2.json +1 -0
  195. package/kits/skills/ec-group/SKILL.md +4 -0
  196. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  197. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  198. package/kits/skills/thread-ops/SKILL.md +8 -5
  199. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  200. package/kits/templates/message-fragments/group-batch.md +1 -0
  201. package/kits/templates/message-fragments/item-group.md +4 -0
  202. package/kits/templates/message-fragments/item-private.md +4 -0
  203. package/kits/templates/message-fragments/thread-context.md +1 -1
  204. package/kits/templates/system-fragments/commands.md +5 -5
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +11 -7
  207. package/package.json +3 -2
  208. package/scripts/agent-template/index.mjs +9 -4
  209. package/scripts/agent-template/inspect.mjs +16 -9
  210. package/scripts/agent-template/shared/plan.mjs +3 -33
  211. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  212. package/scripts/agent-template/shared/template-package.mjs +119 -10
  213. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  214. package/scripts/agent-template/shared/template.mjs +5 -5
  215. package/scripts/agent-template/team-pack.mjs +245 -0
  216. package/scripts/agent-template/team-preview.mjs +111 -0
  217. package/scripts/aid-batch/identity-batch.mjs +143 -0
  218. package/dist/ability/versions.js +0 -32
  219. package/dist/aun/model-headers.js +0 -17
  220. package/dist/channels/builtin-plugins.js +0 -19
  221. package/dist/core/command/team-workspace-initializer.js +0 -2
  222. package/dist/core/command/team-workspace-job-store.js +0 -88
  223. package/dist/core/command/team-workspace-management-service.js +0 -2
  224. package/dist/core/contact-bind-registry.js +0 -27
  225. package/dist/event-center/ledger.js +0 -52
  226. package/dist/services/reply.js +0 -55
  227. package/kits/templates/message-fragments/item.md +0 -3
  228. package/scripts/agent-template/pack.mjs +0 -169
@@ -2,7 +2,8 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import crypto from 'crypto';
4
4
  import { createRequire } from 'module';
5
- import { integrityDbPath, integritySnapshotDir, resolveRoot } from '../../paths.js';
5
+ import { getPackageRoot, integrityDbPath, integritySnapshotDir, kitsDir, resolveRoot } from '../../paths.js';
6
+ import { MAIN_PACKAGE_NAME } from '../../product.js';
6
7
  import { logger } from '../../utils/logger.js';
7
8
  // 项目是 ESM,裸 require 不存在;与 codex-session-file-adapter 同款懒加载
8
9
  const requireFromHere = createRequire(import.meta.url);
@@ -14,7 +15,8 @@ const CREATE_TABLE_SQL = `
14
15
  sha256 TEXT NOT NULL,
15
16
  registered_at INTEGER NOT NULL,
16
17
  last_verified_at INTEGER,
17
- registrar_aid TEXT
18
+ registrar_aid TEXT,
19
+ package_version TEXT
18
20
  )
19
21
  `;
20
22
  function getDb() {
@@ -29,13 +31,64 @@ function getDb() {
29
31
  throw new Error('[file-integrity] node:sqlite 不可用,需要 Node.js 22.5+');
30
32
  }
31
33
  fs.mkdirSync(path.dirname(integrityDbPath()), { recursive: true });
32
- _db = new DatabaseSync(integrityDbPath());
34
+ const db = new DatabaseSync(integrityDbPath());
33
35
  // CLI 进程和 daemon 可能同时打开同一个库:先设等待,再切 WAL
34
- _db.exec('PRAGMA busy_timeout = 5000');
35
- _db.exec('PRAGMA journal_mode = WAL');
36
- _db.exec(CREATE_TABLE_SQL);
36
+ try {
37
+ db.exec('PRAGMA busy_timeout = 5000');
38
+ db.exec('PRAGMA journal_mode = WAL');
39
+ // CLI 与 daemon 可能同时启动,迁移检查与 ALTER 必须在同一写锁内。
40
+ db.exec('BEGIN IMMEDIATE');
41
+ db.exec(CREATE_TABLE_SQL);
42
+ const columns = db.prepare('PRAGMA table_info(file_integrity)').all();
43
+ if (!columns.some(column => column.name === 'package_version')) {
44
+ db.exec('ALTER TABLE file_integrity ADD COLUMN package_version TEXT');
45
+ }
46
+ db.exec('COMMIT');
47
+ _db = db;
48
+ }
49
+ catch (err) {
50
+ try {
51
+ db.exec('ROLLBACK');
52
+ }
53
+ catch { /* ignore */ }
54
+ db.close();
55
+ throw err;
56
+ }
37
57
  return _db;
38
58
  }
59
+ function transaction(action) {
60
+ const db = getDb();
61
+ db.exec('BEGIN IMMEDIATE');
62
+ try {
63
+ const result = action();
64
+ db.exec('COMMIT');
65
+ return result;
66
+ }
67
+ catch (err) {
68
+ try {
69
+ db.exec('ROLLBACK');
70
+ }
71
+ catch { /* ignore */ }
72
+ throw err;
73
+ }
74
+ }
75
+ /** 随包发布的 kits 文档、模板与内置技能共用版本基线。 */
76
+ export function isShippedPath(filePath) {
77
+ const rel = path.relative(path.resolve(kitsDir()), path.resolve(filePath));
78
+ return rel !== '' && !path.isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${path.sep}`);
79
+ }
80
+ function packageVersionFor(filePath) {
81
+ if (!isShippedPath(filePath))
82
+ return null;
83
+ // 读取磁盘当前版本,不能复用进程启动版本缓存:npm 可能在原路径替换安装包。
84
+ const file = path.join(getPackageRoot(), 'package.json');
85
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
86
+ if (pkg?.name !== MAIN_PACKAGE_NAME || typeof pkg.version !== 'string'
87
+ || !pkg.version.trim() || pkg.version === 'unknown') {
88
+ throw new Error(`[file-integrity] invalid package identity/version: ${file}`);
89
+ }
90
+ return pkg.version;
91
+ }
39
92
  // ── 快照路径规范化 ────────────────────────────────────────────────────────────
40
93
  /**
41
94
  * 台账主键:绝对路径 + 正斜杠;Windows 文件系统大小写不敏感,再统一转小写,
@@ -83,45 +136,41 @@ function short(hash) {
83
136
  export function registerFile(filePath, aid) {
84
137
  const key = recordKey(filePath);
85
138
  const bytes = fs.readFileSync(filePath);
86
- registerBytes(key, bytes, aid, fs.statSync(filePath).mtime);
139
+ registerBytes(key, bytes, aid, fs.statSync(filePath).mtime, packageVersionFor(filePath));
87
140
  logger.info(`[file-integrity] registered path=${key} sha256=${short(computeSha256(bytes))}${aid ? ` aid=${aid}` : ''}`);
88
141
  }
89
142
  /**
90
143
  * node:sqlite 没有 transaction() 包装,手写 BEGIN/COMMIT:
91
144
  * 快照写失败则 ROLLBACK,台账不会指向一份不存在的快照。
92
145
  */
93
- function registerBytes(key, bytes, aid, mtime) {
146
+ function registerBytes(key, bytes, aid, mtime, packageVersion = null) {
147
+ transaction(() => persistBytes(key, bytes, aid, mtime, packageVersion));
148
+ }
149
+ /** 调用方持有写锁,台账版本与快照在同一事务中切换。 */
150
+ function persistBytes(key, bytes, aid, mtime, packageVersion = null) {
94
151
  const sha256 = computeSha256(bytes);
95
152
  const now = Math.floor(Date.now() / 1000);
96
153
  const db = getDb();
97
- db.exec('BEGIN');
98
- try {
99
- db.prepare(`INSERT INTO file_integrity (file_path, sha256, registered_at, registrar_aid)
100
- VALUES (?, ?, ?, ?)
101
- ON CONFLICT(file_path) DO UPDATE SET
102
- sha256 = excluded.sha256,
103
- registered_at = excluded.registered_at,
104
- registrar_aid = excluded.registrar_aid`).run(key, sha256, now, aid ?? null);
105
- const snap = snapshotPath(key);
106
- atomicWrite(snap, bytes);
107
- // 快照带上原文件 mtime,恢复时还原回去;记忆的排序和超期判断都读 mtime
108
- if (mtime)
109
- fs.utimesSync(snap, mtime, mtime);
110
- db.exec('COMMIT');
111
- }
112
- catch (err) {
113
- try {
114
- db.exec('ROLLBACK');
115
- }
116
- catch { /* ignore */ }
117
- throw err;
118
- }
154
+ db.prepare(`INSERT INTO file_integrity (file_path, sha256, registered_at, registrar_aid, package_version)
155
+ VALUES (?, ?, ?, ?, ?)
156
+ ON CONFLICT(file_path) DO UPDATE SET
157
+ sha256 = excluded.sha256,
158
+ registered_at = excluded.registered_at,
159
+ registrar_aid = excluded.registrar_aid,
160
+ package_version = excluded.package_version,
161
+ last_verified_at = NULL`).run(key, sha256, now, aid ?? null, packageVersion);
162
+ const snap = snapshotPath(key);
163
+ atomicWrite(snap, bytes);
164
+ // 快照带上原文件 mtime,恢复时还原回去;记忆的排序和超期判断都读 mtime
165
+ if (mtime)
166
+ fs.utimesSync(snap, mtime, mtime);
119
167
  }
120
168
  /**
121
169
  * 校验文件完整性。
122
170
  *
123
171
  * - 文件不存在 → missing
124
172
  * - 台账无记录 → 用本次读到的字节自动登记,返回 verified
173
+ * - kits 所属安装版本变化(包括旧记录没有版本)→ 登记当前安装内容,绝不恢复旧版本快照
125
174
  * - sha256 匹配 → verified,更新 last_verified_at
126
175
  * - 不匹配且 restoreOnFail → 快照 sha256 与台账一致则原子恢复,返回 restored;否则 tampered
127
176
  * - 不匹配且未要求恢复 → tampered
@@ -132,16 +181,27 @@ export function verifyFile(filePath, opts) {
132
181
  const key = recordKey(filePath);
133
182
  if (!fs.existsSync(filePath))
134
183
  return { status: 'missing' };
184
+ // 串行化跨进程的首次登记、版本切换和恢复,避免读到旧台账后覆盖新快照。
185
+ return transaction(() => verifyLocked(filePath, key, opts));
186
+ }
187
+ function verifyLocked(filePath, key, opts) {
188
+ // 包信息读取失败时直接报错,在读旧快照及写文件之前结束。
189
+ const packageVersion = packageVersionFor(filePath);
135
190
  const bytes = fs.readFileSync(filePath);
136
191
  const actual = computeSha256(bytes);
137
192
  const db = getDb();
138
- const row = db.prepare('SELECT sha256 FROM file_integrity WHERE file_path = ?').get(key);
193
+ const row = db.prepare('SELECT sha256, package_version FROM file_integrity WHERE file_path = ?').get(key);
139
194
  if (!row) {
140
195
  // 用已读字节登记,避免二次读文件时内容已变
141
- registerBytes(key, bytes, undefined, fs.statSync(filePath).mtime);
196
+ persistBytes(key, bytes, undefined, fs.statSync(filePath).mtime, packageVersion);
142
197
  logger.info(`[file-integrity] auto-registered path=${key} sha256=${short(actual)}`);
143
198
  return { status: 'verified', bytes };
144
199
  }
200
+ if (packageVersion !== null && row.package_version !== packageVersion) {
201
+ persistBytes(key, bytes, undefined, fs.statSync(filePath).mtime, packageVersion);
202
+ logger.info(`[file-integrity] package-baseline-updated path=${key} from=${row.package_version ?? 'legacy'} to=${packageVersion} sha256=${short(actual)}`);
203
+ return { status: 'verified', bytes };
204
+ }
145
205
  if (actual === row.sha256) {
146
206
  db.prepare('UPDATE file_integrity SET last_verified_at = ? WHERE file_path = ?')
147
207
  .run(Math.floor(Date.now() / 1000), key);
@@ -171,7 +231,7 @@ export function verifyFile(filePath, opts) {
171
231
  }
172
232
  /** 只读查询台账记录,不读文件,供诊断和 CLI 使用。 */
173
233
  export function queryRecord(filePath) {
174
- const row = getDb().prepare('SELECT file_path, sha256, registered_at, last_verified_at, registrar_aid FROM file_integrity WHERE file_path = ?').get(recordKey(filePath));
234
+ const row = getDb().prepare('SELECT file_path, sha256, registered_at, last_verified_at, registrar_aid, package_version FROM file_integrity WHERE file_path = ?').get(recordKey(filePath));
175
235
  return row ?? null;
176
236
  }
177
237
  /**
@@ -246,7 +306,7 @@ export function removeRegisteredFile(file) {
246
306
  export function registerContent(filePath, content, aid) {
247
307
  const key = recordKey(filePath);
248
308
  const bytes = Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf-8');
249
- registerBytes(key, bytes, aid);
309
+ registerBytes(key, bytes, aid, undefined, packageVersionFor(filePath));
250
310
  }
251
311
  /** 只读检查,不改台账、不恢复文件,也不更新 last_verified_at。供诊断和 CLI 使用。 */
252
312
  export function checkFile(filePath) {
@@ -1,10 +1,12 @@
1
1
  import { logger } from '../../utils/logger.js';
2
+ import { templateInstallationGate } from '../../agent-template/jobs.js';
2
3
  export class HandoffDispatcher {
3
4
  store;
4
5
  mutexes;
5
6
  sender;
6
7
  running = new Set();
7
8
  pausedAgents = new Set();
9
+ holds = new Map();
8
10
  maxAttempts;
9
11
  retryDelaysMs;
10
12
  queueTtlMs;
@@ -24,7 +26,9 @@ export class HandoffDispatcher {
24
26
  this.now = options.now ?? Date.now;
25
27
  }
26
28
  notify(selfAid, targetSessionId) {
27
- if (this.pausedAgents.has(selfAid))
29
+ if (templateInstallationGate(selfAid).blocked)
30
+ return;
31
+ if (this.isAgentPaused(selfAid))
28
32
  return;
29
33
  const key = this.key(selfAid, targetSessionId);
30
34
  if (this.running.has(key))
@@ -42,6 +46,23 @@ export class HandoffDispatcher {
42
46
  this.expirationTimers.delete(key);
43
47
  }
44
48
  }
49
+ holdAgent(selfAid, token) {
50
+ if (this.isAgentRunning(selfAid) || this.holds.get(selfAid)?.size) {
51
+ throw Object.assign(new Error('Agent has active handoff work'), { code: 'AGENT_BUSY' });
52
+ }
53
+ const holds = new Set([token]);
54
+ this.holds.set(selfAid, holds);
55
+ let released = false;
56
+ return () => {
57
+ if (released)
58
+ return;
59
+ released = true;
60
+ holds.delete(token);
61
+ if (!holds.size)
62
+ this.holds.delete(selfAid);
63
+ this.resumeAgentDeliveries(selfAid);
64
+ };
65
+ }
45
66
  async drainAgent(selfAid, timeoutMs = 30000) {
46
67
  this.pauseAgent(selfAid);
47
68
  const startedAt = Date.now();
@@ -54,6 +75,11 @@ export class HandoffDispatcher {
54
75
  }
55
76
  resumeAgent(selfAid) {
56
77
  this.pausedAgents.delete(selfAid);
78
+ this.resumeAgentDeliveries(selfAid);
79
+ }
80
+ resumeAgentDeliveries(selfAid) {
81
+ if (this.isAgentPaused(selfAid))
82
+ return;
57
83
  const targets = new Set(this.store.list(selfAid)
58
84
  .filter(instance => instance.state === 'queued')
59
85
  .map(instance => instance.target_session_id));
@@ -61,7 +87,7 @@ export class HandoffDispatcher {
61
87
  this.notify(selfAid, targetSessionId);
62
88
  }
63
89
  isAgentPaused(selfAid) {
64
- return this.pausedAgents.has(selfAid);
90
+ return this.pausedAgents.has(selfAid) || !!this.holds.get(selfAid)?.size;
65
91
  }
66
92
  /** Whether delivery work for this exact target is currently executing. */
67
93
  isRunning(selfAid, targetSessionId) {
@@ -108,7 +134,7 @@ export class HandoffDispatcher {
108
134
  }
109
135
  async run(selfAid, targetSessionId) {
110
136
  while (true) {
111
- if (this.pausedAgents.has(selfAid))
137
+ if (this.isAgentPaused(selfAid))
112
138
  return;
113
139
  this.expireQueued(selfAid, targetSessionId);
114
140
  const next = this.store.listByTarget(selfAid, targetSessionId, 'queued')[0];
@@ -121,10 +147,10 @@ export class HandoffDispatcher {
121
147
  let sent = false;
122
148
  let blocked = false;
123
149
  for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
124
- if (this.pausedAgents.has(selfAid))
150
+ if (this.isAgentPaused(selfAid))
125
151
  return;
126
152
  sent = await this.mutexes.forKey(this.key(selfAid, targetSessionId)).runExclusive(async () => {
127
- if (this.pausedAgents.has(selfAid))
153
+ if (this.isAgentPaused(selfAid))
128
154
  return false;
129
155
  const current = this.store.get(selfAid, next.handoff_id);
130
156
  if (!current || current.state !== 'queued' || current.attention_required) {
@@ -167,7 +193,7 @@ export class HandoffDispatcher {
167
193
  return false;
168
194
  }
169
195
  });
170
- if (this.pausedAgents.has(selfAid))
196
+ if (this.isAgentPaused(selfAid))
171
197
  return;
172
198
  if (sent)
173
199
  break;
@@ -196,7 +222,7 @@ export class HandoffDispatcher {
196
222
  return `${selfAid}\u0000${targetSessionId}`;
197
223
  }
198
224
  scheduleExpiration(selfAid, instance) {
199
- if (this.queueTtlMs === undefined || this.pausedAgents.has(selfAid))
225
+ if (this.queueTtlMs === undefined || this.isAgentPaused(selfAid))
200
226
  return;
201
227
  const key = this.key(selfAid, instance.target_session_id);
202
228
  if (this.expirationTimers.has(key))
@@ -1,3 +1,4 @@
1
+ import { templateInstallationGate } from '../../agent-template/jobs.js';
1
2
  import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
2
3
  import { classifyAunPayloadForLog } from '../message/message-log.js';
3
4
  import { HandoffDispatcher } from './dispatcher.js';
@@ -70,6 +71,8 @@ export class HandoffRuntime {
70
71
  this.dispatcher = new HandoffDispatcher(store, this.mutexes, sender, options);
71
72
  }
72
73
  async createOutbound(input) {
74
+ if (templateInstallationGate(input.selfAid).blocked)
75
+ throw Object.assign(new Error('Team creation has not committed'), { code: 'TEAM_NOT_COMMITTED' });
73
76
  const operationSequence = ++this.lifecycleSequence;
74
77
  throwIfAborted(input.signal);
75
78
  const origin = await this.sessionManager.getSessionById(input.originSessionId);
@@ -271,6 +274,8 @@ export class HandoffRuntime {
271
274
  });
272
275
  }
273
276
  async enqueueOriginUnlocked(selfAid, handoffId, resultId, operationSequence, recovery) {
277
+ if (templateInstallationGate(selfAid).blocked)
278
+ return;
274
279
  if (recovery?.isCancelled?.())
275
280
  return;
276
281
  const instance = this.store.get(selfAid, handoffId);
@@ -630,6 +635,9 @@ export class HandoffRuntime {
630
635
  pauseAgent(selfAid) {
631
636
  this.dispatcher.pauseAgent(selfAid);
632
637
  }
638
+ holdAgent(selfAid, token) {
639
+ return this.dispatcher.holdAgent(selfAid, token);
640
+ }
633
641
  drainAgent(selfAid, timeoutMs) {
634
642
  return this.dispatcher.drainAgent(selfAid, timeoutMs);
635
643
  }
@@ -150,11 +150,15 @@ export function createHostSnapshotProvider(deps) {
150
150
  staticState.cachedAt = new Date().toISOString();
151
151
  writeStaticCache({ virtualization: staticState.virtualization, runtimes: staticState.runtimes, cachedAt: staticState.cachedAt });
152
152
  };
153
- const getSnapshot = () => {
153
+ const getHost = () => {
154
154
  const host = readHostInfo(versions.evolcore, resolvePaths().root, { runtimes: staticState.runtimes });
155
155
  host.os.virtualization = staticState.virtualization;
156
156
  // CPU 只有 daemon 有采样值;采样未启动时宁可给 null,也不给一个骗人的数字。
157
157
  host.hardware.cpuUsagePercent = deps.getSystemCpuPercent?.() ?? null;
158
+ return host;
159
+ };
160
+ const getSnapshot = () => {
161
+ const host = getHost();
158
162
  const agents = deps.agentRegistry.list();
159
163
  let totalPending = 0;
160
164
  let totalProcessing = 0;
@@ -201,7 +205,8 @@ export function createHostSnapshotProvider(deps) {
201
205
  },
202
206
  };
203
207
  };
204
- // 不阻塞启动:等当前微任务队列跑完再起子进程。
205
- setImmediate(() => { void probe(); });
206
- return { getSnapshot, refresh: probe };
208
+ // The daemon schedules these informational child processes after Ready.
209
+ if (deps.autoProbe !== false)
210
+ setImmediate(() => { void probe(); });
211
+ return { getHost, getSnapshot, refresh: probe };
207
212
  }
@@ -2,10 +2,11 @@ import { normalizeBaseagent, resolveAnthropicDirectConfig, resolveEcagentConfig,
2
2
  import { buildModelRequestHeaders } from '../../agents/request-identity.js';
3
3
  import { appendRequestQueryParams } from '../../agents/request-identity.js';
4
4
  import { appendRequestPath, appendV1RequestPath } from '../../agents/request-identity.js';
5
- import { resolveServiceSelection } from '../../config/providers.js';
5
+ import { assertExplicitProviderModelAllowed, resolveServiceSelection } from '../../config/providers.js';
6
6
  import { eligibleServiceFallbackModels } from '../model/model-fallback.js';
7
7
  import { RetryScheduler } from '../message/retry-scheduler.js';
8
8
  import { classifyError, ErrorType } from '../../utils/error-utils.js';
9
+ import { resolveProjectDefaultPath } from '../../utils/project-path.js';
9
10
  /** 决策判定用的系统提示词:把 state 与问题一起喂给通用模型,要求只回 JSON。 */
10
11
  const DECISION_SYSTEM_PROMPT = 'Evaluate the provided state against each question and its criteria. '
11
12
  + 'Return only a JSON object with an "answers" object keyed by question ID. '
@@ -66,6 +67,7 @@ async function completeServiceRequest(input) {
66
67
  let scheduler;
67
68
  while (true) {
68
69
  input.request.signal?.throwIfAborted();
70
+ assertExplicitProviderModelAllowed(connection.model, connection.providerId, connection.serviceType);
69
71
  try {
70
72
  return await input.complete(connection, input.request);
71
73
  }
@@ -141,6 +143,8 @@ export class AnthropicTextInferenceProvider {
141
143
  this.config = config;
142
144
  }
143
145
  async completeText(request) {
146
+ if (this.config.providerId)
147
+ assertExplicitProviderModelAllowed(request.model, this.config.providerId, this.config.serviceType ?? 'claude');
144
148
  const endpoint = this.config.providerId ? appendV1RequestPath(this.config.baseUrl, 'messages') : apiEndpoint(this.config.baseUrl, 'messages');
145
149
  const response = await fetch(appendRequestQueryParams(endpoint, this.config.queryParams), {
146
150
  method: 'POST',
@@ -183,6 +187,8 @@ export class OpenAITextInferenceProvider {
183
187
  this.config = config;
184
188
  }
185
189
  async completeText(request) {
190
+ if (this.config.providerId)
191
+ assertExplicitProviderModelAllowed(request.model, this.config.providerId, this.config.serviceType ?? 'codex');
186
192
  const endpoint = this.config.providerId ? appendRequestPath(this.config.baseUrl, 'responses') : apiEndpoint(this.config.baseUrl, 'responses');
187
193
  const response = await fetch(appendRequestQueryParams(endpoint, this.config.queryParams), {
188
194
  method: 'POST',
@@ -233,6 +239,10 @@ export class EcagentTextInferenceProvider {
233
239
  };
234
240
  }
235
241
  async completeText(request) {
242
+ if (this.config.providerId) {
243
+ const serviceType = this.config.providerServiceType ?? this.config.serviceType;
244
+ assertExplicitProviderModelAllowed(request.model, this.config.providerId, serviceType ?? 'ecagent', serviceType ? undefined : 'ecagent');
245
+ }
236
246
  const response = await fetch(appendRequestQueryParams(this.config.providerId ? appendRequestPath(this.config.baseUrl, 'chat/completions') : apiEndpoint(this.config.baseUrl, 'chat/completions'), this.config.queryParams), {
237
247
  method: 'POST',
238
248
  signal: request.signal,
@@ -277,7 +287,7 @@ export function createTextInferenceProvider(baseagent, config) {
277
287
  if (canonical === 'claude') {
278
288
  const resolved = resolveAnthropicDirectConfig(config.baseagents?.claude, {
279
289
  agentAid: config.aid,
280
- projectPath: config.projects?.defaultPath,
290
+ projectPath: resolveProjectDefaultPath(config.projects?.defaultPath),
281
291
  });
282
292
  return resolved ? new AnthropicTextInferenceProvider({
283
293
  ...resolved,
@@ -134,7 +134,9 @@ export class EcwebInitializationService {
134
134
  return ownerResolver.bind(aid, owner);
135
135
  }
136
136
  async verifiedOwner(state, force = true, source = 'initialization.operation') {
137
- const view = await this.ownership(state.controlAid, force, source);
137
+ return this.applyVerifiedOwner(state, await this.ownership(state.controlAid, force, source));
138
+ }
139
+ applyVerifiedOwner(state, view) {
138
140
  const owner = view.consensusStatus === 'consensus' && view.ownerAid && isValidAid(view.ownerAid)
139
141
  && view.ownerAid !== state.controlAid ? view.ownerAid : undefined;
140
142
  if (owner && state.ownerAid && state.ownerAid !== owner)
@@ -240,13 +242,23 @@ export class EcwebInitializationService {
240
242
  }
241
243
  }
242
244
  const bindingPending = !!state.binding?.ownerAid && ['pending', 'unknown'].includes(state.binding.status);
243
- const ownerAid = await this.verifiedOwner(state, bindingPending, bindingPending ? 'initialization.binding' : 'initialization.view');
245
+ const ownership = await this.ownership(state.controlAid, true, bindingPending ? 'initialization.binding' : 'initialization.view');
246
+ const ownerAid = this.applyVerifiedOwner(state, ownership);
247
+ const pending = bindingPending || ['requesting', 'submitted'].includes(ownership.requestStatus ?? '')
248
+ || (ownership.task?.operation === 'bind' && ownership.task.status === 'pending');
249
+ const ownershipStatus = ownerAid ? 'bound' : ownership.consensusStatus === 'single_sided' ? 'pending'
250
+ : ['unbound', 'released'].includes(ownership.consensusStatus) ? pending ? 'pending' : 'unbound' : 'unknown';
244
251
  const binding = state.binding;
245
252
  const scannable = binding?.status === 'created' && binding.expiresAt > this.now();
246
253
  return {
247
254
  status: state.step === 'ready' ? 'completed' : state.step === 'welcome' ? 'pending' : 'in_progress',
248
255
  step: ownerAid ? state.step === 'welcome' || state.step === 'binding' ? 'configuration' : state.step : state.step === 'welcome' ? 'welcome' : 'binding',
249
256
  controlAid: state.controlAid, ownerAid: ownerAid ?? null, updatedAt: state.updatedAt,
257
+ ownership: {
258
+ status: ownershipStatus, consensusStatus: ownership.consensusStatus,
259
+ code: ownership.refreshFailure?.code ?? null,
260
+ reason: ownership.refreshFailure?.reason ?? ownership.reason ?? null,
261
+ },
250
262
  binding: binding ? {
251
263
  id: binding.id, status: binding.status === 'bound' && !ownerAid ? 'unknown' : binding.status,
252
264
  expiresAt: binding.expiresAt,
@@ -420,8 +432,14 @@ export class EcwebInitializationService {
420
432
  return { status: 200, body: { success: true, data: await this.view(state) } };
421
433
  }
422
434
  if (input.method === 'POST' && (pathname === '/api/init/binding-sessions' || pathname === '/api/init/binding-sessions/refresh')) {
423
- if (await this.verifiedOwner(state))
424
- return { status: 200, body: { success: true, data: await this.view(state) } };
435
+ const data = await this.view(state);
436
+ const ownership = data.ownership;
437
+ if (ownership.status === 'bound')
438
+ return { status: 200, body: { success: true, data } };
439
+ if (ownership.status === 'unknown')
440
+ fail('OWNERSHIP_UNAVAILABLE', ownership.reason || '主机 Owner 状态暂时无法确认,请重试', 503);
441
+ if (ownership.status === 'pending')
442
+ return { status: 202, body: { success: true, data } };
425
443
  if (state.binding?.ownerAid)
426
444
  fail('BIND_PENDING', '绑定已提交,请先在 EVOL APP 确认并查询结果,不能重复创建', 409);
427
445
  if (pathname.endsWith('/refresh') || !state.binding || state.binding.expiresAt <= this.now()) {
@@ -8,7 +8,7 @@
8
8
  * - 4xx → 不重试,直接失败
9
9
  * - `--retries 0` → 只打一次
10
10
  */
11
- import { resolveProviderService } from '../../config/providers.js';
11
+ import { assertExplicitProviderModelAllowed, assertProviderModelAllowed, resolveProviderService } from '../../config/providers.js';
12
12
  import { InvokeError } from './types.js';
13
13
  import { resolveStyleRoute } from './style-router.js';
14
14
  export const DEFAULT_INVOKE_TIMEOUT_MS = 60_000;
@@ -56,8 +56,11 @@ export async function runWithRetry(executor, context, options) {
56
56
  }
57
57
  /** 解析 `--model` 缺省值:从 catalog 取第一个已启用模型。 */
58
58
  async function resolveDefaultModel(providerId, serviceType) {
59
+ const { getProviderCatalog } = await import('../model/model-catalog.js');
60
+ const connection = resolveProviderService(providerId, serviceType);
59
61
  const { getLocalProviderCatalog } = await import('../model/model-catalog.js');
60
- const snapshot = await getLocalProviderCatalog(providerId, serviceType, false);
62
+ const snapshot = connection.modelPolicy ? await getProviderCatalog(providerId, serviceType, false)
63
+ : await getLocalProviderCatalog(providerId, serviceType, false);
61
64
  const model = snapshot.models.find(entry => !entry.aliasFor) ?? snapshot.models[0];
62
65
  if (!model) {
63
66
  throw new InvokeError('MODEL_REQUIRED', `No model available for provider ${providerId} service ${serviceType}; pass --model`);
@@ -96,6 +99,14 @@ export async function executeInvoke(request) {
96
99
  }
97
100
  }
98
101
  }
102
+ if (connection.modelPolicy && (!request.dryRun || request.model)) {
103
+ try {
104
+ assertProviderModelAllowed(model, connection);
105
+ }
106
+ catch (error) {
107
+ return { ok: false, code: 'PROVIDER_MODEL_NOT_ALLOWED', error: error.message };
108
+ }
109
+ }
99
110
  let route;
100
111
  try {
101
112
  route = await resolveStyleRoute({ style: connection.style, serviceType: request.serviceType });
@@ -137,7 +148,14 @@ export async function executeInvoke(request) {
137
148
  outPath: request.outPath,
138
149
  };
139
150
  try {
140
- const result = await runWithRetry(route.executor, context, { timeoutMs, retries });
151
+ const executor = route.executor;
152
+ const result = await runWithRetry({
153
+ ...executor,
154
+ invoke: (current, options) => {
155
+ assertExplicitProviderModelAllowed(current.model, current.provider.providerId, current.provider.serviceType);
156
+ return executor.invoke(current, options);
157
+ },
158
+ }, context, { timeoutMs, retries });
141
159
  return {
142
160
  ok: true,
143
161
  provider: connection.providerId,
@@ -149,6 +167,9 @@ export async function executeInvoke(request) {
149
167
  };
150
168
  }
151
169
  catch (error) {
170
+ if (error.code === 'PROVIDER_MODEL_NOT_ALLOWED') {
171
+ return { ok: false, code: 'PROVIDER_MODEL_NOT_ALLOWED', error: error.message };
172
+ }
152
173
  if (error instanceof InvokeError) {
153
174
  return { ok: false, code: error.code, error: error.message, data: error.data };
154
175
  }
@@ -294,6 +294,9 @@ export function registerDaemonIpc({ lifecycle, ipcServer, agentRegistry, agentDe
294
294
  if (eventCenter) {
295
295
  ipcServer.setEventsOperationExecutor(createEventsOperationExecutor({
296
296
  registry: eventCenter,
297
+ // `pack add` 在单元还没起时也要能用——那是全新 agent 装第一个包的唯一路径。
298
+ // 缺了它,`resolveAid` 的 preferDefault 分支永远走不到,返回 NO_AGENT。
299
+ defaultAid: () => daemonAid,
297
300
  daemonAid: () => daemonAid,
298
301
  }));
299
302
  }
@@ -352,9 +355,11 @@ export function registerDaemonIpc({ lifecycle, ipcServer, agentRegistry, agentDe
352
355
  }
353
356
  export function createIpcStatusProvider(dependencies) {
354
357
  return () => {
358
+ // One fresh projection per request; channel and activity views share it.
359
+ const agents = dependencies.agentRegistry.list();
355
360
  const channels = {};
356
361
  const channelsByType = {};
357
- const channelRuntime = dependencies.getChannelRuntimeSnapshot?.();
362
+ const channelRuntime = dependencies.getChannelRuntimeSnapshot?.(agents);
358
363
  for (const instance of dependencies.channelInstances) {
359
364
  const name = instance.adapter.channelName;
360
365
  const channelType = instance.channelType || name;
@@ -380,7 +385,6 @@ export function createIpcStatusProvider(dependencies) {
380
385
  names.push(channelName);
381
386
  }
382
387
  const snapshot = dependencies.statsCollector.getSnapshot();
383
- const agents = dependencies.agentRegistry.list();
384
388
  const runtimeError = dependencies.getAgentRuntimeError();
385
389
  const build = dependencies.getBuildDiagnostics();
386
390
  return {
@@ -424,7 +428,7 @@ export function createIpcStatusProvider(dependencies) {
424
428
  ...(channelRuntime ? { channelRuntime } : {}),
425
429
  queue: { pending: dependencies.messageQueue.getGlobalQueueLength(), processing: dependencies.messageQueue.getGlobalProcessingCount() },
426
430
  ...(dependencies.getTriggerSummary ? { triggers: dependencies.getTriggerSummary() } : {}),
427
- ...(dependencies.getStatusSnapshot ? dependencies.getStatusSnapshot() : {}),
431
+ ...(dependencies.getStatusSnapshot ? dependencies.getStatusSnapshot(agents) : {}),
428
432
  ...(dependencies.getServiceProxySnapshot ? { serviceProxy: dependencies.getServiceProxySnapshot() } : {}),
429
433
  stats: {
430
434
  received: snapshot.lastHour.received,
@@ -1147,15 +1147,15 @@ export function createConsolidationSessionFinalizer({ sessionManager, getAgent,
1147
1147
  // 用 sessionId 无状态重算路径,不依赖 spec 传递——保证即使 spec 不传 runtimeDir
1148
1148
  // 字段,目录也能在会话结束后被清掉。
1149
1149
  if (sessionId) {
1150
- const runtimeDir = ensureSessionRuntimeDir(sessionId);
1151
- if (runtimeDir) {
1152
- try {
1150
+ try {
1151
+ const runtimeDir = ensureSessionRuntimeDir(sessionId);
1152
+ if (runtimeDir) {
1153
1153
  fs.rmSync(runtimeDir, { recursive: true, force: true });
1154
1154
  logger.debug(`[Memory] 清理 runtime 目录: ${runtimeDir}`);
1155
1155
  }
1156
- catch (cleanupError) {
1157
- logger.warn(`[Memory] runtime 目录清理失败(session=${sessionId}): ${cleanupError?.message}`);
1158
- }
1156
+ }
1157
+ catch (cleanupError) {
1158
+ logger.warn(`[Memory] runtime 目录清理失败(session=${sessionId}): ${cleanupError?.message}`);
1159
1159
  }
1160
1160
  }
1161
1161
  }