evolcore 0.0.43-test.6 → 0.0.43-test.8

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 (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -1,5 +1,11 @@
1
1
  import fsPromises from 'fs/promises';
2
+ import fs from 'node:fs';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { createRequire } from 'node:module';
5
+ import { isDeepStrictEqual } from 'node:util';
6
+ import path from 'path';
2
7
  import { logger } from '../../utils/logger.js';
8
+ import { withFileLock } from '../../utils/atomic-write.js';
3
9
  /**
4
10
  * 检查会话文件健康度(接收完整文件路径)
5
11
  */
@@ -43,3 +49,240 @@ export async function backupSessionFile(sessionFile) {
43
49
  logger.info(`[SessionFileHealth] Backup created: ${backupPath}`);
44
50
  return backupPath;
45
51
  }
52
+ const requireFromHere = createRequire(import.meta.url);
53
+ const repairHash = (bytes) => createHash('sha256').update(bytes).digest('hex');
54
+ function syncRepairDirectory(directory) {
55
+ if (process.platform === 'win32')
56
+ return;
57
+ const fd = fs.openSync(directory, 'r');
58
+ try {
59
+ fs.fsyncSync(fd);
60
+ }
61
+ finally {
62
+ fs.closeSync(fd);
63
+ }
64
+ }
65
+ function writeRepairSnapshot(file, content) {
66
+ const fd = fs.openSync(file, 'wx', 0o600);
67
+ try {
68
+ fs.writeFileSync(fd, content);
69
+ fs.fsyncSync(fd);
70
+ }
71
+ finally {
72
+ fs.closeSync(fd);
73
+ }
74
+ syncRepairDirectory(path.dirname(file));
75
+ }
76
+ function codexMetadata(bytes, threadId) {
77
+ const end = bytes.indexOf(10);
78
+ const line = bytes.subarray(0, end < 0 ? bytes.length : end).toString('utf8');
79
+ const event = JSON.parse(line);
80
+ if (event.type !== 'session_meta' || !(event.payload?.id || event.payload?.session_id)
81
+ || [event.payload.id, event.payload.session_id].some(id => id !== undefined && id !== threadId)
82
+ || typeof event.payload.model_provider !== 'string' || !event.payload.model_provider) {
83
+ throw new Error('Codex Provider repair rejected: session metadata does not match the bound thread');
84
+ }
85
+ return { line, end: end < 0 ? bytes.length : end, provider: event.payload.model_provider };
86
+ }
87
+ function rewriteCodexProvider(bytes, threadId, provider) {
88
+ const header = codexMetadata(bytes, threadId);
89
+ const property = /("model_provider"\s*:\s*)"(?:\\.|[^"\\])*"/g;
90
+ const matches = [...header.line.matchAll(property)];
91
+ if (matches.length !== 1)
92
+ throw new Error('Codex Provider repair rejected: ambiguous Provider metadata');
93
+ const line = header.line.replace(property, (_value, prefix) => prefix + JSON.stringify(provider));
94
+ const expected = JSON.parse(header.line);
95
+ expected.payload.model_provider = provider;
96
+ if (!isDeepStrictEqual(JSON.parse(line), expected))
97
+ throw new Error('Codex Provider repair changed unrelated metadata');
98
+ return Buffer.concat([Buffer.from(line), bytes.subarray(header.end)]);
99
+ }
100
+ function readCodexProviderHeader(file, threadId) {
101
+ const fd = fs.openSync(file, 'r');
102
+ try {
103
+ const chunks = [];
104
+ let length = 0;
105
+ while (length < 1024 * 1024) {
106
+ const chunk = Buffer.alloc(16 * 1024);
107
+ const read = fs.readSync(fd, chunk, 0, chunk.length, null);
108
+ if (!read)
109
+ return codexMetadata(Buffer.concat(chunks), threadId).provider;
110
+ const end = chunk.subarray(0, read).indexOf(10);
111
+ chunks.push(chunk.subarray(0, end < 0 ? read : end + 1));
112
+ if (end >= 0)
113
+ return codexMetadata(Buffer.concat(chunks), threadId).provider;
114
+ length += read;
115
+ }
116
+ throw new Error('Codex Provider repair rejected: oversized session metadata');
117
+ }
118
+ finally {
119
+ fs.closeSync(fd);
120
+ }
121
+ }
122
+ function assertRepairFile(file, root) {
123
+ const relative = path.relative(root, fs.realpathSync(file));
124
+ const stat = fs.lstatSync(file);
125
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)
126
+ || !stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) {
127
+ throw new Error('Codex Provider repair rejected: unsafe storage path');
128
+ }
129
+ }
130
+ /**
131
+ * Change only the Provider of an existing Codex thread. Rollout bytes after the
132
+ * header and the EC/backend IDs are preserved. The durable intent plus before
133
+ * snapshot recover a crash between the filesystem rename and SQLite commit.
134
+ * This is called only by the runner for an authoritative EC thread binding.
135
+ */
136
+ export async function repairCodexSessionProvider(options) {
137
+ const { threadId, provider } = options;
138
+ if (!/^evolcore_registry_[a-f0-9]{20}$/.test(provider)) {
139
+ throw new Error('Codex Provider repair requires a resolved registry Provider');
140
+ }
141
+ const home = fs.realpathSync(options.codexHome);
142
+ const rollout = path.resolve(options.sessionFile);
143
+ const sessions = ['sessions', 'archived_sessions'].find(name => {
144
+ const relative = path.relative(path.join(home, name), rollout);
145
+ return relative && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
146
+ });
147
+ if (!sessions || !path.basename(rollout).endsWith(threadId + '.jsonl')) {
148
+ throw new Error('Codex Provider repair rejected: rollout is outside Codex session storage');
149
+ }
150
+ assertRepairFile(rollout, fs.realpathSync(path.join(home, sessions)));
151
+ const databaseName = fs.readdirSync(home).filter(name => /^state_\d+\.sqlite$/.test(name))
152
+ .sort((a, b) => Number(b.match(/\d+/)[0]) - Number(a.match(/\d+/)[0]))[0];
153
+ if (!databaseName)
154
+ throw new Error('Codex Provider repair requires a supported thread index');
155
+ const database = path.join(home, databaseName);
156
+ assertRepairFile(database, home);
157
+ const { DatabaseSync } = requireFromHere('node:sqlite');
158
+ const directory = rollout + '.provider-repair';
159
+ const journalFile = path.join(directory, 'intent.json');
160
+ const readIndex = () => {
161
+ const db = new DatabaseSync(database, { readOnly: true });
162
+ try {
163
+ const row = db.prepare('SELECT model_provider, rollout_path FROM threads WHERE id = ?').get(threadId);
164
+ if (!row || typeof row.model_provider !== 'string' || typeof row.rollout_path !== 'string'
165
+ || path.resolve(row.rollout_path) !== rollout)
166
+ throw new Error('Codex thread index does not match its rollout');
167
+ return row;
168
+ }
169
+ finally {
170
+ db.close();
171
+ }
172
+ };
173
+ if (!fs.existsSync(journalFile) && readCodexProviderHeader(rollout, threadId) === provider
174
+ && readIndex().model_provider === provider)
175
+ return false;
176
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
177
+ if (fs.lstatSync(directory).isSymbolicLink()
178
+ || fs.realpathSync(directory) !== path.join(path.dirname(fs.realpathSync(rollout)), path.basename(directory))) {
179
+ throw new Error('Codex Provider repair rejected: unsafe backup directory');
180
+ }
181
+ return withFileLock(path.join(directory, 'operation.lock'), async () => {
182
+ const before = fs.readFileSync(rollout);
183
+ const index = readIndex();
184
+ const header = codexMetadata(before, threadId);
185
+ if (!fs.existsSync(journalFile) && header.provider === provider && index.model_provider === provider)
186
+ return false;
187
+ await options.releaseThread();
188
+ assertRepairFile(rollout, fs.realpathSync(path.join(home, sessions)));
189
+ if (repairHash(fs.readFileSync(rollout)) !== repairHash(before)
190
+ || !isDeepStrictEqual(readIndex(), index))
191
+ throw new Error('Codex session changed while preparing Provider repair');
192
+ const apply = (intent) => {
193
+ const backupRoot = path.join(directory, path.basename(path.dirname(intent.backup)));
194
+ if (intent.version !== 1 || intent.threadId !== threadId || intent.database !== database
195
+ || intent.rollout !== rollout || path.resolve(intent.indexedPath) !== rollout
196
+ || intent.backup !== path.join(backupRoot, 'before.snapshot')
197
+ || intent.next !== path.join(backupRoot, 'after.snapshot')
198
+ || !/^evolcore_registry_[a-f0-9]{20}$/.test(intent.provider)) {
199
+ throw new Error('Invalid Codex Provider repair journal');
200
+ }
201
+ assertRepairFile(intent.backup, directory);
202
+ const original = fs.readFileSync(intent.backup);
203
+ const replacement = rewriteCodexProvider(original, threadId, intent.provider);
204
+ if (repairHash(original) !== intent.beforeHash || repairHash(replacement) !== intent.afterHash) {
205
+ throw new Error('Codex Provider repair snapshot failed integrity verification');
206
+ }
207
+ const db = new DatabaseSync(database);
208
+ let transaction = false;
209
+ let replaced = false;
210
+ try {
211
+ db.exec('PRAGMA busy_timeout = 3000');
212
+ db.exec('BEGIN IMMEDIATE');
213
+ transaction = true;
214
+ const row = db.prepare('SELECT model_provider, rollout_path FROM threads WHERE id = ?').get(threadId);
215
+ const currentHash = repairHash(fs.readFileSync(rollout));
216
+ if (!row || row.rollout_path !== intent.indexedPath
217
+ || ![intent.previousProvider, intent.provider].includes(row.model_provider)
218
+ || ![intent.beforeHash, intent.afterHash].includes(currentHash)) {
219
+ throw new Error('Codex Provider repair conflicts with newer session data');
220
+ }
221
+ if (currentHash !== intent.afterHash) {
222
+ if (fs.existsSync(intent.next)) {
223
+ assertRepairFile(intent.next, directory);
224
+ if (repairHash(fs.readFileSync(intent.next)) !== intent.afterHash)
225
+ throw new Error('Invalid repair snapshot');
226
+ }
227
+ else
228
+ writeRepairSnapshot(intent.next, replacement);
229
+ fs.chmodSync(intent.next, fs.statSync(rollout).mode & 0o777);
230
+ fs.renameSync(intent.next, rollout);
231
+ replaced = true;
232
+ syncRepairDirectory(path.dirname(rollout));
233
+ }
234
+ if (row.model_provider !== intent.provider) {
235
+ const changed = db.prepare('UPDATE threads SET model_provider = ? WHERE id = ? AND model_provider = ?')
236
+ .run(intent.provider, threadId, intent.previousProvider);
237
+ if (changed.changes !== 1)
238
+ throw new Error('Codex Provider repair index update conflicted');
239
+ }
240
+ db.exec('COMMIT');
241
+ transaction = false;
242
+ }
243
+ catch (error) {
244
+ if (transaction)
245
+ db.exec('ROLLBACK');
246
+ if (replaced && repairHash(fs.readFileSync(rollout)) === intent.afterHash) {
247
+ const rollback = path.join(backupRoot, 'rollback-' + randomUUID() + '.snapshot');
248
+ writeRepairSnapshot(rollback, original);
249
+ fs.chmodSync(rollback, fs.statSync(rollout).mode & 0o777);
250
+ fs.renameSync(rollback, rollout);
251
+ syncRepairDirectory(path.dirname(rollout));
252
+ }
253
+ throw error;
254
+ }
255
+ finally {
256
+ db.close();
257
+ }
258
+ fs.unlinkSync(journalFile);
259
+ syncRepairDirectory(directory);
260
+ };
261
+ if (fs.existsSync(journalFile)) {
262
+ assertRepairFile(journalFile, directory);
263
+ apply(JSON.parse(fs.readFileSync(journalFile, 'utf8')));
264
+ }
265
+ const bytes = fs.readFileSync(rollout);
266
+ const current = readIndex();
267
+ if (codexMetadata(bytes, threadId).provider !== provider || current.model_provider !== provider) {
268
+ if (codexMetadata(bytes, threadId).provider !== current.model_provider) {
269
+ throw new Error('Codex Provider repair rejected: rollout and index disagree');
270
+ }
271
+ const backupRoot = path.join(directory, randomUUID());
272
+ fs.mkdirSync(backupRoot, { mode: 0o700 });
273
+ const replacement = rewriteCodexProvider(bytes, threadId, provider);
274
+ const intent = {
275
+ version: 1, threadId, database, rollout, indexedPath: current.rollout_path,
276
+ previousProvider: current.model_provider, provider,
277
+ beforeHash: repairHash(bytes), afterHash: repairHash(replacement),
278
+ backup: path.join(backupRoot, 'before.snapshot'), next: path.join(backupRoot, 'after.snapshot'),
279
+ };
280
+ writeRepairSnapshot(intent.backup, bytes);
281
+ writeRepairSnapshot(intent.next, replacement);
282
+ writeRepairSnapshot(journalFile, JSON.stringify(intent));
283
+ apply(intent);
284
+ }
285
+ logger.info(`[SessionFileHealth] Codex Provider repaired: thread=${threadId} provider=${provider}`);
286
+ return true;
287
+ });
288
+ }
@@ -2,6 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { createInterface } from 'node:readline';
4
4
  import { setImmediate as yieldToIo } from 'node:timers/promises';
5
+ import { performance } from 'node:perf_hooks';
5
6
  // 文件系统非法字符(Windows 最严格):< > : " / \ | ? *
6
7
  // 还有控制字符 0x00-0x1F。我们把这些字符编码为 %XX(hex 大写)。
7
8
  // `%` 本身也要转义为 %25,保证可逆。
@@ -464,8 +465,9 @@ export function readLastJsonlLine(filePath) {
464
465
  }
465
466
  }
466
467
  /** Async tail reader with the same committed-record rules as the sync readers. */
467
- export async function readLastJsonlLineAsync(filePath, strict = false) {
468
+ export async function readLastJsonlLineAsync(filePath, strict = false, timing) {
468
469
  let handle;
470
+ let started = timing ? performance.now() : 0;
469
471
  try {
470
472
  handle = await fs.promises.open(filePath, 'r');
471
473
  }
@@ -474,21 +476,40 @@ export async function readLastJsonlLineAsync(filePath, strict = false) {
474
476
  return undefined;
475
477
  throw error;
476
478
  }
479
+ finally {
480
+ if (timing)
481
+ timing.openMs += performance.now() - started;
482
+ }
477
483
  try {
478
- let cursor = (await handle.stat()).size;
484
+ started = timing ? performance.now() : 0;
485
+ let cursor;
486
+ try {
487
+ cursor = (await handle.stat()).size;
488
+ }
489
+ finally {
490
+ if (timing)
491
+ timing.statMs += performance.now() - started;
492
+ }
479
493
  let carry = Buffer.alloc(0);
480
494
  let skipUncommitted = strict;
481
495
  const parse = (raw, offset) => {
482
- const line = raw.toString('utf8').trim();
483
- if (!line)
484
- return undefined;
485
- if (strict)
486
- return parseJsonlLineStrict(line, filePath, offset);
496
+ const parseStarted = timing ? performance.now() : 0;
487
497
  try {
488
- return JSON.parse(line);
498
+ const line = raw.toString('utf8').trim();
499
+ if (!line)
500
+ return undefined;
501
+ if (strict)
502
+ return parseJsonlLineStrict(line, filePath, offset);
503
+ try {
504
+ return JSON.parse(line);
505
+ }
506
+ catch {
507
+ return undefined;
508
+ }
489
509
  }
490
- catch {
491
- return undefined;
510
+ finally {
511
+ if (timing)
512
+ timing.parseMs += performance.now() - parseStarted;
492
513
  }
493
514
  };
494
515
  while (cursor > 0) {
@@ -496,7 +517,17 @@ export async function readLastJsonlLineAsync(filePath, strict = false) {
496
517
  const chunk = Buffer.allocUnsafe(cursor - start);
497
518
  let offset = 0;
498
519
  while (offset < chunk.length) {
499
- const { bytesRead } = await handle.read(chunk, offset, chunk.length - offset, start + offset);
520
+ started = timing ? performance.now() : 0;
521
+ let bytesRead;
522
+ try {
523
+ ({ bytesRead } = await handle.read(chunk, offset, chunk.length - offset, start + offset));
524
+ }
525
+ finally {
526
+ if (timing)
527
+ timing.readMs += performance.now() - started;
528
+ }
529
+ if (timing)
530
+ timing.bytes += bytesRead;
500
531
  if (!bytesRead)
501
532
  throw new Error(`short JSONL read at ${filePath}:${start + offset}`);
502
533
  offset += bytesRead;
@@ -521,7 +552,14 @@ export async function readLastJsonlLineAsync(filePath, strict = false) {
521
552
  return skipUncommitted ? undefined : parse(carry, 0);
522
553
  }
523
554
  finally {
524
- await handle.close();
555
+ started = timing ? performance.now() : 0;
556
+ try {
557
+ await handle.close();
558
+ }
559
+ finally {
560
+ if (timing)
561
+ timing.closeMs += performance.now() - started;
562
+ }
525
563
  }
526
564
  }
527
565
  export function readAllJsonlLines(filePath) {
@@ -593,8 +631,7 @@ export async function readAllJsonlLinesAsync(filePath) {
593
631
  }
594
632
  return results;
595
633
  }
596
- /** Scan only one Agent/channel, with bounded asynchronous directory reads. */
597
- export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey) {
634
+ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey, options) {
598
635
  if (!selfAID || selfAID === '.' || selfAID === '..')
599
636
  throw new Error('invalid selfAID');
600
637
  const sessionsDir = path.join(sessionsRoot, encodeSegment(selfAID), 'sessions');
@@ -608,17 +645,19 @@ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey)
608
645
  throw error;
609
646
  }
610
647
  const results = [];
611
- for (let offset = 0; offset < entries.length; offset += 8) {
612
- const batch = await Promise.all(entries.slice(offset, offset + 8).map(async (entry) => {
648
+ let next = 0;
649
+ const workers = await Promise.allSettled(Array.from({ length: Math.min(8, entries.length) }, async () => {
650
+ while (next < entries.length) {
651
+ const entry = entries[next++];
613
652
  if (!entry.isDirectory())
614
- return undefined;
653
+ continue;
615
654
  const parsed = tryParseChannelSessionKey(entry.name);
616
655
  if (!parsed)
617
- return undefined;
656
+ continue;
618
657
  const key = parsed.channelType === 'daemon' ? 'daemon'
619
658
  : `${parsed.channelType}#${selfAID}#${parsed.channelName}`;
620
659
  if (channelKey && key !== channelKey)
621
- return undefined;
660
+ continue;
622
661
  const dirPath = path.join(sessionsDir, entry.name);
623
662
  let payload;
624
663
  try {
@@ -626,18 +665,18 @@ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey)
626
665
  }
627
666
  catch (error) {
628
667
  if (error.code === 'ENOENT')
629
- return undefined;
668
+ continue;
630
669
  throw error;
631
670
  }
632
671
  if (!payload.some(isSessionPayload))
633
- return undefined;
634
- return { channelType: parsed.channelType, selfAID, channelId: parsed.channelId,
635
- channelKey: key, channelSessionKey: entry.name, dirPath };
636
- }));
637
- for (const chat of batch)
638
- if (chat)
639
- results.push(chat);
640
- }
672
+ continue;
673
+ results.push({ channelType: parsed.channelType, selfAID, channelId: parsed.channelId,
674
+ channelKey: key, channelSessionKey: entry.name, dirPath, ...(options?.includeEntries ? { entries: payload } : {}) });
675
+ }
676
+ }));
677
+ for (const worker of workers)
678
+ if (worker.status === 'rejected')
679
+ throw worker.reason;
641
680
  return results.sort((a, b) => a.dirPath < b.dirPath ? -1 : a.dirPath > b.dirPath ? 1 : 0);
642
681
  }
643
682
  /**
@@ -7,6 +7,7 @@ import { isSystemControlChannel } from '../system-channels.js';
7
7
  import { logger } from '../../utils/logger.js';
8
8
  import { atomicWriteJson } from './session-fs-store.js';
9
9
  import { createRootCausation } from '../causation/context.js';
10
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
10
11
  export const DEFAULT_SESSION_LOOP_SECONDS = 300;
11
12
  export const MIN_SESSION_LOOP_SECONDS = 30;
12
13
  export const MAX_SESSION_LOOP_SECONDS = 86400;
@@ -187,6 +188,7 @@ export class SessionIdleMonitor {
187
188
  persistedState;
188
189
  started = false;
189
190
  active = false;
191
+ activation = 0;
190
192
  onTaskTerminal = (event) => {
191
193
  if (!isTaskTerminalEvent(event) || !event.sessionId)
192
194
  return;
@@ -255,27 +257,60 @@ export class SessionIdleMonitor {
255
257
  this.options.eventBus.subscribe('session:created', this.onSessionCreated);
256
258
  this.options.eventBus.subscribe('session:loop-changed', this.onSessionLoopChanged);
257
259
  }
258
- /** Arm restored timers only after event-trigger subscriptions are registered. */
259
- activate() {
260
+ /** Subscribe first; restore cold history only after normal task Ready. */
261
+ activate(options = {}) {
260
262
  if (this.active)
261
- return;
263
+ return Promise.resolve();
262
264
  this.active = true;
263
265
  this.refreshSessionIdleTriggerIds();
264
- for (const sessionId of this.sessions.keys())
265
- void this.restorePendingSession(sessionId);
266
- }
267
- async restorePendingSession(sessionId) {
268
- try {
269
- const session = await this.options.getSessionById(sessionId);
270
- const state = this.sessions.get(sessionId);
271
- const pending = session && readSessionLoopOnceConfig(session);
272
- if (state && pending && state.onceRequestId === pending.requestId)
273
- state.emitted = false;
274
- this.scheduleSession(sessionId);
275
- }
276
- catch (error) {
277
- this.warn(`Failed to restore pending idle check for ${sessionId}`, error);
266
+ const activation = ++this.activation;
267
+ const cutoff = this.now() - 24 * 60 * 60 * 1000;
268
+ // Capture identity and generation now, not when the cold group is admitted:
269
+ // intervening task/configuration changes own their timers and must win.
270
+ const entries = [...this.sessions].map(([id, state]) => ({ id, state,
271
+ generation: this.generations.get(id) ?? 0 }));
272
+ const recent = entries.filter(({ state }) => !options.waitForBackground
273
+ || Math.max(state.lastEndedAt, state.armedAt ?? 0) >= cutoff || !!state.onceRequestId);
274
+ const recentIds = new Set(recent.map(entry => entry.id));
275
+ const older = entries.filter(entry => !recentIds.has(entry.id));
276
+ return (async () => {
277
+ await this.restorePendingSessions(recent, activation, 'recent', options.onRestored);
278
+ if (!this.active || this.activation !== activation || !older.length)
279
+ return;
280
+ if (options.waitForBackground && !await options.waitForBackground())
281
+ return;
282
+ await this.restorePendingSessions(older, activation, 'older', options.onRestored);
283
+ })();
284
+ }
285
+ async restorePendingSessions(entries, activation, group, onRestored) {
286
+ const started = Date.now();
287
+ // getSessionById currently performs synchronous filesystem work. A burst
288
+ // of restored timers must not hold Runner microtasks or AUN admission.
289
+ for (let offset = 0; offset < entries.length; offset += 4) {
290
+ await yieldToIo();
291
+ if (!this.active || this.activation !== activation)
292
+ return;
293
+ await Promise.all(entries.slice(offset, offset + 4).map(async ({ id, state, generation }) => {
294
+ const current = () => this.active && this.activation === activation && this.sessions.get(id) === state
295
+ && (this.generations.get(id) ?? 0) === generation;
296
+ if (!current())
297
+ return;
298
+ try {
299
+ const session = await this.options.getSessionById(id);
300
+ if (!current())
301
+ return;
302
+ const pending = session && readSessionLoopOnceConfig(session);
303
+ if (pending && state.onceRequestId === pending.requestId)
304
+ state.emitted = false;
305
+ await this.scheduleSessionAsync(id, { session });
306
+ }
307
+ catch (error) {
308
+ this.warn(`Failed to restore pending idle check for ${id}`, error);
309
+ }
310
+ }));
278
311
  }
312
+ if (this.active && this.activation === activation)
313
+ onRestored?.(group, started, Date.now(), entries.length);
279
314
  }
280
315
  /**
281
316
  * 重新采集 session:idle trigger 身份。
@@ -351,7 +386,12 @@ export class SessionIdleMonitor {
351
386
  }
352
387
  stop() {
353
388
  this.active = false;
389
+ this.activation++;
354
390
  this.clearAllTimers();
391
+ // Also invalidate scheduling/emission already awaiting a configuration read.
392
+ for (const sessionId of this.sessions.keys()) {
393
+ this.generations.set(sessionId, (this.generations.get(sessionId) ?? 0) + 1);
394
+ }
355
395
  if (!this.started)
356
396
  return;
357
397
  this.started = false;
@@ -394,7 +434,7 @@ export class SessionIdleMonitor {
394
434
  scheduleSession(sessionId) {
395
435
  void this.scheduleSessionAsync(sessionId);
396
436
  }
397
- async scheduleSessionAsync(sessionId) {
437
+ async scheduleSessionAsync(sessionId, restored) {
398
438
  const state = this.sessions.get(sessionId);
399
439
  if (!state || !this.active)
400
440
  return;
@@ -403,7 +443,7 @@ export class SessionIdleMonitor {
403
443
  return;
404
444
  let session;
405
445
  try {
406
- session = await this.options.getSessionById(sessionId);
446
+ session = restored ? restored.session : await this.options.getSessionById(sessionId);
407
447
  }
408
448
  catch (error) {
409
449
  this.warn(`Failed to load session ${sessionId} while scheduling idle check`, error);
@@ -1401,11 +1401,13 @@ export class SessionManager {
1401
1401
  if (chatType === 'private' && userId) {
1402
1402
  if (!session.metadata)
1403
1403
  session.metadata = {};
1404
- if (!session.metadata.peerId) {
1404
+ // 本端不能成为话题对端:跨话题自派等内部消息即使把 peerId 写成自己,
1405
+ // 会话对端也必须保持原来的私聊对端,否则话题会变成「我↔我」。
1406
+ if (!session.metadata.peerId && userId !== selfAID) {
1405
1407
  session.metadata.peerId = userId;
1406
1408
  mutated = true;
1407
1409
  }
1408
- if (!session.metadata.peerName && metadata?.peerName) {
1410
+ if (!session.metadata.peerName && metadata?.peerName && metadata.peerName !== selfAID) {
1409
1411
  session.metadata.peerName = metadata.peerName;
1410
1412
  mutated = true;
1411
1413
  }
@@ -1464,10 +1466,10 @@ export class SessionManager {
1464
1466
  logger.info(`[SessionManager] Updating chatType for session ${session.id}: ${session.chatType} -> ${chatType}`);
1465
1467
  session.chatType = chatType;
1466
1468
  }
1467
- if (chatType === 'private' && userId && !session.metadata.peerId) {
1469
+ if (chatType === 'private' && userId && !session.metadata.peerId && userId !== selfAID) {
1468
1470
  session.metadata.peerId = userId;
1469
1471
  }
1470
- if (chatType === 'private' && metadata?.peerName && !session.metadata.peerName) {
1472
+ if (chatType === 'private' && metadata?.peerName && !session.metadata.peerName && metadata.peerName !== selfAID) {
1471
1473
  session.metadata.peerName = metadata.peerName;
1472
1474
  }
1473
1475
  if (metadata?.peerType) {
@@ -1807,6 +1809,13 @@ export class SessionManager {
1807
1809
  upsertAgentThreadIndex(input) {
1808
1810
  if (!input.selfAid || !input.threadId)
1809
1811
  return;
1812
+ // 只收话题会话。daemon 内部会话(记忆整理 `bg:<kind>`、trigger 会话
1813
+ // `trigger:<id>`)也带 threadId,但它们是伪话题,会话清理后会留下永远查不到
1814
+ // 会话的悬空条目,让 `rebuild-index --check` 永久报「严重」。
1815
+ if (input.channelType === 'daemon')
1816
+ return;
1817
+ if (!input.threadId.startsWith('thread-'))
1818
+ return;
1810
1819
  try {
1811
1820
  const indexPath = agentThreadIndexPath(input.selfAid);
1812
1821
  const raw = readJsonFile(indexPath);
@@ -71,7 +71,7 @@ export class TaskRecoveryService {
71
71
  if (request.automatic && (!request.expectedTaskId || !Number.isSafeInteger(request.expectedGeneration))) {
72
72
  return result('not_recoverable', '自动恢复必须指定原任务及其版本', false);
73
73
  }
74
- const session = await this.deps.sessions.getSessionById(request.sessionId);
74
+ let session = await this.deps.sessions.getSessionById(request.sessionId);
75
75
  if (!session || session.deletedAt || (request.agentAid && session.selfAID !== request.agentAid)) {
76
76
  return result('not_found', '目标会话不存在或不属于当前 Agent', false);
77
77
  }
@@ -97,12 +97,23 @@ export class TaskRecoveryService {
97
97
  return result('waiting_interaction', '任务正在等待必要输入或审批,请先完成交互');
98
98
  }
99
99
  let runner;
100
+ const binding = JSON.stringify([session.selfAID, session.baseagent, session.agentSessionId, session.processingState, state]);
100
101
  try {
101
- runner = this.deps.getRunner(session);
102
+ runner = await this.deps.getRunner(session);
102
103
  }
103
104
  catch {
104
105
  return result('not_recoverable', '原 baseagent 当前不可用', false);
105
106
  }
107
+ if (request.signal?.aborted)
108
+ return result('not_recoverable', '恢复请求已取消', false);
109
+ // First-use loading can yield for seconds. A stop, replacement turn or
110
+ // backend change during that wait must invalidate this recovery attempt.
111
+ const latest = await this.deps.sessions.getSessionById(request.sessionId);
112
+ if (!latest || latest.deletedAt || binding !== JSON.stringify([
113
+ latest.selfAID, latest.baseagent, latest.agentSessionId, latest.processingState, latest.metadata?.turnState,
114
+ ]))
115
+ return result('stale', '等待 Runner 期间会话状态已变化,已忽略过期恢复请求');
116
+ session = latest;
106
117
  if (!request.automatic && this.deps.resumePause(session.id)) {
107
118
  return result('resumed_pause', '✓ 已继续暂停的任务');
108
119
  }
@@ -8,7 +8,7 @@ const VALUE_OPTIONS = new Set(['--self', '--agent', '--format', '--name', '--lab
8
8
  const OPTIONS = {
9
9
  peers: [], list: ['--status', '--label', '--unlabeled', '--sort', '--page', '--limit'],
10
10
  show: [], history: ['--limit', '--before', '--after'],
11
- create: ['--name', '--label', '--status', '--group'], rename: [], label: ['--clear'], status: [],
11
+ create: ['--name', '--label', '--status', '--group', '--private'], rename: [], label: ['--clear'], status: [],
12
12
  delete: [], 'rebuild-index': ['--check', '--agent'], 'check-index': ['--agent'],
13
13
  'summary-show': [], 'summary-set': ['--name', '--if-rev'], 'summary-log': [], 'summary-clear': [],
14
14
  };
@@ -120,7 +120,14 @@ export function resolveThreadCommandArgv(argv, context = {}) {
120
120
  if (command === 'create') {
121
121
  if (!text('--name')?.trim())
122
122
  throw new Error('Topic name is required');
123
- Object.assign(request, { name: text('--name'), label: text('--label'), topicStatus: status, peerKind: options.has('--group') ? 'group' : 'private' });
123
+ // 对端类型:显式 `--group` / `--private` 优先;都没写时留空,由执行层按
124
+ // 关系证据推断(群里漏写 --group 曾被记成 private,之后 scope 判定全错)。
125
+ const explicitPeerKind = options.has('--group') ? 'group'
126
+ : options.has('--private') ? 'private' : undefined;
127
+ Object.assign(request, {
128
+ name: text('--name'), label: text('--label'), topicStatus: status,
129
+ ...(explicitPeerKind ? { peerKind: explicitPeerKind } : {}),
130
+ });
124
131
  }
125
132
  if (command === 'rename') {
126
133
  if (!positional[1].trim())