evolcore 0.0.47 → 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 (218) hide show
  1. package/CHANGELOG.md +56 -1
  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 +34 -17
  8. package/dist/agents/codex-runner.js +31 -16
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/service-proxy.js +4 -2
  14. package/dist/build-identity.json +1 -0
  15. package/dist/channels/aun.js +81 -24
  16. package/dist/channels/daemon.js +9 -25
  17. package/dist/cli/aun-commands.js +86 -51
  18. package/dist/cli/code-stats.js +19 -8
  19. package/dist/cli/command-log.js +1 -1
  20. package/dist/cli/daemon-commands.js +44 -43
  21. package/dist/cli/directory.js +7 -1
  22. package/dist/cli/ecmsg-gateway.js +5 -2
  23. package/dist/cli/index.js +2 -8
  24. package/dist/cli/init-channel.js +4 -6
  25. package/dist/cli/init.js +72 -50
  26. package/dist/cli/invoke-command.js +1 -1
  27. package/dist/cli/provider-command.js +74 -13
  28. package/dist/cli/role.js +61 -17
  29. package/dist/cli/stats.js +3 -3
  30. package/dist/cli/thread-command.js +16 -51
  31. package/dist/config/boot-log.js +3 -9
  32. package/dist/config/builtin-roles.js +5 -7
  33. package/dist/config/config-manager.js +2 -6
  34. package/dist/config/daemon-services.js +30 -3
  35. package/dist/config/gateway-config.js +2 -2
  36. package/dist/config/invoke-ipc-service.js +6 -4
  37. package/dist/config/peer-bind-code.js +3 -4
  38. package/dist/config/peer-book-store.js +62 -229
  39. package/dist/config/peer-book.js +26 -27
  40. package/dist/config/peer-role-resolver.js +16 -1
  41. package/dist/config/provider-identity-migration.js +4 -1
  42. package/dist/config/provider-ipc-service.js +56 -11
  43. package/dist/config/provider-menu-request.js +24 -5
  44. package/dist/config/provider-templates.js +127 -0
  45. package/dist/config/providers-config.js +59 -8
  46. package/dist/config/providers-management.js +467 -49
  47. package/dist/config/role-command-service.js +248 -1
  48. package/dist/config/schema-migration.js +105 -4
  49. package/dist/core/agent-application-service.js +6 -1
  50. package/dist/core/agent-runtime.js +4 -0
  51. package/dist/core/auth/agent-delegation.js +2 -1
  52. package/dist/core/auth/auth-gateway.js +2 -1
  53. package/dist/core/auth/delegation-authorization.js +3 -0
  54. package/dist/core/auth/operation-authorizer.js +25 -0
  55. package/dist/core/auth/operation-catalog.js +28 -64
  56. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  57. package/dist/core/channel-loader.js +18 -0
  58. package/dist/core/command/agent-control.js +32 -0
  59. package/dist/core/command/command-handler.js +81 -85
  60. package/dist/core/command/menu-catalog.js +1 -0
  61. package/dist/core/command/menu-handler.js +61 -149
  62. package/dist/core/command/menu-protocol.js +7 -1
  63. package/dist/core/command/provider-menu.js +13 -3
  64. package/dist/core/command/role-menu.js +47 -23
  65. package/dist/core/command/slash-handler.js +26 -43
  66. package/dist/core/command/team-workspace-items.js +81 -12
  67. package/dist/core/command/team-workspace-team.js +9 -71
  68. package/dist/core/command/topic-slash.js +9 -30
  69. package/dist/core/daemon-bootstrap.js +8 -1
  70. package/dist/core/daemon-control.js +7 -7
  71. package/dist/core/evolagent-registry.js +14 -1
  72. package/dist/core/file-integrity/store.js +2 -0
  73. package/dist/core/handoff/runtime.js +37 -1
  74. package/dist/core/inference/text-inference.js +3 -1
  75. package/dist/core/initialization/service.js +11 -6
  76. package/dist/core/interaction-router.js +3 -0
  77. package/dist/core/invoke/executors/text.js +72 -19
  78. package/dist/core/ipc-registration.js +2 -1
  79. package/dist/core/message/aun-ipc-sender.js +165 -55
  80. package/dist/core/message/im-renderer.js +1 -1
  81. package/dist/core/message/message-bridge.js +51 -334
  82. package/dist/core/message/message-log.js +5 -0
  83. package/dist/core/message/message-queue.js +22 -0
  84. package/dist/core/message/message-utils.js +8 -0
  85. package/dist/core/message/response-engine.js +429 -116
  86. package/dist/core/message/send-routing.js +5 -1
  87. package/dist/core/model/catalog-service.js +31 -11
  88. package/dist/core/model/model-capabilities.js +22 -4
  89. package/dist/core/model/model-catalog.js +1 -0
  90. package/dist/core/ownership/owner-resolver.js +328 -50
  91. package/dist/core/permission/protected-paths.js +6 -6
  92. package/dist/core/relation/peer-identity.js +23 -1
  93. package/dist/core/relation/same-owner-proof.js +81 -112
  94. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  95. package/dist/core/session/session-file-health.js +13 -7
  96. package/dist/core/session/session-fs-store.js +91 -35
  97. package/dist/core/session/session-manager.js +68 -24
  98. package/dist/core/session/session-mapper.js +14 -34
  99. package/dist/core/session/session-transcript.js +5 -1
  100. package/dist/core/task/task-activity-store.js +84 -0
  101. package/dist/core/task/task-recovery-service.js +12 -0
  102. package/dist/core/thread/command-parser.js +7 -12
  103. package/dist/core/thread/thread-context-storage.js +3 -2
  104. package/dist/core/thread/thread-operation.js +2 -13
  105. package/dist/core/thread/thread-service.js +15 -46
  106. package/dist/directory/owner-directory-admission.js +1 -1
  107. package/dist/directory/owner-directory-cache.js +45 -28
  108. package/dist/directory/owner-directory-markdown.js +13 -1
  109. package/dist/directory/owner-directory-query-operation.js +29 -3
  110. package/dist/directory/owner-directory-remarks.js +11 -3
  111. package/dist/eck/message-renderer.js +84 -24
  112. package/dist/ecweb/basic-settings-service.js +3 -1
  113. package/dist/ecweb/message-context-service.js +1 -1
  114. package/dist/ecweb/pairing.js +4 -3
  115. package/dist/ecweb/providers-service.js +26 -1
  116. package/dist/ecweb/runtime/lifecycle.js +18 -8
  117. package/dist/ecweb/runtime/proxy-access.js +74 -0
  118. package/dist/ecweb/runtime/supervisor.js +4 -2
  119. package/dist/event-center/registry.js +13 -2
  120. package/dist/event-center/runtime.js +103 -11
  121. package/dist/event-center/script-runner.js +5 -5
  122. package/dist/index.js +92 -59
  123. package/dist/ipc.js +13 -2
  124. package/dist/outputs/events.js +62 -0
  125. package/dist/outputs/protocol.js +102 -0
  126. package/dist/outputs/service.js +279 -0
  127. package/dist/paths.js +3 -0
  128. package/dist/proxy/manager.js +43 -13
  129. package/dist/services/index.js +89 -4
  130. package/dist/services/ipc-operation.js +4 -15
  131. package/dist/services/pack-manager.js +12 -1
  132. package/dist/services/router.js +21 -6
  133. package/dist/services/script-runner.js +5 -4
  134. package/dist/services/validation.js +1 -1
  135. package/dist/stats/budget.js +1 -1
  136. package/dist/stats/db.js +19 -0
  137. package/dist/stats/index.js +1 -1
  138. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  139. package/dist/stats/normalizer.js +2 -0
  140. package/dist/stats/query.js +35 -27
  141. package/dist/stats/role-budget.js +5 -2
  142. package/dist/stats/writer.js +10 -6
  143. package/dist/trigger/audit.js +7 -0
  144. package/dist/trigger/authorization.js +105 -11
  145. package/dist/trigger/feedback.js +10 -0
  146. package/dist/trigger/history.js +37 -11
  147. package/dist/trigger/ipc-service.js +12 -1
  148. package/dist/trigger/manager.js +1 -0
  149. package/dist/trigger/scheduler.js +7 -5
  150. package/dist/trigger/script-executor.js +2 -1
  151. package/dist/trigger/script-sandbox.js +9 -3
  152. package/dist/trigger/validation.js +22 -0
  153. package/dist/utils/cross-platform.js +73 -26
  154. package/dist/utils/error-dict.json +94 -4
  155. package/dist/utils/error-utils.js +27 -4
  156. package/dist/utils/evolcore-version.js +36 -65
  157. package/dist/utils/msg-diag.js +1 -0
  158. package/dist/utils/process-introspect.js +12 -7
  159. package/dist/utils/process-tree.js +50 -2
  160. package/dist/utils/windows-shell-trust.js +2 -0
  161. package/dist/workbench/protocol.js +80 -0
  162. package/dist/workbench/service.js +359 -0
  163. package/ecagent/dist/types.d.ts +6 -2
  164. package/kits/docs/context-assembly.md +1 -1
  165. package/kits/docs/evolcore/INDEX.md +2 -2
  166. package/kits/docs/evolcore/config.md +12 -0
  167. package/kits/docs/evolcore/directory.md +22 -3
  168. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  169. package/kits/docs/evolcore/model.md +10 -0
  170. package/kits/docs/evolcore/peer.md +19 -65
  171. package/kits/docs/evolcore/provider.md +123 -3
  172. package/kits/docs/evolcore/role.md +80 -0
  173. package/kits/docs/evolcore/services.md +6 -6
  174. package/kits/docs/evolcore/team-workspace.md +1 -1
  175. package/kits/docs/evolcore/thread-chain.md +14 -15
  176. package/kits/docs/evolcore/tool-authorization.md +5 -0
  177. package/kits/docs/evolcore/trigger.md +10 -0
  178. package/kits/eck_message_manifest.json +12 -0
  179. package/kits/provider-templates.json +1213 -0
  180. package/kits/rules/04-relation.md +3 -3
  181. package/kits/schemas/_meta.json +14 -2
  182. package/kits/schemas/contact-book.schema.4.json +52 -0
  183. package/kits/schemas/providers.schema.3.json +200 -0
  184. package/kits/skills/.switches.json +4 -0
  185. package/kits/skills/ability/references/calling.md +1 -1
  186. package/kits/skills/ec-group/SKILL.md +2 -2
  187. package/kits/skills/ec-identity/SKILL.md +19 -72
  188. package/kits/skills/ec-provider/SKILL.md +221 -0
  189. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  190. package/kits/skills/ec-trigger/SKILL.md +1 -1
  191. package/kits/skills/thread-ops/SKILL.md +34 -21
  192. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  193. package/kits/templates/message-fragments/group-batch.md +1 -1
  194. package/kits/templates/message-fragments/inject-default.md +1 -1
  195. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  196. package/kits/templates/message-fragments/item-group.md +1 -1
  197. package/kits/templates/message-fragments/item-private.md +1 -1
  198. package/kits/templates/message-fragments/thread-context.md +1 -1
  199. package/kits/templates/message-fragments/trigger-session.md +1 -1
  200. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  201. package/kits/templates/roles/admin.json +2 -19
  202. package/kits/templates/roles/member.json +0 -3
  203. package/kits/templates/system-fragments/baseagent.md +6 -0
  204. package/kits/templates/system-fragments/commands.md +3 -3
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +1 -1
  207. package/kits/templates/system-fragments/thread.md +6 -5
  208. package/package.json +6 -4
  209. package/scripts/agent-template/inspect.mjs +4 -1
  210. package/scripts/agent-template/shared/common.mjs +2 -3
  211. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  212. package/scripts/agent-template/shared/template-package.mjs +9 -2
  213. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  214. package/scripts/agent-template/team-pack.mjs +6 -3
  215. package/dist/cli/peer.js +0 -127
  216. package/dist/config/peer-operation-service.js +0 -132
  217. package/dist/config/peer-request-service.js +0 -532
  218. package/dist/core/command/connect-menu.js +0 -624
@@ -223,6 +223,25 @@ export class PeerIdentityCache {
223
223
  : maxAgeMs;
224
224
  return cached.lastCheckedAt === 0 || Date.now() - cached.lastCheckedAt > effectiveMaxAge;
225
225
  }
226
+ /**
227
+ * 本地 agent.md 是否已与缓存快照不同。
228
+ *
229
+ * 名录同步和 SDK 的 `agentmd.changed` 观察会独立刷新本地 agent.md,但
230
+ * `peer-identity.json` 有 30 天时效;只靠 `lastCheckedAt` 会让名片改名
231
+ * 最长 30 天才生效。命中缓存时比对本地文件哈希,变了就走同步路径;
232
+ * 读不到本地文件则维持缓存。
233
+ */
234
+ static localAgentMdChanged(peerId, cached, aunPath) {
235
+ let content;
236
+ try {
237
+ content = fs.readFileSync(agentMdPath(peerId, aunPath), 'utf-8');
238
+ }
239
+ catch {
240
+ return false;
241
+ }
242
+ const hash = 'sha256:' + crypto.createHash('sha256').update(content, 'utf-8').digest('hex');
243
+ return hash !== cached.agentMdHash;
244
+ }
226
245
  /**
227
246
  * 从 agent.md 更新身份信息
228
247
  * @param source 'agentmd'(验签通过)或 'agentmd-unverified'(内容可解析但验签未过)
@@ -364,10 +383,13 @@ export class PeerIdentityCache {
364
383
  // 1. 缓存检查
365
384
  if (!forceRefresh && !this.needsRefresh(channelType, peerId, agentDir)) {
366
385
  const cached = this.get(channelType, peerId, agentDir);
367
- if (cached) {
386
+ if (cached && !this.localAgentMdChanged(peerId, cached, resolvedAunPath)) {
368
387
  logger.debug(`[PeerIdentityCache] Cache hit: ${channelType}#${peerId} type=${cached.type} age=${Math.floor((Date.now() - cached.lastCheckedAt) / 1000 / 60 / 60 / 24)}d`);
369
388
  return cached;
370
389
  }
390
+ if (cached) {
391
+ logger.debug(`[PeerIdentityCache] Local agent.md changed since cache: ${channelType}#${peerId}, refreshing`);
392
+ }
371
393
  }
372
394
  const cachePath = this.getFilePath(channelType, peerId, agentDir);
373
395
  const revision = this.invalidationRevisions.get(cachePath) ?? 0;
@@ -1,132 +1,101 @@
1
- import { createHash } from 'crypto';
2
1
  import { isValidAid } from '../../aun/aid/validation.js';
3
- import { parseAgentMdFrontmatter } from './peer-identity.js';
4
- export const SAME_OWNER_MAX_AGE_MS = 30_000;
5
- const SAME_OWNER_TIMEOUT_MS = 8_000;
6
- const runtimes = new Map();
2
+ import { ownerResolver, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
3
+ export const SAME_OWNER_MAX_AGE_MS = OWNERSHIP_CACHE_MAX_AGE_MS;
4
+ const clients = new Map();
5
+ // A fail-closed identity hint, never a second authorization cache.
7
6
  const knownTeams = new Map();
8
- let revision = 0;
9
7
  export function registerSameOwnerClient(selfAid, client, store) {
10
8
  unregisterSameOwnerClient(selfAid);
11
- const peers = knownTeams.get(selfAid) ?? new Set();
12
- knownTeams.set(selfAid, peers);
13
- const runtime = { client, store, generation: 0, entries: new Map(), pending: new Map(), knownTeams: peers, subscriptions: [] };
14
- runtimes.set(selfAid, runtime);
15
- const invalidate = () => {
16
- if (runtimes.get(selfAid) !== runtime)
17
- return;
18
- runtime.generation++;
19
- runtime.entries.clear();
20
- runtime.pending.clear();
21
- revision++;
22
- };
23
- for (const event of ['agentmd.changed', 'storage.object_changed', 'ownership.completed', 'ownership.rejected',
24
- 'ownership.stopped', 'ownership.error', 'disconnected']) {
25
- runtime.subscriptions.push(client.on(event, invalidate));
9
+ ownerResolver.registerEvidenceClient(selfAid, client, store);
10
+ const subscriptions = [];
11
+ for (const event of ['agentmd.changed', 'agent_md_changed', 'ownership.completed', 'ownership.rejected',
12
+ 'ownership.stopped', 'ownership.error']) {
13
+ subscriptions.push(client.on(event, payload => {
14
+ if (clients.get(selfAid)?.client !== client)
15
+ return;
16
+ const value = payload;
17
+ const aid = typeof payload === 'string' ? payload : value?.sub_aid ?? value?.aid;
18
+ if (aid && isValidAid(aid))
19
+ ownerResolver.invalidateEvidence(aid);
20
+ }));
26
21
  }
22
+ subscriptions.push(client.on('storage.object_changed', payload => {
23
+ if (clients.get(selfAid)?.client !== client)
24
+ return;
25
+ const value = payload;
26
+ const key = value?.object_key?.replace(/^\/+/, '');
27
+ const sub = key ? /^sub_aids\/([^/]+)\/owner\.md$/.exec(key)?.[1] : undefined;
28
+ const aid = sub ?? (key === 'agent.md' ? value.owner_aid : undefined);
29
+ if (aid && isValidAid(aid))
30
+ ownerResolver.invalidateEvidence(aid);
31
+ }));
32
+ clients.set(selfAid, { client, subscriptions });
27
33
  }
28
34
  export function unregisterSameOwnerClient(selfAid, client) {
29
- const runtime = runtimes.get(selfAid);
30
- if (!runtime || (client && runtime.client !== client))
35
+ const current = clients.get(selfAid);
36
+ if (!current || (client && current.client !== client))
31
37
  return;
32
- runtimes.delete(selfAid);
33
- revision++;
34
- for (const subscription of runtime.subscriptions)
38
+ clients.delete(selfAid);
39
+ for (const subscription of current.subscriptions)
35
40
  subscription.unsubscribe();
41
+ ownerResolver.unregisterEvidenceClient(selfAid, current.client);
42
+ }
43
+ function qualify(self, peer) {
44
+ if (self.refreshFailure || peer.refreshFailure || self.authorizationStatus !== 'verified'
45
+ || peer.authorizationStatus !== 'verified' || !self.profile || !peer.profile)
46
+ return 'unavailable';
47
+ if (self.profile.type !== 'agent' || peer.profile.type !== 'agent')
48
+ return 'unmatched';
49
+ return self.ownerAid && peer.ownerAid && self.ownerAid === peer.ownerAid ? 'matched' : 'unmatched';
36
50
  }
37
51
  export function sameOwnerQualification(selfAid, peerAid) {
38
- const runtime = runtimes.get(selfAid);
39
- const entry = runtime?.entries.get(peerAid);
40
- return runtime?.client.isReady && entry && entry.expiresAt > Date.now()
41
- ? entry.qualification : 'unavailable';
52
+ if (!isValidAid(selfAid) || !isValidAid(peerAid))
53
+ return 'unavailable';
54
+ return qualify(ownerResolver.snapshot(selfAid), ownerResolver.snapshot(peerAid));
42
55
  }
43
56
  export function sameOwnerRevision(selfAid) {
44
- const runtime = runtimes.get(selfAid);
45
- const entries = [...(runtime?.entries ?? [])].map(([peerAid, entry]) => [peerAid, entry.revision, entry.expiresAt > Date.now()]);
46
- return JSON.stringify([revision, runtime?.client.isReady === true, entries]);
57
+ if (!isValidAid(selfAid))
58
+ return '';
59
+ return JSON.stringify([ownerResolver.revision(selfAid), [...(knownTeams.get(selfAid) ?? [])]
60
+ .map(peer => [peer, ownerResolver.revision(peer), sameOwnerQualification(selfAid, peer)])]);
47
61
  }
48
62
  export function requiresSameOwnerProof(selfAid, peerAid) {
49
- return knownTeams.get(selfAid)?.has(peerAid) === true;
63
+ if (!isValidAid(selfAid) || !isValidAid(peerAid))
64
+ return false;
65
+ if (knownTeams.get(selfAid)?.has(peerAid) === true)
66
+ return true;
67
+ // Historical facts only keep a missing proof fail-closed after restart; they never grant a role.
68
+ const self = ownerResolver.snapshot(selfAid);
69
+ const peer = ownerResolver.snapshot(peerAid);
70
+ return self.profile?.type === 'agent' && peer.profile?.type === 'agent'
71
+ && !!self.relation?.ownerAid && self.relation.ownerAid === peer.relation?.ownerAid;
50
72
  }
51
73
  export async function prepareSameOwnerProof(selfAid, peerAid) {
52
- if (!selfAid || !peerAid || selfAid === peerAid || !isValidAid(selfAid) || !isValidAid(peerAid))
53
- return;
54
- const runtime = runtimes.get(selfAid);
55
- if (!runtime?.client.isReady)
56
- return;
57
- const cached = runtime.entries.get(peerAid);
58
- if (cached && cached.expiresAt > Date.now())
59
- return;
60
- const pending = runtime.pending.get(peerAid);
61
- if (pending)
62
- return pending;
63
- const generation = runtime.generation;
64
- const startedAt = Date.now();
65
- const query = async () => {
66
- // Lifecycle CLI commands never need profile verification or the AUN SDK.
67
- const { agentmdGet } = await import('../../aun/aid/agentmd.js');
68
- const cards = await Promise.all([selfAid, peerAid].map(aid => agentmdGet(aid, { store: runtime.store, withVerification: true, remoteOnly: true })));
69
- const profiles = cards.map((card, index) => {
70
- if (card.source !== 'remote' || card.verification.status !== 'verified')
71
- throw new Error('Unverified agent profile');
72
- const profile = parseAgentMdFrontmatter(card.content);
73
- if (profile.aid !== [selfAid, peerAid][index])
74
- throw new Error('Mismatched agent profile');
75
- return profile;
76
- });
77
- // 这里证明的是「同一个 Owner 名下的内部 agent」,**不是** PA Team 成员关系:
78
- // 团队归属由 contacts.json 的 open_pa_context 决定(见 owner-directory-scope.ts
79
- // 的 isInPaTeam),本模块不读那份名单。判据也不看 exttype 前缀——同 Owner 的
80
- // 非 PA agent 同样是内部联系人。human/service/device 不参与:它们拿不到
81
- // agent.md 里协议共识校验所需的 ownership statement。
82
- if (!profiles.every(profile => String(profile.type || '').trim().toLowerCase() === 'agent'))
83
- return 'unmatched';
84
- const consensuses = await Promise.all([selfAid, peerAid].map(aid => runtime.client.checkOwnershipConsensus(aid, true)));
85
- for (const [index, consensus] of consensuses.entries()) {
86
- const digest = createHash('sha256').update(cards[index].content, 'utf8').digest('hex');
87
- if (consensus.status !== 'consensus' || consensus.sub_aid !== [selfAid, peerAid][index]
88
- || consensus.lock !== 'locked' || !consensus.owner_aid || !isValidAid(consensus.owner_aid)
89
- || !Number.isSafeInteger(consensus.relation_version) || consensus.relation_version < 1
90
- || consensus.agent_md_sha256 !== digest
91
- || profiles[index].owner !== consensus.owner_aid)
92
- return 'unavailable';
93
- }
94
- return consensuses[0].owner_aid === consensuses[1].owner_aid ? 'matched' : 'unmatched';
95
- };
96
- const task = (async () => {
97
- let timeout;
98
- let qualification = 'unavailable';
99
- try {
100
- qualification = await Promise.race([query(), new Promise(resolve => {
101
- timeout = setTimeout(() => resolve('unavailable'), SAME_OWNER_TIMEOUT_MS);
102
- timeout.unref?.();
103
- })]);
104
- }
105
- catch {
106
- qualification = 'unavailable';
107
- }
108
- finally {
109
- if (timeout)
110
- clearTimeout(timeout);
111
- }
112
- if (runtimes.get(selfAid) !== runtime || runtime.generation !== generation || !runtime.client.isReady)
113
- return;
114
- if (qualification === 'matched')
115
- runtime.knownTeams.add(peerAid);
116
- if (qualification === 'unmatched')
117
- runtime.knownTeams.delete(peerAid);
118
- runtime.entries.set(peerAid, {
119
- qualification,
120
- expiresAt: startedAt + (qualification === 'unavailable' ? 2_000 : SAME_OWNER_MAX_AGE_MS),
121
- revision: ++revision,
122
- });
123
- })();
124
- runtime.pending.set(peerAid, task);
125
- try {
126
- await task;
74
+ if (!selfAid || !peerAid || selfAid === peerAid || !isValidAid(selfAid) || !isValidAid(peerAid)) {
75
+ return { qualification: 'unmatched' };
127
76
  }
128
- finally {
129
- if (runtime.pending.get(peerAid) === task)
130
- runtime.pending.delete(peerAid);
77
+ if (ownerResolver.owner(selfAid) === peerAid)
78
+ return { qualification: 'unmatched' };
79
+ if (!clients.has(selfAid)) {
80
+ return { qualification: sameOwnerQualification(selfAid, peerAid), retryable: true,
81
+ reason: 'Same-Owner authorization transport is unavailable' };
82
+ }
83
+ const views = await Promise.all([selfAid, peerAid].map(aid => ownerResolver.refresh(aid, {
84
+ observerAid: selfAid, requireProfile: true, maxAgeMs: SAME_OWNER_MAX_AGE_MS, source: 'same-owner',
85
+ })));
86
+ const qualification = qualify(views[0], views[1]);
87
+ const peers = knownTeams.get(selfAid) ?? new Set();
88
+ knownTeams.set(selfAid, peers);
89
+ if (qualification === 'matched')
90
+ peers.add(peerAid);
91
+ if (qualification === 'unmatched')
92
+ peers.delete(peerAid);
93
+ if (qualification === 'unavailable') {
94
+ const permanent = views.find(view => view.refreshFailure?.kind === 'permanent'
95
+ || ['invalid', 'released', 'unbound', 'single_sided', 'not_applicable'].includes(view.consensusStatus));
96
+ const failed = permanent ?? views.find(view => view.refreshFailure) ?? views[0];
97
+ return { qualification, retryable: !permanent,
98
+ reason: failed.refreshFailure?.reason ?? failed.reason ?? 'Ownership authorization evidence is unavailable' };
131
99
  }
100
+ return { qualification };
132
101
  }
@@ -15,7 +15,7 @@ import { logger } from '../../../utils/logger.js';
15
15
  import path from 'path';
16
16
  import fs from 'fs';
17
17
  import os from 'os';
18
- import { visitSessionHistory } from '../session-fs-store.js';
18
+ import { visitSessionHistory, visitSessionHistoryLines } from '../session-fs-store.js';
19
19
  const requireFromHere = createRequire(import.meta.url);
20
20
  let sqliteModule; // undefined = not tried, null = unavailable
21
21
  export const sanitizeCodexThreadTitle = sanitizeSessionTitle;
@@ -106,34 +106,30 @@ export class CodexSessionFileAdapter {
106
106
  * recoverable. Require the rollout to contain both its own session metadata
107
107
  * and the exact turn_context before EvolCore publishes a new binding.
108
108
  */
109
- checkTurnPersisted(_projectPath, agentSessionId, turnId, _agentAid) {
109
+ async checkTurnPersisted(_projectPath, agentSessionId, turnId, _agentAid) {
110
110
  const normalizedSessionId = agentSessionId.trim();
111
111
  const normalizedTurnId = turnId.trim();
112
112
  if (!normalizedSessionId || !normalizedTurnId)
113
113
  return false;
114
- let rolloutPath = null;
114
+ let preferred;
115
115
  const db = this.getDb();
116
116
  if (db) {
117
117
  try {
118
118
  const row = db.prepare('SELECT rollout_path FROM threads WHERE id = ? AND archived = 0').get(normalizedSessionId);
119
- rolloutPath = this.resolveRolloutPath(row?.rollout_path, normalizedSessionId);
119
+ preferred = row?.rollout_path;
120
120
  }
121
121
  catch (error) {
122
122
  logger.warn('[CodexAdapter] checkTurnPersisted DB query failed:', error);
123
123
  }
124
124
  }
125
- rolloutPath ??= this.findRolloutFile(normalizedSessionId);
125
+ const rolloutPath = await this.findRolloutFileAsync(normalizedSessionId, preferred);
126
126
  if (!rolloutPath)
127
127
  return false;
128
128
  try {
129
129
  let hasMatchingSession = false;
130
130
  let hasMatchingTurn = false;
131
- const lines = fs.readFileSync(rolloutPath, 'utf-8').split('\n');
132
- for (const line of lines) {
133
- if (!line.trim())
134
- continue;
131
+ await this.visitRolloutEvents(rolloutPath, event => {
135
132
  try {
136
- const event = JSON.parse(line);
137
133
  if (event?.type === 'session_meta') {
138
134
  const persistedSessionId = event.payload?.session_id ?? event.payload?.id;
139
135
  const version = event.payload?.version ?? event.payload?.cli_version;
@@ -144,19 +140,32 @@ export class CodexSessionFileAdapter {
144
140
  else if (event?.type === 'turn_context' && event.payload?.turn_id === normalizedTurnId) {
145
141
  hasMatchingTurn = true;
146
142
  }
147
- if (hasMatchingSession && hasMatchingTurn)
148
- return true;
149
143
  }
150
144
  catch {
151
- // The last JSONL line may still be in flight; a later poll retries it.
145
+ // Ignore unusable metadata, as with malformed JSONL records.
152
146
  }
153
- }
154
- return false;
147
+ if (hasMatchingSession && hasMatchingTurn)
148
+ return false;
149
+ });
150
+ return hasMatchingSession && hasMatchingTurn;
155
151
  }
156
152
  catch {
157
153
  return false;
158
154
  }
159
155
  }
156
+ /** Visit a bounded UTF-8 JSONL snapshot; false stops after sufficient evidence. */
157
+ async visitRolloutEvents(file, visit) {
158
+ await visitSessionHistoryLines(file, line => {
159
+ let event;
160
+ try {
161
+ event = JSON.parse(line);
162
+ }
163
+ catch {
164
+ return;
165
+ }
166
+ return visit(event);
167
+ });
168
+ }
160
169
  /**
161
170
  * 在 ~/.codex/sessions/ 下递归查找含 agentSessionId 的 rollout JSONL 文件
162
171
  */
@@ -216,6 +225,51 @@ export class CodexSessionFileAdapter {
216
225
  }
217
226
  return { turns: 0 };
218
227
  }
228
+ async getFileInfoAsync(_projectPath, agentSessionId) {
229
+ let row;
230
+ let initial;
231
+ const previewOptions = { includeSyntheticFallback: false, maxLength: 80 };
232
+ const db = this.getDb();
233
+ if (db) {
234
+ try {
235
+ const candidate = db.prepare('SELECT title, first_user_message, rollout_path FROM threads WHERE id = ?').get(agentSessionId);
236
+ if (candidate) {
237
+ initial = buildCliSessionPreview([candidate.first_user_message], 'codex', {
238
+ ...previewOptions, explicitTitle: candidate.title,
239
+ });
240
+ row = candidate;
241
+ }
242
+ }
243
+ catch (error) {
244
+ logger.warn('[CodexAdapter] getFileInfo DB query failed:', error);
245
+ }
246
+ }
247
+ const rollout = await this.findRolloutFileAsync(agentSessionId, row?.rollout_path);
248
+ let turns = 0;
249
+ let preview = initial;
250
+ if (rollout) {
251
+ try {
252
+ await this.visitRolloutEvents(rollout, event => {
253
+ if (event?.type === 'turn_context')
254
+ turns++;
255
+ if (preview && !preview.hasReal && event?.type === 'event_msg'
256
+ && event.payload?.type === 'user_message' && event.payload.message) {
257
+ try {
258
+ preview = buildCliSessionPreview([String(event.payload.message)], 'codex', {
259
+ ...previewOptions, explicitTitle: row.title,
260
+ });
261
+ }
262
+ catch { /* Skip unusable user messages, as in the synchronous reader. */ }
263
+ }
264
+ });
265
+ }
266
+ catch {
267
+ turns = 0;
268
+ preview = initial;
269
+ }
270
+ }
271
+ return row ? { turns, title: preview?.title || undefined } : { turns };
272
+ }
219
273
  readFirstMessage(projectPath, agentSessionId) {
220
274
  // 1. 优先查 state DB
221
275
  const db = this.getDb();
@@ -338,6 +392,33 @@ export class CodexSessionFileAdapter {
338
392
  return null;
339
393
  return this.readUserMessageFromRollout(rolloutPath, 'last');
340
394
  }
395
+ async readLastUserMessageAsync(_projectPath, agentSessionId) {
396
+ let preferred;
397
+ try {
398
+ preferred = this.getDb()?.prepare('SELECT rollout_path FROM threads WHERE id = ?').get(agentSessionId)?.rollout_path;
399
+ }
400
+ catch (error) {
401
+ logger.warn('[CodexAdapter] readLastUserMessage DB query failed:', error);
402
+ }
403
+ const rollout = await this.findRolloutFileAsync(agentSessionId, preferred);
404
+ if (!rollout)
405
+ return null;
406
+ const messages = [];
407
+ try {
408
+ await this.visitRolloutEvents(rollout, event => {
409
+ try {
410
+ if (event?.type === 'event_msg' && event.payload?.type === 'user_message' && event.payload.message) {
411
+ messages.push(String(event.payload.message));
412
+ }
413
+ }
414
+ catch { /* Skip unusable user messages, as in the synchronous reader. */ }
415
+ });
416
+ }
417
+ catch {
418
+ return null;
419
+ }
420
+ return buildCliSessionPreview(messages.reverse(), 'codex').title;
421
+ }
341
422
  scanCliSessions(projectPath, limit = 10) {
342
423
  const db = this.getDb();
343
424
  if (!db)
@@ -6,6 +6,7 @@ import { isDeepStrictEqual } from 'node:util';
6
6
  import path from 'path';
7
7
  import { logger } from '../../utils/logger.js';
8
8
  import { withFileLock } from '../../utils/atomic-write.js';
9
+ import { visitSessionHistoryLines } from './session-fs-store.js';
9
10
  /**
10
11
  * 检查会话文件健康度(接收完整文件路径)
11
12
  */
@@ -17,20 +18,25 @@ export async function checkSessionFile(sessionFile) {
17
18
  if (stats.size > 50 * 1024 * 1024) {
18
19
  issues.push(`会话文件过大: ${sizeMB.toFixed(1)}MB`);
19
20
  }
20
- const content = await fsPromises.readFile(sessionFile, 'utf-8');
21
- const lines = content.split('\n').filter(l => l.trim());
22
- for (let i = 0; i < lines.length; i++) {
21
+ let row = 0;
22
+ let corrupt = false;
23
+ await visitSessionHistoryLines(sessionFile, line => {
24
+ if (!line.trim())
25
+ return;
26
+ row++;
23
27
  try {
24
- JSON.parse(lines[i]);
28
+ JSON.parse(line);
25
29
  }
26
30
  catch (e) {
27
- issues.push(`会话文件格式损坏(第 ${i + 1} 行)`);
28
- return { healthy: false, issues, corrupt: true, fileSize: stats.size };
31
+ issues.push(`会话文件格式损坏(第 ${row} 行)`);
32
+ corrupt = true;
33
+ return false;
29
34
  }
30
- }
35
+ });
31
36
  return {
32
37
  healthy: issues.length === 0,
33
38
  issues,
39
+ ...(corrupt ? { corrupt: true } : {}),
34
40
  fileSize: stats.size
35
41
  };
36
42
  }
@@ -196,23 +196,89 @@ export const SESSION_META_COMPACT_POLICY = {
196
196
  function* iterateLinesBackward(fd, endExclusive, filePath) {
197
197
  const chunkSize = 64 * 1024;
198
198
  let cursor = endExclusive;
199
- let carry = Buffer.alloc(0);
199
+ let parts = [];
200
+ let partsBytes = 0;
200
201
  while (cursor > 0) {
201
202
  const start = Math.max(0, cursor - chunkSize);
202
203
  const chunk = readExactAt(fd, cursor - start, start, filePath);
203
- const buf = carry.length ? Buffer.concat([chunk, carry]) : chunk;
204
- let end = buf.length;
205
- let newline = buf.lastIndexOf(0x0a, end - 1);
204
+ let end = chunk.length;
205
+ let newline = chunk.lastIndexOf(0x0a, end - 1);
206
206
  while (newline >= 0) {
207
- yield buf.subarray(newline + 1, end);
207
+ const tail = chunk.subarray(newline + 1, end);
208
+ if (parts.length) {
209
+ // Assemble a cross-block line once; repeated concatenation is quadratic.
210
+ parts.push(tail);
211
+ yield Buffer.concat(parts.reverse(), partsBytes + tail.length);
212
+ parts = [];
213
+ partsBytes = 0;
214
+ }
215
+ else {
216
+ yield tail;
217
+ }
208
218
  end = newline;
209
- newline = end > 0 ? buf.lastIndexOf(0x0a, end - 1) : -1;
219
+ newline = end > 0 ? chunk.lastIndexOf(0x0a, end - 1) : -1;
220
+ }
221
+ if (end > 0) {
222
+ parts.push(chunk.subarray(0, end));
223
+ partsBytes += end;
210
224
  }
211
- carry = Buffer.from(buf.subarray(0, end));
212
225
  cursor = start;
213
226
  }
214
- if (carry.length)
215
- yield carry;
227
+ if (parts.length)
228
+ yield parts.length === 1 ? parts[0] : Buffer.concat(parts.reverse(), partsBytes);
229
+ }
230
+ /** Best-effort provider history, newest line first, bounded to the opened file's size. */
231
+ export function* readSessionHistoryBackward(filePath) {
232
+ let fd;
233
+ try {
234
+ fd = fs.openSync(filePath, 'r');
235
+ }
236
+ catch {
237
+ return;
238
+ }
239
+ try {
240
+ for (const line of iterateLinesBackward(fd, fs.fstatSync(fd).size, filePath))
241
+ yield line.toString('utf8');
242
+ }
243
+ catch { /* An unreadable history provides no further completion evidence. */ }
244
+ finally {
245
+ fs.closeSync(fd);
246
+ }
247
+ }
248
+ /** Visit complete UTF-8 lines in a bounded snapshot; false stops the read. */
249
+ export async function visitSessionHistoryLines(file, consume) {
250
+ let stream;
251
+ try {
252
+ const stat = await fs.promises.stat(file);
253
+ if (stat.size === 0 && stat.isFile()) {
254
+ // An empty history is valid only if it can actually be opened for reading.
255
+ const handle = await fs.promises.open(file, 'r');
256
+ await handle.close();
257
+ return;
258
+ }
259
+ stream = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: 1024 * 1024,
260
+ ...(stat.size > 0 ? { end: stat.size - 1 } : {}) });
261
+ // Only LF separates records; a bare CR must not turn invalid JSONL into valid records.
262
+ let fragments = [];
263
+ for await (const chunk of stream) {
264
+ const text = chunk;
265
+ let start = 0, end;
266
+ while ((end = text.indexOf('\n', start)) !== -1) {
267
+ const part = text.slice(start, end);
268
+ if (consume(fragments.length ? fragments.join('') + part : part) === false)
269
+ return;
270
+ fragments = [];
271
+ start = end + 1;
272
+ }
273
+ if (start < text.length)
274
+ fragments.push(text.slice(start));
275
+ }
276
+ if (fragments.length)
277
+ consume(fragments.join(''));
278
+ }
279
+ finally {
280
+ stream?.destroy();
281
+ }
216
282
  }
217
283
  /**
218
284
  * 快照日志的尾部压缩:文件超过 policy.maxBytes 时,只保留最近 keepLines 行
@@ -304,35 +370,25 @@ function recoverJsonlTail(fd, filePath) {
304
370
  const stat = fs.fstatSync(fd);
305
371
  if (stat.size === 0)
306
372
  return;
307
- const finalByte = Buffer.allocUnsafe(1);
308
- const finalRead = fs.readSync(fd, finalByte, 0, 1, stat.size - 1);
309
- if (finalRead !== 1)
310
- throw new Error(`short JSONL tail read while recovering ${filePath}`);
311
- if (finalByte[0] === 0x0a)
373
+ if (readExactAt(fd, 1, stat.size - 1, filePath)[0] === 0x0a)
312
374
  return;
313
- const chunkSize = 64 * 1024;
314
- let cursor = stat.size;
315
- let lastNewline = -1;
316
- while (cursor > 0 && lastNewline < 0) {
317
- const start = Math.max(0, cursor - chunkSize);
318
- const length = cursor - start;
319
- const chunk = Buffer.allocUnsafe(length);
320
- let offset = 0;
321
- while (offset < length) {
322
- const read = fs.readSync(fd, chunk, offset, length - offset, start + offset);
323
- if (read <= 0)
324
- throw new Error(`short JSONL read while recovering ${filePath}`);
325
- offset += read;
375
+ // Windows append handles may lack truncation rights. Keep O_APPEND for
376
+ // writes, but repair through a read/write handle to the very same file.
377
+ const repairFd = fs.openSync(filePath, 'r+');
378
+ try {
379
+ const repairStat = fs.fstatSync(repairFd);
380
+ if (repairStat.dev !== stat.dev || repairStat.ino !== stat.ino) {
381
+ throw new Error(`JSONL file changed while recovering ${filePath}`);
326
382
  }
327
- const index = chunk.lastIndexOf(0x0a);
328
- if (index >= 0)
329
- lastNewline = start + index;
330
- cursor = start;
383
+ // Recheck after reopening: another writer may have completed the tail.
384
+ if (repairStat.size === 0 || readExactAt(repairFd, 1, repairStat.size - 1, filePath)[0] === 0x0a)
385
+ return;
386
+ const committedSize = findLastNewline(repairFd, repairStat.size, filePath) + 1;
387
+ fs.ftruncateSync(repairFd, committedSize);
388
+ fs.fsyncSync(repairFd);
331
389
  }
332
- const committedSize = lastNewline < 0 ? 0 : lastNewline + 1;
333
- if (committedSize !== stat.size) {
334
- fs.ftruncateSync(fd, committedSize);
335
- fs.fsyncSync(fd);
390
+ finally {
391
+ fs.closeSync(repairFd);
336
392
  }
337
393
  }
338
394
  function readExactAt(fd, length, position, filePath) {