evolcore 0.0.46 → 0.0.48

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 (237) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +43 -18
  8. package/dist/agents/codex/app-server-client.js +32 -23
  9. package/dist/agents/codex-runner.js +31 -16
  10. package/dist/agents/ecagent-runner.js +7 -4
  11. package/dist/agents/gemini-runner.js +5 -2
  12. package/dist/agents/runner-types.js +5 -21
  13. package/dist/aun/aid/agentmd.js +5 -1
  14. package/dist/aun/group/fs-download.js +1 -1
  15. package/dist/aun/service-proxy.js +4 -2
  16. package/dist/build-identity.json +1 -0
  17. package/dist/channels/aun.js +100 -32
  18. package/dist/channels/daemon.js +10 -26
  19. package/dist/cli/aun-commands.js +86 -51
  20. package/dist/cli/code-stats.js +19 -8
  21. package/dist/cli/command-log.js +1 -1
  22. package/dist/cli/daemon-commands.js +65 -76
  23. package/dist/cli/daemon-lifecycle-client.js +17 -3
  24. package/dist/cli/directory.js +7 -1
  25. package/dist/cli/ecmsg-gateway.js +5 -2
  26. package/dist/cli/index.js +2 -8
  27. package/dist/cli/init-channel.js +6 -8
  28. package/dist/cli/init.js +74 -46
  29. package/dist/cli/invoke-command.js +1 -1
  30. package/dist/cli/provider-command.js +74 -13
  31. package/dist/cli/restart-monitor.js +104 -28
  32. package/dist/cli/role.js +61 -17
  33. package/dist/cli/stats.js +3 -3
  34. package/dist/cli/task-context.js +83 -15
  35. package/dist/cli/thread-command.js +16 -51
  36. package/dist/cli/upgrade-command.js +4 -2
  37. package/dist/config/boot-log.js +3 -9
  38. package/dist/config/builtin-roles.js +5 -7
  39. package/dist/config/config-manager.js +31 -23
  40. package/dist/config/daemon-services.js +30 -3
  41. package/dist/config/gateway-config.js +2 -2
  42. package/dist/config/invoke-ipc-service.js +6 -4
  43. package/dist/config/peer-bind-code.js +3 -4
  44. package/dist/config/peer-book-store.js +59 -218
  45. package/dist/config/peer-book.js +26 -27
  46. package/dist/config/peer-role-resolver.js +16 -1
  47. package/dist/config/provider-identity-migration.js +161 -6
  48. package/dist/config/provider-ipc-service.js +56 -11
  49. package/dist/config/provider-menu-request.js +24 -5
  50. package/dist/config/provider-templates.js +127 -0
  51. package/dist/config/providers-config.js +59 -8
  52. package/dist/config/providers-management.js +467 -49
  53. package/dist/config/role-command-service.js +248 -1
  54. package/dist/config/schema-migration.js +228 -20
  55. package/dist/config/schema-registry.js +6 -2
  56. package/dist/core/agent-application-service.js +6 -1
  57. package/dist/core/agent-runtime.js +10 -5
  58. package/dist/core/auth/agent-delegation.js +10 -4
  59. package/dist/core/auth/auth-gateway.js +2 -1
  60. package/dist/core/auth/delegation-authorization.js +3 -0
  61. package/dist/core/auth/delegation-diagnostics.js +56 -15
  62. package/dist/core/auth/operation-authorizer.js +26 -1
  63. package/dist/core/auth/operation-catalog.js +28 -64
  64. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  65. package/dist/core/channel-loader.js +18 -0
  66. package/dist/core/command/agent-control.js +32 -0
  67. package/dist/core/command/command-handler.js +81 -85
  68. package/dist/core/command/menu-catalog.js +1 -0
  69. package/dist/core/command/menu-handler.js +65 -153
  70. package/dist/core/command/menu-protocol.js +7 -1
  71. package/dist/core/command/provider-menu.js +13 -3
  72. package/dist/core/command/role-menu.js +47 -23
  73. package/dist/core/command/slash-handler.js +30 -49
  74. package/dist/core/command/team-workspace-items.js +81 -12
  75. package/dist/core/command/team-workspace-team.js +9 -71
  76. package/dist/core/command/topic-slash.js +9 -30
  77. package/dist/core/daemon-bootstrap.js +19 -10
  78. package/dist/core/daemon-control.js +8 -10
  79. package/dist/core/daemon-lifecycle.js +50 -40
  80. package/dist/core/evolagent-registry.js +22 -3
  81. package/dist/core/file-integrity/store.js +2 -0
  82. package/dist/core/handoff/runtime.js +37 -1
  83. package/dist/core/host-snapshot.js +9 -4
  84. package/dist/core/inference/text-inference.js +3 -1
  85. package/dist/core/initialization/service.js +31 -8
  86. package/dist/core/interaction-router.js +3 -0
  87. package/dist/core/invoke/executors/text.js +72 -19
  88. package/dist/core/ipc-registration.js +6 -4
  89. package/dist/core/memory/consolidation.js +6 -6
  90. package/dist/core/message/aun-ipc-sender.js +165 -55
  91. package/dist/core/message/im-renderer.js +1 -1
  92. package/dist/core/message/message-bridge.js +51 -334
  93. package/dist/core/message/message-log.js +5 -0
  94. package/dist/core/message/message-queue.js +22 -0
  95. package/dist/core/message/message-utils.js +8 -0
  96. package/dist/core/message/response-engine.js +429 -116
  97. package/dist/core/message/send-routing.js +5 -1
  98. package/dist/core/model/catalog-service.js +31 -11
  99. package/dist/core/model/model-capabilities.js +22 -4
  100. package/dist/core/model/model-catalog.js +1 -0
  101. package/dist/core/ownership/owner-resolver.js +355 -60
  102. package/dist/core/permission/protected-paths.js +6 -6
  103. package/dist/core/relation/peer-identity.js +28 -2
  104. package/dist/core/relation/same-owner-proof.js +81 -111
  105. package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
  106. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  107. package/dist/core/session/session-file-health.js +49 -14
  108. package/dist/core/session/session-fs-store.js +91 -35
  109. package/dist/core/session/session-manager.js +68 -24
  110. package/dist/core/session/session-mapper.js +14 -34
  111. package/dist/core/session/session-transcript.js +5 -1
  112. package/dist/core/task/task-activity-store.js +84 -0
  113. package/dist/core/task/task-image-resources.js +1 -1
  114. package/dist/core/task/task-recovery-service.js +12 -0
  115. package/dist/core/thread/command-parser.js +7 -12
  116. package/dist/core/thread/thread-context-storage.js +3 -2
  117. package/dist/core/thread/thread-operation.js +2 -13
  118. package/dist/core/thread/thread-service.js +15 -46
  119. package/dist/directory/owner-directory-admission.js +1 -1
  120. package/dist/directory/owner-directory-cache.js +45 -28
  121. package/dist/directory/owner-directory-markdown.js +13 -1
  122. package/dist/directory/owner-directory-query-operation.js +29 -3
  123. package/dist/directory/owner-directory-remarks.js +11 -3
  124. package/dist/eck/message-renderer.js +84 -24
  125. package/dist/ecweb/basic-settings-service.js +3 -1
  126. package/dist/ecweb/message-context-service.js +1 -1
  127. package/dist/ecweb/pairing.js +4 -3
  128. package/dist/ecweb/providers-service.js +26 -1
  129. package/dist/ecweb/runtime/lifecycle.js +82 -23
  130. package/dist/ecweb/runtime/proxy-access.js +74 -0
  131. package/dist/ecweb/runtime/supervisor.js +6 -17
  132. package/dist/event-center/registry.js +13 -2
  133. package/dist/event-center/runtime.js +103 -11
  134. package/dist/event-center/script-runner.js +5 -5
  135. package/dist/index.js +129 -93
  136. package/dist/ipc.js +15 -3
  137. package/dist/outputs/events.js +62 -0
  138. package/dist/outputs/protocol.js +102 -0
  139. package/dist/outputs/service.js +279 -0
  140. package/dist/paths.js +3 -0
  141. package/dist/proxy/manager.js +43 -13
  142. package/dist/services/index.js +89 -4
  143. package/dist/services/ipc-operation.js +4 -15
  144. package/dist/services/pack-manager.js +12 -1
  145. package/dist/services/router.js +21 -6
  146. package/dist/services/script-runner.js +5 -4
  147. package/dist/services/validation.js +1 -1
  148. package/dist/stats/budget.js +1 -1
  149. package/dist/stats/db.js +19 -0
  150. package/dist/stats/index.js +1 -1
  151. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  152. package/dist/stats/normalizer.js +2 -0
  153. package/dist/stats/query.js +35 -27
  154. package/dist/stats/role-budget.js +5 -2
  155. package/dist/stats/writer.js +10 -6
  156. package/dist/trigger/audit.js +7 -0
  157. package/dist/trigger/authorization.js +105 -11
  158. package/dist/trigger/feedback.js +10 -0
  159. package/dist/trigger/history.js +37 -11
  160. package/dist/trigger/ipc-service.js +12 -1
  161. package/dist/trigger/manager.js +1 -0
  162. package/dist/trigger/scheduler.js +11 -5
  163. package/dist/trigger/script-executor.js +2 -1
  164. package/dist/trigger/script-sandbox.js +9 -3
  165. package/dist/trigger/state.js +7 -0
  166. package/dist/trigger/validation.js +22 -0
  167. package/dist/utils/aid-bind.js +155 -18
  168. package/dist/utils/atomic-write.js +3 -3
  169. package/dist/utils/cross-platform.js +97 -31
  170. package/dist/utils/error-dict.json +94 -4
  171. package/dist/utils/error-utils.js +40 -4
  172. package/dist/utils/evolcore-version.js +36 -65
  173. package/dist/utils/instance-registry.js +61 -0
  174. package/dist/utils/msg-diag.js +1 -0
  175. package/dist/utils/process-introspect.js +158 -8
  176. package/dist/utils/process-tree.js +50 -2
  177. package/dist/utils/upgrade-jobs.js +4 -4
  178. package/dist/utils/windows-shell-trust.js +2 -0
  179. package/dist/workbench/protocol.js +80 -0
  180. package/dist/workbench/service.js +359 -0
  181. package/ecagent/dist/types.d.ts +6 -2
  182. package/kits/docs/context-assembly.md +1 -1
  183. package/kits/docs/evolcore/INDEX.md +2 -2
  184. package/kits/docs/evolcore/aid.md +3 -1
  185. package/kits/docs/evolcore/config.md +12 -0
  186. package/kits/docs/evolcore/directory.md +22 -3
  187. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  188. package/kits/docs/evolcore/model.md +10 -0
  189. package/kits/docs/evolcore/peer.md +19 -65
  190. package/kits/docs/evolcore/provider.md +133 -5
  191. package/kits/docs/evolcore/role.md +80 -0
  192. package/kits/docs/evolcore/services.md +6 -6
  193. package/kits/docs/evolcore/team-workspace.md +1 -1
  194. package/kits/docs/evolcore/thread-chain.md +14 -15
  195. package/kits/docs/evolcore/tool-authorization.md +5 -0
  196. package/kits/docs/evolcore/trigger.md +10 -0
  197. package/kits/eck_message_manifest.json +12 -0
  198. package/kits/provider-templates.json +1213 -0
  199. package/kits/rules/04-relation.md +3 -3
  200. package/kits/schemas/_meta.json +14 -2
  201. package/kits/schemas/contact-book.schema.4.json +52 -0
  202. package/kits/schemas/providers.schema.3.json +200 -0
  203. package/kits/skills/.switches.json +4 -0
  204. package/kits/skills/ability/references/calling.md +1 -1
  205. package/kits/skills/ec-group/SKILL.md +2 -2
  206. package/kits/skills/ec-identity/SKILL.md +19 -72
  207. package/kits/skills/ec-provider/SKILL.md +221 -0
  208. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  209. package/kits/skills/ec-trigger/SKILL.md +1 -1
  210. package/kits/skills/thread-ops/SKILL.md +34 -21
  211. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  212. package/kits/templates/message-fragments/group-batch.md +1 -1
  213. package/kits/templates/message-fragments/inject-default.md +1 -1
  214. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  215. package/kits/templates/message-fragments/item-group.md +1 -1
  216. package/kits/templates/message-fragments/item-private.md +1 -1
  217. package/kits/templates/message-fragments/thread-context.md +1 -1
  218. package/kits/templates/message-fragments/trigger-session.md +1 -1
  219. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  220. package/kits/templates/roles/admin.json +2 -19
  221. package/kits/templates/roles/member.json +0 -3
  222. package/kits/templates/system-fragments/baseagent.md +6 -0
  223. package/kits/templates/system-fragments/commands.md +3 -3
  224. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  225. package/kits/templates/system-fragments/relation.md +1 -1
  226. package/kits/templates/system-fragments/thread.md +6 -5
  227. package/package.json +6 -4
  228. package/scripts/agent-template/inspect.mjs +4 -1
  229. package/scripts/agent-template/shared/common.mjs +2 -3
  230. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  231. package/scripts/agent-template/shared/template-package.mjs +9 -2
  232. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  233. package/scripts/agent-template/team-pack.mjs +6 -3
  234. package/dist/cli/peer.js +0 -127
  235. package/dist/config/peer-operation-service.js +0 -132
  236. package/dist/config/peer-request-service.js +0 -532
  237. package/dist/core/command/connect-menu.js +0 -624
@@ -1,28 +1,165 @@
1
- import { randomUUID } from 'crypto';
1
+ import { randomBytes, randomUUID, timingSafeEqual, createHash } from 'crypto';
2
+ import { loadAgent } from '../config-store.js';
3
+ import { isValidAid } from '../aun/aid/validation.js';
4
+ import { ownerResolver } from '../core/ownership/owner-resolver.js';
5
+ import { readInstalledEvolcoreVersion } from './evolcore-version.js';
2
6
  const BIND_TTL_MS = 10 * 60 * 1000;
3
- const deferredMessage = 'Evol App ownership binding is deferred; use ec aid bind <ownerAid> [--subject <subjectAid>]';
4
7
  export class BindService {
5
- constructor(_options) { }
6
- startCleanup() { }
7
- stopCleanup() { }
8
- begin(_request) {
9
- return {
10
- ok: true,
11
- taskId: randomUUID(),
12
- qrData: {},
13
- expiresAt: Date.now() + BIND_TTL_MS,
8
+ options;
9
+ sessions = new Map();
10
+ cleanup;
11
+ constructor(options) {
12
+ this.options = options;
13
+ }
14
+ startCleanup() {
15
+ if (this.cleanup)
16
+ return;
17
+ this.cleanup = setInterval(() => this.expireSessions(), 60_000);
18
+ this.cleanup.unref?.();
19
+ }
20
+ stopCleanup() { clearInterval(this.cleanup); this.cleanup = undefined; }
21
+ begin(request) {
22
+ this.expireSessions();
23
+ if (!['daemon', 'agent'].includes(request.bindType) || 'ownerMode' in request) {
24
+ return { ok: false, code: 'INVALID_ARGUMENT', error: 'Select a daemon or Agent binding; use Ownership transfer to replace an Owner' };
25
+ }
26
+ const subjectAid = request.bindType === 'daemon' ? this.options.receiverAid : request.targetAid;
27
+ if (!subjectAid || !isValidAid(subjectAid)
28
+ || (request.bindType === 'agent' && (subjectAid === this.options.receiverAid || !loadAgent(subjectAid)))) {
29
+ return { ok: false, code: 'SUBJECT_UNAVAILABLE', error: 'Binding requires a local subject AID' };
30
+ }
31
+ if (this.sessions.size >= 128)
32
+ return { ok: false, code: 'BIND_CAPACITY', error: 'Too many pending binding sessions' };
33
+ const ttl = request.ttlMs ?? BIND_TTL_MS;
34
+ if (!Number.isFinite(ttl) || ttl <= 0 || ttl > BIND_TTL_MS) {
35
+ return { ok: false, code: 'INVALID_ARGUMENT', error: 'Binding TTL must be between 1 and 600000 milliseconds' };
36
+ }
37
+ const session = {
38
+ id: randomUUID(), token: randomBytes(32).toString('base64url'), bindType: request.bindType,
39
+ subjectAid, expiresAt: Date.now() + ttl, status: 'pending',
14
40
  };
41
+ this.sessions.set(session.id, session);
42
+ return { ok: true, taskId: session.id, expiresAt: session.expiresAt, qrData: {
43
+ type: 'evolcore.bind', version: readInstalledEvolcoreVersion(),
44
+ platform: process.platform === 'win32' ? 'windows' : process.platform,
45
+ bindType: session.bindType, subjectAid, receiverAid: this.options.receiverAid,
46
+ token: session.token, expiresAt: session.expiresAt,
47
+ } };
15
48
  }
16
- status(_taskId) {
17
- return { ok: false, code: 'OWNERSHIP_APP_DEFERRED', error: deferredMessage };
49
+ async status(taskId) {
50
+ this.expireSessions();
51
+ const session = this.sessions.get(taskId);
52
+ if (!session)
53
+ return { ok: false, code: 'BIND_SESSION_INVALID', error: 'Binding session does not exist' };
54
+ if (session.status !== 'cancelled' && session.ownerAid) {
55
+ try {
56
+ const state = await ownerResolver.status(session.subjectAid, { force: true });
57
+ session.status = this.confirmsOwner(session, state) ? 'bound' : 'pending';
58
+ }
59
+ catch (error) {
60
+ session.status = 'pending';
61
+ const code = error?.code;
62
+ return { ok: false,
63
+ code: typeof code === 'string' && /^[A-Za-z0-9_]{1,64}$/.test(code) ? code : 'OWNERSHIP_UNAVAILABLE',
64
+ error: 'Unable to verify current Ownership consensus' };
65
+ }
66
+ }
67
+ return { ok: true, taskId, status: session.status,
68
+ ...(session.status === 'bound' ? { boundAid: session.ownerAid } : {}) };
18
69
  }
19
- cancel(_taskId) {
20
- return { ok: false, code: 'OWNERSHIP_APP_DEFERRED', error: deferredMessage };
70
+ cancel(taskId) {
71
+ const session = this.sessions.get(taskId);
72
+ if (!session)
73
+ return { ok: false, code: 'BIND_SESSION_INVALID', error: 'Binding session does not exist' };
74
+ if (session.ownerAid)
75
+ return { ok: false, code: 'BIND_PENDING', error: 'An accepted Ownership request cannot be cancelled by cancelling its QR session' };
76
+ session.status = 'cancelled';
77
+ return { ok: true, taskId, status: 'cancelled' };
21
78
  }
22
- async handleRequest(payload, _fromAid) {
79
+ async handleRequest(payload, fromAid, encrypted = false) {
23
80
  if (payload?.type !== 'bind.request')
24
81
  return null;
25
- return { type: 'bind.response', bindType: payload.bindType === 'agent' ? 'agent' : 'daemon', success: false,
26
- error: { code: 'OWNERSHIP_APP_DEFERRED', message: deferredMessage } };
82
+ this.expireSessions();
83
+ const response = (code, message) => ({
84
+ type: 'bind.response', bindType: payload.bindType === 'agent' ? 'agent' : 'daemon', success: false,
85
+ ...(typeof payload.creationId === 'string' && payload.creationId.length <= 128 ? { creationId: payload.creationId } : {}),
86
+ error: { code, message },
87
+ });
88
+ if (!encrypted)
89
+ return response('ENCRYPTION_REQUIRED', 'Binding requires an encrypted identity message');
90
+ if (!isValidAid(fromAid))
91
+ return response('INVALID_SENDER', 'Binding requires an authenticated sender AID');
92
+ const session = [...this.sessions.values()].find(item => typeof payload.token === 'string'
93
+ && Buffer.byteLength(payload.token) === Buffer.byteLength(item.token)
94
+ && timingSafeEqual(Buffer.from(payload.token), Buffer.from(item.token)));
95
+ if (!session) {
96
+ return await this.options.handleAppBindRequest?.(payload, fromAid, encrypted)
97
+ ?? response('BIND_SESSION_INVALID', 'Binding session is invalid; refresh the QR code');
98
+ }
99
+ if (payload.bindType !== session.bindType
100
+ || (payload.subjectAid !== undefined && payload.subjectAid !== session.subjectAid)
101
+ || (payload.targetAid !== undefined && payload.targetAid !== session.subjectAid)) {
102
+ return response('BIND_CONFLICT', 'Binding subject does not match the QR session');
103
+ }
104
+ if (typeof payload.creationId !== 'string' || !payload.creationId.trim() || payload.creationId.length > 128) {
105
+ return response('INVALID_CREATION_ID', 'Binding requires a creationId');
106
+ }
107
+ if (payload.timestamp !== undefined && (typeof payload.timestamp !== 'number' || !Number.isFinite(payload.timestamp)
108
+ || Math.abs(Date.now() - payload.timestamp) > BIND_TTL_MS))
109
+ return response('REQUEST_EXPIRED', 'Binding request has expired');
110
+ const ownerAid = fromAid.toLowerCase();
111
+ const fingerprint = createHash('sha256').update(JSON.stringify({
112
+ ownerAid, creationId: payload.creationId, bindType: payload.bindType,
113
+ subjectAid: session.subjectAid, clientName: payload.clientName, deviceName: payload.deviceName,
114
+ platform: payload.platform, appVersion: payload.appVersion, timestamp: payload.timestamp,
115
+ })).digest('hex');
116
+ if (session.ownerAid) {
117
+ if (session.ownerAid !== ownerAid || session.fingerprint !== fingerprint)
118
+ return response('BIND_CONFLICT', 'Binding request conflicts with an accepted request');
119
+ return session.flight ?? session.response;
120
+ }
121
+ if (session.status !== 'pending' || session.expiresAt <= Date.now())
122
+ return response('BIND_SESSION_EXPIRED', 'Binding QR session is no longer valid');
123
+ session.ownerAid = ownerAid;
124
+ session.creationId = payload.creationId;
125
+ session.fingerprint = fingerprint;
126
+ const work = async () => {
127
+ try {
128
+ const state = await ownerResolver.bind(session.subjectAid, ownerAid, () => session.status !== 'cancelled', () => { session.submissionStarted = true; });
129
+ const bound = this.confirmsOwner(session, state);
130
+ session.status = bound ? 'bound' : 'pending';
131
+ return { type: 'bind.response', bindType: session.bindType, creationId: session.creationId,
132
+ success: true, subjectAid: session.subjectAid, ownerAid, status: bound ? 'bound' : 'pending' };
133
+ }
134
+ catch (error) {
135
+ if (session.submissionStarted)
136
+ return { type: 'bind.response', bindType: session.bindType,
137
+ creationId: session.creationId, success: true, subjectAid: session.subjectAid, ownerAid, status: 'unknown' };
138
+ session.ownerAid = undefined;
139
+ session.fingerprint = undefined;
140
+ const code = error?.code;
141
+ return response(typeof code === 'string' && /^[A-Za-z0-9_]{1,64}$/.test(code) ? code : 'BIND_FAILED', 'Binding preparation failed; query Ownership before retrying');
142
+ }
143
+ };
144
+ session.flight = work();
145
+ try {
146
+ return session.response = await session.flight;
147
+ }
148
+ finally {
149
+ session.flight = undefined;
150
+ }
151
+ }
152
+ confirmsOwner(session, state) {
153
+ return state.consensusStatus === 'consensus' && state.ownerAid === session.ownerAid
154
+ && state.consensus?.sub_aid === session.subjectAid && state.consensus.lock === 'locked'
155
+ && state.authorizationStatus === 'verified' && !state.refreshFailure;
156
+ }
157
+ expireSessions() {
158
+ for (const [id, session] of this.sessions) {
159
+ if (!session.ownerAid && session.status === 'pending' && session.expiresAt <= Date.now())
160
+ session.status = 'expired';
161
+ if (!session.flight && session.expiresAt + BIND_TTL_MS <= Date.now())
162
+ this.sessions.delete(id);
163
+ }
27
164
  }
28
165
  }
@@ -324,8 +324,8 @@ export async function atomicReplaceJson(file, value) {
324
324
  const retryableCodes = new Set(['EPERM', 'EACCES', 'EBUSY']);
325
325
  const delays = [10, 25, 50, 100];
326
326
  const pause = new Int32Array(new SharedArrayBuffer(4));
327
- /** Retry brief file-handle contention without opening or deleting the live file. */
328
- export function atomicReplaceFile(source, destination) {
327
+ /** Retry brief contention; disable allowInPlaceFallback when replacement must remain atomic. */
328
+ export function atomicReplaceFile(source, destination, options = {}) {
329
329
  let lastError;
330
330
  for (let attempt = 0;; attempt += 1) {
331
331
  try {
@@ -341,7 +341,7 @@ export function atomicReplaceFile(source, destination) {
341
341
  }
342
342
  }
343
343
  const code = lastError?.code;
344
- if (process.platform === 'win32' && code === 'EPERM') {
344
+ if (options.allowInPlaceFallback !== false && process.platform === 'win32' && code === 'EPERM') {
345
345
  // Some Windows file projections deny renaming an open JSON target. Keep
346
346
  // its inode and use atomicWrite's hot-backup/stable-write fallback instead.
347
347
  atomicWrite(destination, fs.readFileSync(source, 'utf8'));
@@ -4,7 +4,7 @@ import { createRequire } from 'module';
4
4
  import { execFileSync, execFile, spawn, spawnSync } from 'child_process';
5
5
  import { promisify, TextDecoder } from 'util';
6
6
  import fs from 'fs';
7
- import { getProcessStartTime, parseCimDate } from './process-introspect.js';
7
+ import { createWindowsProcessQuery, getProcessSnapshot, getProcessStartTime, parseCimDate } from './process-introspect.js';
8
8
  import { requireTrustedWindowsCmdPath, requireTrustedWindowsCmdPathAsync, WindowsShellTrustError, } from './windows-shell-trust.js';
9
9
  import { logger } from './logger.js';
10
10
  const execFileAsync = promisify(execFile);
@@ -506,21 +506,21 @@ export async function launchMonitorAndConfirm(args, env, isAliveInRegistry, hasO
506
506
  catch (error) {
507
507
  diagnostic(`Spawn callback failed: ${error.message}`);
508
508
  }
509
- const accepted = () => isAliveInRegistry(childPid) || hasOtherLiveMonitor(childPid);
509
+ const accepted = async () => await isAliveInRegistry(childPid) || await hasOtherLiveMonitor(childPid);
510
510
  const deadline = Date.now() + (options.timeoutMs ?? 15_000);
511
511
  while (Date.now() < deadline) {
512
512
  await new Promise(resolve => setTimeout(resolve, 300));
513
- if (accepted())
513
+ if (await accepted())
514
514
  return finish({ ok: true, pid: childPid });
515
515
  if (spawnError)
516
516
  return finish({ ok: false, pid: childPid, reason: spawnError });
517
- if (exited && !options.isPendingInRegistry?.()) {
517
+ if (exited && !await options.isPendingInRegistry?.()) {
518
518
  return finish({ ok: false, pid: childPid, reason: `进程已退出,exit=${exitCode}, signal=${exitSignal ?? 'none'}` });
519
519
  }
520
520
  }
521
- if (accepted())
521
+ if (await accepted())
522
522
  return finish({ ok: true, pid: childPid });
523
- if ((!exited && isProcessRunning(childPid)) || options.isPendingInRegistry?.()) {
523
+ if ((!exited && await isProcessRunningAsync(childPid)) || await options.isPendingInRegistry?.()) {
524
524
  return finish({
525
525
  ok: false,
526
526
  pid: childPid,
@@ -894,6 +894,25 @@ export function killProcess(pid, force = false) {
894
894
  return !isProcessRunning(pid);
895
895
  }
896
896
  }
897
+ /** Same process-tree termination as killProcess, without blocking Windows I/O. */
898
+ export async function killProcessAsync(pid, force = false) {
899
+ if (!Number.isInteger(pid) || pid <= 0)
900
+ return false;
901
+ if (!isWindows)
902
+ return killProcess(pid, force);
903
+ try {
904
+ const args = ['/PID', String(pid), '/T'];
905
+ if (force)
906
+ args.push('/F');
907
+ await execFileAsync('taskkill', args, {
908
+ encoding: 'utf-8', timeout: 10_000, windowsHide: true,
909
+ });
910
+ return true;
911
+ }
912
+ catch {
913
+ return !await isProcessRunningAsync(pid);
914
+ }
915
+ }
897
916
  /**
898
917
  * Terminate exactly one process, without recursively terminating its children.
899
918
  *
@@ -971,33 +990,47 @@ export function findProcessesWithCommandLine(pattern) {
971
990
  // stable literal anchor first, then apply the requested regex locally.
972
991
  const anchor = windowsProcessSearchAnchor(pattern);
973
992
  const escapedAnchor = anchor.replace(/'/g, "''");
974
- const script = `$a='${escapedAnchor}'; Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like ('*' + $a + '*') } | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`;
975
- const result = spawnSync('powershell', ['-NoProfile', '-Command', script], { encoding: null, timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
976
- const raw = decodeWindowsOutput(result.stdout).trim();
977
- if (raw) {
993
+ // Reuse the native WMI transport, but keep enumeration fresh and retain
994
+ // the original literal pre-filter. Wildcard anchors keep the old query.
995
+ let rows;
996
+ if (/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(anchor)) {
997
+ try {
998
+ const snapshot = getProcessSnapshot({ fresh: true });
999
+ if (snapshot.complete)
1000
+ rows = [...snapshot.commandLines]
1001
+ .filter(([, command]) => command.toLowerCase().includes(anchor.toLowerCase()))
1002
+ .map(([pid, commandLine]) => ({ ProcessId: pid, CommandLine: commandLine }));
1003
+ }
1004
+ catch { /* Retain the original query if snapshot collection failed. */ }
1005
+ }
1006
+ if (rows === undefined) {
1007
+ const script = `$a='${escapedAnchor}'; Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like ('*' + $a + '*') } | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`;
1008
+ const result = spawnSync('powershell', ['-NoProfile', '-Command', script], { encoding: null, timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
1009
+ const raw = decodeWindowsOutput(result.stdout).trim();
1010
+ if (!raw)
1011
+ return [];
978
1012
  const parsed = JSON.parse(raw);
979
- const rows = !parsed ? [] : Array.isArray(parsed) ? parsed : [parsed];
980
- const matcherCandidates = [pattern, pattern.replace(/\\\\/g, '\\')]
981
- .filter((value, index, values) => values.indexOf(value) === index)
982
- .map((value) => {
983
- try {
984
- return new RegExp(value, 'i');
985
- }
986
- catch {
987
- return null;
988
- }
989
- })
990
- .filter((value) => value !== null);
991
- return rows
992
- .filter(row => Number.isInteger(row.ProcessId) && row.ProcessId !== process.pid)
993
- .filter(row => {
994
- const commandLine = row.CommandLine || '';
995
- const normalized = commandLine.replace(/\\/g, '/');
996
- return matcherCandidates.some(matcher => matcher.test(commandLine) || matcher.test(normalized));
997
- })
998
- .map(row => ({ pid: row.ProcessId, commandLine: row.CommandLine || '' }));
1013
+ rows = !parsed ? [] : Array.isArray(parsed) ? parsed : [parsed];
999
1014
  }
1000
- return [];
1015
+ const matcherCandidates = [pattern, pattern.replace(/\\\\/g, '\\')]
1016
+ .filter((value, index, values) => values.indexOf(value) === index)
1017
+ .map((value) => {
1018
+ try {
1019
+ return new RegExp(value, 'i');
1020
+ }
1021
+ catch {
1022
+ return null;
1023
+ }
1024
+ })
1025
+ .filter((value) => value !== null);
1026
+ return rows
1027
+ .filter(row => Number.isInteger(row.ProcessId) && row.ProcessId !== process.pid)
1028
+ .filter(row => {
1029
+ const commandLine = row.CommandLine || '';
1030
+ const normalized = commandLine.replace(/\\/g, '/');
1031
+ return matcherCandidates.some(matcher => matcher.test(commandLine) || matcher.test(normalized));
1032
+ })
1033
+ .map(row => ({ pid: row.ProcessId, commandLine: row.CommandLine || '' }));
1001
1034
  }
1002
1035
  else {
1003
1036
  const output = execFileSync('pgrep', ['-f', pattern], { encoding: 'utf-8' }).trim();
@@ -1098,9 +1131,42 @@ export async function findProcessByPortAsync(port) {
1098
1131
  }
1099
1132
  return [...pids];
1100
1133
  }
1134
+ const WINDOWS_WMI_PROCESS_INFO_SCRIPT = String.raw `
1135
+ var service = GetObject('winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2');
1136
+ var rows = new Enumerator(service.ExecQuery('SELECT ProcessId,WorkingSetSize,CreationDate FROM Win32_Process WHERE ProcessId=' + Number(WScript.Arguments(0))));
1137
+ for (; !rows.atEnd(); rows.moveNext()) {
1138
+ var item = rows.item();
1139
+ WScript.Echo('{"ProcessId":' + Number(item.ProcessId)
1140
+ + ',"WorkingSetSize":' + Number(item.WorkingSetSize)
1141
+ + ',"CreationDate":' + (item.CreationDate == null ? 'null' : '"' + String(item.CreationDate) + '"') + '}');
1142
+ }
1143
+ `;
1101
1144
  export function getProcessInfo(pid) {
1102
1145
  try {
1103
1146
  if (isWindows) {
1147
+ const query = createWindowsProcessQuery(WINDOWS_WMI_PROCESS_INFO_SCRIPT, pid);
1148
+ if (query) {
1149
+ try {
1150
+ const result = spawnSync(query.command, query.args, {
1151
+ encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
1152
+ });
1153
+ if (result.status === 0) {
1154
+ const row = JSON.parse(result.stdout || '');
1155
+ const memory = Number(row?.WorkingSetSize);
1156
+ const createdAt = typeof row?.CreationDate === 'string' ? parseCimDate(row.CreationDate) : null;
1157
+ if (row?.ProcessId === pid && Number.isFinite(memory) && memory > 0 && createdAt !== null) {
1158
+ return {
1159
+ memory: String(Math.round(memory / 1024)),
1160
+ uptime: formatUptime(Math.max(0, Math.floor((Date.now() - createdAt) / 1000))),
1161
+ };
1162
+ }
1163
+ }
1164
+ }
1165
+ catch { /* Keep the original transports when WMI scripting is unavailable. */ }
1166
+ finally {
1167
+ query.dispose();
1168
+ }
1169
+ }
1104
1170
  // WMIC was removed from recent Windows installations. Prefer the
1105
1171
  // supported CIM API and keep WMIC as a compatibility fallback.
1106
1172
  const psScript = `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}' | Select-Object WorkingSetSize,CreationDate | ConvertTo-Json -Compress)`;
@@ -24,16 +24,66 @@
24
24
  {
25
25
  "id": "invalid-api-key",
26
26
  "match": "invalid api key",
27
- "action": "stop",
27
+ "action": "ask",
28
28
  "type": "auth_error",
29
- "message": "❌ API Key 无效,请检查密钥配置。使用 /status 查看当前配置"
29
+ "message": "❌ API Key 无效,请更新服务商连接凭据",
30
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
30
31
  },
31
32
  {
32
33
  "id": "key-not-found",
33
34
  "match": "key_not_found",
34
- "action": "stop",
35
+ "action": "ask",
36
+ "type": "auth_error",
37
+ "message": "❌ API Key 未找到,请补充服务商连接凭据",
38
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
39
+ },
40
+ {
41
+ "id": "provider-key-missing",
42
+ "match": "has no API key",
43
+ "action": "ask",
44
+ "type": "auth_error",
45
+ "message": "请补充服务商 API Key / Token",
46
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
47
+ },
48
+ {
49
+ "id": "provider-environment-missing",
50
+ "match": "provider_connection_missing",
51
+ "action": "ask",
52
+ "type": "auth_error",
53
+ "message": "服务商连接配置不完整,请补充缺失信息",
54
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
55
+ },
56
+ {
57
+ "id": "provider-base-url-missing",
58
+ "match": "provider_base_url_missing",
59
+ "action": "ask",
60
+ "type": "auth_error",
61
+ "message": "请补充服务商地址",
62
+ "question": { "handler": "provider-connection", "fields": ["baseUrl"], "includeMissing": ["apiKey"] }
63
+ },
64
+ {
65
+ "id": "native-key-missing",
66
+ "match": "no api key found",
67
+ "action": "ask",
35
68
  "type": "auth_error",
36
- "message": "❌ API Key 未找到,请检查密钥配置"
69
+ "message": "请补充模型连接 API Key / Token",
70
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
71
+ },
72
+ {
73
+ "id": "codex-key-missing",
74
+ "match": "no codex credential found",
75
+ "action": "ask",
76
+ "type": "auth_error",
77
+ "message": "请补充模型连接 API Key / Token",
78
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
79
+ },
80
+ {
81
+ "id": "ecagent-key-missing",
82
+ "match": "no ecagent api key found",
83
+ "action": "ask",
84
+ "type": "auth_error",
85
+ "message": "请补充模型连接 API Key / Token",
86
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
37
87
  },
38
88
  {
39
89
  "id": "api-key-verifier-too-many-connections",
@@ -161,6 +211,46 @@
161
211
  "type": "unknown",
162
212
  "message": "❌ 权限不足,请联系管理员配置应用权限"
163
213
  },
214
+ {
215
+ "id": "provider-authentication-error",
216
+ "match": "authentication_error",
217
+ "action": "ask",
218
+ "type": "auth_error",
219
+ "message": "服务商认证失败,请更新 API Key / Token",
220
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
221
+ },
222
+ {
223
+ "id": "provider-invalid-credential",
224
+ "match": "provider_credential_invalid",
225
+ "action": "ask",
226
+ "type": "auth_error",
227
+ "message": "服务商认证失败,请更新 API Key / Token",
228
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
229
+ },
230
+ {
231
+ "id": "provider-http-401",
232
+ "match": "http 401",
233
+ "action": "ask",
234
+ "type": "auth_error",
235
+ "message": "服务商认证失败,请更新 API Key / Token",
236
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
237
+ },
238
+ {
239
+ "id": "provider-api-401",
240
+ "match": "api error: 401",
241
+ "action": "ask",
242
+ "type": "auth_error",
243
+ "message": "服务商认证失败,请更新 API Key / Token",
244
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
245
+ },
246
+ {
247
+ "id": "provider-status-401",
248
+ "match": "401 unauthorized",
249
+ "action": "ask",
250
+ "type": "auth_error",
251
+ "message": "服务商认证失败,请更新 API Key / Token",
252
+ "question": { "handler": "provider-connection", "fields": ["apiKey"], "includeMissing": ["baseUrl"] }
253
+ },
164
254
  {
165
255
  "id": "stream-error",
166
256
  "match": "stream",
@@ -103,6 +103,7 @@ export var ErrorType;
103
103
  ErrorType["COMPACTION_FAILED"] = "compaction_failed";
104
104
  ErrorType["MODEL_UNAVAILABLE"] = "model_unavailable";
105
105
  ErrorType["SESSION_UNAVAILABLE"] = "session_unavailable";
106
+ ErrorType["SESSION_RUNTIME_UNAVAILABLE"] = "session_runtime_unavailable";
106
107
  ErrorType["SANDBOX_INITIALIZATION_FAILED"] = "sandbox_initialization_failed";
107
108
  ErrorType["SANDBOX_DEPENDENCIES_MISSING"] = "sandbox_dependencies_missing";
108
109
  ErrorType["CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE"] = "codex_sandbox_userns_unavailable";
@@ -295,7 +296,7 @@ export function prefixErrorType(prefix, errorType) {
295
296
  return `${prefix}:${errorType}`;
296
297
  }
297
298
  // ── 错误字典 ──────────────────────────────────────────────────────────
298
- const VALID_ACTIONS = new Set(['retry', 'stop', 'ignore']);
299
+ const VALID_ACTIONS = new Set(['retry', 'stop', 'ignore', 'ask']);
299
300
  let _dictPath = null;
300
301
  let _dictPathExplicit = false;
301
302
  let _rules = [];
@@ -336,11 +337,23 @@ function validateRule(r, index) {
336
337
  if (!r.match || typeof r.match !== 'string')
337
338
  return `rules[${index}] (${r.id}): 缺少 match 或类型不是 string`;
338
339
  if (!VALID_ACTIONS.has(r.action))
339
- return `rules[${index}] (${r.id}): action 无效 "${r.action}",允许值: retry/stop/ignore`;
340
+ return `rules[${index}] (${r.id}): action 无效 "${r.action}",允许值: retry/stop/ignore/ask`;
340
341
  if (r.type !== undefined && typeof r.type !== 'string')
341
342
  return `rules[${index}] (${r.id}): type 类型不是 string`;
342
343
  if (r.message !== undefined && typeof r.message !== 'string')
343
344
  return `rules[${index}] (${r.id}): message 类型不是 string`;
345
+ if (r.action === 'ask') {
346
+ const q = r.question;
347
+ const fields = (value) => Array.isArray(value)
348
+ && value.length <= 2 && value.every(field => field === 'apiKey' || field === 'baseUrl')
349
+ && new Set(value).size === value.length;
350
+ if (!q || q.handler !== 'provider-connection' || !fields(q.fields) || !q.fields.length
351
+ || (q.includeMissing !== undefined && !fields(q.includeMissing))) {
352
+ return `rules[${index}] (${r.id}): ask 需要合法的 provider-connection question`;
353
+ }
354
+ }
355
+ else if (r.question !== undefined)
356
+ return `rules[${index}] (${r.id}): question 仅用于 ask`;
344
357
  return null;
345
358
  }
346
359
  /**
@@ -426,6 +439,13 @@ export function matchErrorRule(errorMessage) {
426
439
  }
427
440
  return null;
428
441
  }
442
+ /** Ask is a terminal, human-assisted action. Match nested setup codes as well as provider messages. */
443
+ export function errorQuestionRule(error) {
444
+ const raw = getErrorRawText(error) ?? '';
445
+ const record = error && typeof error === 'object' ? error : undefined;
446
+ const rule = matchErrorRule(`${record?.code ?? ''}\n${record?.message ?? ''}\n${raw}`.toLowerCase());
447
+ return rule?.action === 'ask' ? rule : undefined;
448
+ }
429
449
  /** 获取当前已加载的规则数量(供测试和状态查询使用) */
430
450
  export function getLoadedRuleCount() {
431
451
  refreshDict();
@@ -466,7 +486,13 @@ const GATEWAY_REQUEST_TIMEOUT_PATTERN = /\bgateway request timed out\b/i;
466
486
  function hasRetryableHttpStatus(text) {
467
487
  return RETRYABLE_HTTP_STATUS_PATTERN.test(text);
468
488
  }
489
+ function isSessionRuntimeError(error) {
490
+ return error?.code === 'SESSION_RUNTIME_UNAVAILABLE'
491
+ || String(error?.message ?? error ?? '').startsWith('SESSION_RUNTIME_UNAVAILABLE:');
492
+ }
469
493
  export function classifyError(error) {
494
+ if (isSessionRuntimeError(error))
495
+ return ErrorType.SESSION_RUNTIME_UNAVAILABLE;
470
496
  if (isWindowsShellTrustError(error))
471
497
  return ErrorType.UNKNOWN;
472
498
  if (isUnattendedInputRequired(error))
@@ -513,7 +539,7 @@ export function classifyError(error) {
513
539
  return ErrorType.CONTEXT_TOO_LONG;
514
540
  }
515
541
  // 字典优先 — 命中则直接返回
516
- const rule = matchErrorRule(msg);
542
+ const rule = errorQuestionRule(error) ?? matchErrorRule(msg);
517
543
  if (rule) {
518
544
  if (rule.type)
519
545
  return rule.type;
@@ -521,6 +547,8 @@ export function classifyError(error) {
521
547
  return ErrorType.API_ERROR;
522
548
  if (rule.action === 'stop')
523
549
  return ErrorType.AUTH_ERROR;
550
+ if (rule.action === 'ask')
551
+ return ErrorType.INPUT_REQUIRED;
524
552
  return ErrorType.UNKNOWN;
525
553
  }
526
554
  // 内置兜底规则(结构性、稳定的错误模式)
@@ -552,6 +580,8 @@ export function classifyError(error) {
552
580
  * 注意:401 认证错误不可重试(API Key 无效不会因重试恢复)
553
581
  */
554
582
  export function isRetryableError(error) {
583
+ if (isSessionRuntimeError(error))
584
+ return false;
555
585
  if (isWindowsShellTrustError(error))
556
586
  return false;
557
587
  if (isUnattendedInputRequired(error))
@@ -565,6 +595,8 @@ export function isRetryableError(error) {
565
595
  return false;
566
596
  if (isPolicyRejectedError(error))
567
597
  return false;
598
+ if (errorQuestionRule(error))
599
+ return false;
568
600
  const msg = error?.message || String(error);
569
601
  const lower = msg.toLowerCase();
570
602
  if (lower.includes('invalid jsonl session file') || lower.includes('invalid session file'))
@@ -617,6 +649,10 @@ function sandboxInitializationErrorMessage(error, prefix) {
617
649
  return `${prefix}执行沙箱启动失败(sandbox_initialization_failed),当前操作未执行;请查看原始诊断并运行 ec diagnose 排查`;
618
650
  }
619
651
  export function getErrorMessage(error, terminalReason, includeEmoji = true) {
652
+ if (isSessionRuntimeError(error)) {
653
+ const message = typeof error === 'string' ? error : error.message ?? error.code;
654
+ return `${includeEmoji ? '❌ ' : ''}会话临时目录准备或安全校验失败,本轮未继续执行。${message}。请检查对应阶段的目录权限或超时原因;不会退回共享临时目录。`;
655
+ }
620
656
  if (isWindowsShellTrustError(error)) {
621
657
  return `${includeEmoji ? '❌ ' : ''}${resolveErrorMessage(error)}`;
622
658
  }
@@ -700,7 +736,7 @@ export function getErrorMessage(error, terminalReason, includeEmoji = true) {
700
736
  return `${warnPrefix}当前会话已失效,请发送 /renew。`;
701
737
  }
702
738
  // 字典优先 — 命中且有自定义消息则直接返回
703
- const rule = matchErrorRule(msg.toLowerCase());
739
+ const rule = errorQuestionRule(error) ?? matchErrorRule(msg.toLowerCase());
704
740
  if (rule?.message && (!isContextTooLongText(msg) || rule.type === ErrorType.CONTEXT_TOO_LONG))
705
741
  return rule.message;
706
742
  // 内置兜底规则(结构性错误)