evolcore 0.0.43-test.8 → 0.0.46

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 (204) hide show
  1. package/CHANGELOG.md +75 -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 +13 -5
  12. package/dist/agents/codex/app-server-client.js +2 -4
  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/menu/client.js +142 -182
  18. package/dist/aun/rpc/client.js +33 -17
  19. package/dist/aun/service-proxy.js +6 -23
  20. package/dist/channels/aun.js +656 -112
  21. package/dist/cli/agent-create.js +37 -10
  22. package/dist/cli/agent-template.js +105 -84
  23. package/dist/cli/agent.js +31 -18
  24. package/dist/cli/daemon-commands.js +15 -17
  25. package/dist/cli/daemon-lifecycle-client.js +40 -18
  26. package/dist/cli/directory.js +12 -4
  27. package/dist/cli/ecmsg-gateway.js +5 -2
  28. package/dist/cli/events-command.js +2 -1
  29. package/dist/cli/init.js +50 -20
  30. package/dist/cli/integrity-command.js +2 -0
  31. package/dist/cli/managed-command-guard.js +20 -1
  32. package/dist/cli/menu-client.js +7 -5
  33. package/dist/cli/restart-monitor.js +33 -20
  34. package/dist/cli/services-command.js +28 -5
  35. package/dist/config/config-field-policy.js +24 -0
  36. package/dist/config/config-manager.js +20 -2
  37. package/dist/config/peer-book-store.js +152 -120
  38. package/dist/config/peer-role-resolver.js +24 -4
  39. package/dist/config/provider-identity-migration.js +1 -1
  40. package/dist/config/provider-identity.js +10 -4
  41. package/dist/config/provider-ipc-service.js +10 -2
  42. package/dist/config/provider-local-sync.js +2 -2
  43. package/dist/config/providers-config.js +95 -10
  44. package/dist/config/providers-import.js +4 -6
  45. package/dist/config/providers.js +14 -3
  46. package/dist/config/role-store.js +1 -1
  47. package/dist/config-store.js +9 -1
  48. package/dist/core/agent-application-service.js +56 -29
  49. package/dist/core/agent-create-status.js +3 -1
  50. package/dist/core/agent-creation-claim.js +1 -0
  51. package/dist/core/agent-ipc-registration.js +2 -2
  52. package/dist/core/agent-reload-coordinator.js +38 -1
  53. package/dist/core/agent-runtime.js +85 -38
  54. package/dist/core/auth/agent-delegation.js +5 -0
  55. package/dist/core/auth/operation-authorizer.js +1 -1
  56. package/dist/core/auth/operation-catalog.js +3 -3
  57. package/dist/core/bootstrap-service.js +3 -0
  58. package/dist/core/capability/capability-manager.js +3 -1
  59. package/dist/core/channel-loader.js +29 -3
  60. package/dist/core/channel-runtime.js +1 -1
  61. package/dist/core/command/agent-control.js +6 -5
  62. package/dist/core/command/agent-template-menu.js +32 -97
  63. package/dist/core/command/eventcenter-menu.js +61 -13
  64. package/dist/core/command/menu-catalog.js +11 -4
  65. package/dist/core/command/menu-handler.js +35 -8
  66. package/dist/core/command/menu-protocol.js +8 -16
  67. package/dist/core/command/skill-slash.js +6 -2
  68. package/dist/core/command/team-workspace-bootstrap.js +1 -2
  69. package/dist/core/command/team-workspace-management-store.js +83 -0
  70. package/dist/core/command/team-workspace-management.js +1 -2
  71. package/dist/core/command/team-workspace-team.js +26 -3
  72. package/dist/core/daemon-control.js +3 -4
  73. package/dist/core/daemon-lifecycle.js +146 -110
  74. package/dist/core/evolagent-registry.js +42 -0
  75. package/dist/core/evolagent.js +2 -1
  76. package/dist/core/file-integrity/read.js +9 -16
  77. package/dist/core/file-integrity/store.js +94 -34
  78. package/dist/core/handoff/dispatcher.js +33 -7
  79. package/dist/core/handoff/runtime.js +8 -0
  80. package/dist/core/inference/text-inference.js +12 -2
  81. package/dist/core/invoke/invoke-service.js +24 -3
  82. package/dist/core/ipc-registration.js +3 -0
  83. package/dist/core/message/aun-ipc-sender.js +109 -7
  84. package/dist/core/message/contact-admission.js +6 -2
  85. package/dist/core/message/message-bridge.js +13 -0
  86. package/dist/core/message/message-queue.js +131 -30
  87. package/dist/core/message/pending-hints.js +8 -0
  88. package/dist/core/message/response-engine.js +48 -2
  89. package/dist/core/message/send-routing.js +3 -12
  90. package/dist/core/model/catalog-service.js +13 -0
  91. package/dist/core/model/model-catalog.js +57 -18
  92. package/dist/core/pack-auth.js +163 -31
  93. package/dist/core/pack-install.js +42 -1
  94. package/dist/{services/ledger.js → core/pack-ledger.js} +17 -6
  95. package/dist/core/permission/ec-command-parser.js +3 -1
  96. package/dist/core/permission/shell-environment.js +23 -0
  97. package/dist/core/rate-window.js +6 -1
  98. package/dist/core/session/session-idle-monitor.js +0 -1
  99. package/dist/core/session/session-manager.js +14 -0
  100. package/dist/core/session/session-title.js +26 -6
  101. package/dist/core/skill/index-generator.js +3 -4
  102. package/dist/core/thread/thread-service.js +0 -1
  103. package/dist/core/thread/topic-id.js +8 -0
  104. package/dist/directory/owner-directory-admission.js +17 -0
  105. package/dist/directory/owner-directory-cache.js +3 -1
  106. package/dist/directory/owner-directory-markdown.js +145 -23
  107. package/dist/directory/owner-directory-policy.js +23 -0
  108. package/dist/directory/owner-directory-query-operation.js +20 -6
  109. package/dist/directory/owner-directory-search.js +47 -0
  110. package/dist/eck/message-renderer.js +171 -32
  111. package/dist/ecweb/basic-settings-service.js +7 -3
  112. package/dist/ecweb/providers-service.js +17 -10
  113. package/dist/ecweb/runtime/lifecycle.js +1 -1
  114. package/dist/ecweb/runtime/supervisor.js +77 -35
  115. package/dist/event-center/admission-materializer.js +1 -1
  116. package/dist/event-center/bus-gate.js +48 -4
  117. package/dist/event-center/bus-host.js +3 -3
  118. package/dist/event-center/center-config.js +57 -28
  119. package/dist/event-center/dispatcher.js +8 -0
  120. package/dist/event-center/event-log.js +69 -27
  121. package/dist/event-center/index-generator.js +6 -1
  122. package/dist/event-center/ipc-operation.js +66 -25
  123. package/dist/event-center/pack-loader.js +12 -55
  124. package/dist/event-center/pack-manager.js +5 -3
  125. package/dist/event-center/registry.js +48 -52
  126. package/dist/event-center/runtime.js +219 -81
  127. package/dist/event-center/script-runner.js +18 -7
  128. package/dist/event-center/types.js +9 -1
  129. package/dist/event-center/validation.js +33 -4
  130. package/dist/index.js +96 -42
  131. package/dist/ipc.js +33 -7
  132. package/dist/product.js +1 -0
  133. package/dist/proxy/manager.js +52 -11
  134. package/dist/proxy/service-supervisor.js +265 -67
  135. package/dist/services/dispatcher.js +26 -3
  136. package/dist/services/idempotency.js +128 -0
  137. package/dist/services/identity.js +3 -27
  138. package/dist/services/index-generator.js +5 -1
  139. package/dist/services/index.js +244 -45
  140. package/dist/services/ipc-operation.js +164 -20
  141. package/dist/services/pack-manager.js +37 -9
  142. package/dist/services/router.js +100 -31
  143. package/dist/services/script-runner.js +15 -4
  144. package/dist/services/service-payload.js +50 -2
  145. package/dist/services/validation.js +107 -3
  146. package/dist/trigger/scheduler.js +14 -4
  147. package/dist/trigger/script-sandbox.js +39 -2
  148. package/dist/utils/cross-platform.js +35 -11
  149. package/dist/utils/error-utils.js +13 -1
  150. package/dist/utils/instance-registry.js +33 -35
  151. package/dist/utils/process-introspect.js +35 -20
  152. package/dist/utils/project-path.js +47 -3
  153. package/dist/utils/windows-shell-trust.js +174 -68
  154. package/kits/docs/context-assembly.md +3 -3
  155. package/kits/docs/evolcore/agent.md +28 -10
  156. package/kits/docs/evolcore/config.md +22 -0
  157. package/kits/docs/evolcore/directory.md +46 -12
  158. package/kits/docs/evolcore/event-center.md +6 -6
  159. package/kits/docs/evolcore/group-collaboration.md +1 -1
  160. package/kits/docs/evolcore/menu-client.md +7 -5
  161. package/kits/docs/evolcore/menu-protocol.md +5 -3
  162. package/kits/docs/evolcore/msg.md +10 -3
  163. package/kits/docs/evolcore/provider.md +7 -3
  164. package/kits/docs/evolcore/services.md +145 -12
  165. package/kits/docs/evolcore/thread-chain.md +17 -9
  166. package/kits/docs/prompt-loading-architecture.md +4 -4
  167. package/kits/eck_message_manifest.json +46 -3
  168. package/kits/rules/04-relation.md +10 -2
  169. package/kits/rules/06-channel.md +2 -1
  170. package/kits/schemas/providers.schema.2.json +1 -0
  171. package/kits/skills/ec-group/SKILL.md +4 -0
  172. package/kits/skills/ec-skill/scripts/cli.mjs +1 -1
  173. package/kits/skills/ec-skill/scripts/skill.mjs +13 -2
  174. package/kits/skills/thread-ops/SKILL.md +8 -5
  175. package/kits/templates/message-fragments/group-batch-item.md +3 -0
  176. package/kits/templates/message-fragments/group-batch.md +1 -0
  177. package/kits/templates/message-fragments/item-group.md +4 -0
  178. package/kits/templates/message-fragments/item-private.md +4 -0
  179. package/kits/templates/message-fragments/thread-context.md +1 -1
  180. package/kits/templates/system-fragments/commands.md +5 -5
  181. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  182. package/kits/templates/system-fragments/relation.md +11 -7
  183. package/package.json +3 -2
  184. package/scripts/agent-template/index.mjs +9 -4
  185. package/scripts/agent-template/inspect.mjs +16 -9
  186. package/scripts/agent-template/shared/plan.mjs +3 -33
  187. package/scripts/agent-template/shared/template-contract.mjs +186 -3
  188. package/scripts/agent-template/shared/template-package.mjs +119 -10
  189. package/scripts/agent-template/shared/template-runtime.mjs +49 -6
  190. package/scripts/agent-template/shared/template.mjs +5 -5
  191. package/scripts/agent-template/team-pack.mjs +245 -0
  192. package/scripts/agent-template/team-preview.mjs +111 -0
  193. package/scripts/aid-batch/identity-batch.mjs +143 -0
  194. package/dist/ability/versions.js +0 -32
  195. package/dist/aun/model-headers.js +0 -17
  196. package/dist/channels/builtin-plugins.js +0 -19
  197. package/dist/core/command/team-workspace-initializer.js +0 -2
  198. package/dist/core/command/team-workspace-job-store.js +0 -88
  199. package/dist/core/command/team-workspace-management-service.js +0 -2
  200. package/dist/core/contact-bind-registry.js +0 -27
  201. package/dist/event-center/ledger.js +0 -52
  202. package/dist/services/reply.js +0 -55
  203. package/kits/templates/message-fragments/item.md +0 -3
  204. 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
  }
@@ -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,
@@ -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
  }