evolcore 0.0.43-test.6 → 0.0.43-test.7

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 (197) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bin/ecmsg.js +171 -54
  3. package/dist/agents/baseagent-availability.js +1 -1
  4. package/dist/agents/codex/app-server-client.js +22 -0
  5. package/dist/agents/codex-runner.js +69 -2
  6. package/dist/aun/msg/p2p.js +6 -1
  7. package/dist/channels/aun.js +234 -21
  8. package/dist/cli/agent-create.js +2 -2
  9. package/dist/cli/daemon-commands.js +6 -66
  10. package/dist/cli/daemon-lifecycle-client.js +61 -0
  11. package/dist/cli/ecmsg-gateway.js +35 -2
  12. package/dist/cli/events-command.js +73 -0
  13. package/dist/cli/index.js +31 -14
  14. package/dist/cli/invoke-command.js +182 -0
  15. package/dist/cli/managed-command-guard.js +6 -1
  16. package/dist/cli/restart-monitor.js +45 -47
  17. package/dist/cli/services-command.js +111 -0
  18. package/dist/cli/team-workspace-command.js +134 -0
  19. package/dist/cli/thread-command.js +6 -2
  20. package/dist/cli/watch-msg.js +1 -1
  21. package/dist/config/config-field-policy.js +2 -2
  22. package/dist/config/config-manager.js +0 -7
  23. package/dist/config/invoke-ipc-service.js +118 -0
  24. package/dist/config/schema-migration.js +6 -1
  25. package/dist/config-store.js +2 -1
  26. package/dist/core/agent-reload-coordinator.js +6 -4
  27. package/dist/core/agent-runtime.js +104 -10
  28. package/dist/core/auth/delegation-authorization.js +66 -0
  29. package/dist/core/auth/operation-catalog.js +20 -0
  30. package/dist/core/baseagent-loader.js +60 -130
  31. package/dist/core/channel-loader.js +10 -1
  32. package/dist/core/channel-runtime.js +4 -3
  33. package/dist/core/command/agent-control.js +1 -1
  34. package/dist/core/command/agent-storage-menu.js +1 -1
  35. package/dist/core/command/chatmode-config.js +2 -36
  36. package/dist/core/command/command-handler.js +53 -11
  37. package/dist/core/command/data-root-resolver.js +32 -23
  38. package/dist/core/command/eventcenter-menu.js +338 -0
  39. package/dist/core/command/menu-catalog.js +8 -0
  40. package/dist/core/command/menu-handler.js +198 -84
  41. package/dist/core/command/menu-protocol.js +60 -11
  42. package/dist/core/command/menu-query-batch.js +194 -0
  43. package/dist/core/command/slash-gate.js +1 -1
  44. package/dist/core/command/slash-handler.js +34 -42
  45. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  46. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  47. package/dist/core/command/team-workspace-initializer.js +2 -0
  48. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  49. package/dist/core/command/team-workspace-job-store.js +88 -0
  50. package/dist/core/command/team-workspace-management-service.js +2 -0
  51. package/dist/core/command/team-workspace-management-store.js +96 -0
  52. package/dist/core/command/team-workspace-management.js +265 -0
  53. package/dist/core/command/team-workspace-members-menu.js +88 -0
  54. package/dist/core/command/team-workspace-store.js +612 -0
  55. package/dist/core/command/team-workspace-team.js +193 -0
  56. package/dist/core/daemon-control.js +8 -5
  57. package/dist/core/daemon-lifecycle.js +132 -73
  58. package/dist/core/handoff/runtime.js +3 -3
  59. package/dist/core/invoke/executors/index.js +13 -0
  60. package/dist/core/invoke/executors/media.js +283 -0
  61. package/dist/core/invoke/executors/text.js +198 -0
  62. package/dist/core/invoke/invoke-service.js +157 -0
  63. package/dist/core/invoke/style-router.js +48 -0
  64. package/dist/core/invoke/types.js +19 -0
  65. package/dist/core/ipc-registration.js +46 -7
  66. package/dist/core/memory/consolidation.js +7 -5
  67. package/dist/core/message/aun-ipc-sender.js +147 -17
  68. package/dist/core/message/im-renderer.js +28 -84
  69. package/dist/core/message/message-bridge.js +4 -0
  70. package/dist/core/message/message-utils.js +10 -2
  71. package/dist/core/message/peer-mode.js +7 -34
  72. package/dist/core/message/response-engine.js +157 -54
  73. package/dist/core/message/send-options.js +7 -4
  74. package/dist/core/message/send-routing.js +43 -5
  75. package/dist/core/ownership/owner-resolver.js +7 -0
  76. package/dist/core/permission/ec-command-parser.js +3 -2
  77. package/dist/core/permission/protected-paths.js +12 -2
  78. package/dist/core/permission/shell-environment.js +9 -0
  79. package/dist/core/session/session-file-health.js +243 -0
  80. package/dist/core/session/session-fs-store.js +2 -3
  81. package/dist/core/task/task-recovery-service.js +13 -2
  82. package/dist/core/thread/command-parser.js +9 -2
  83. package/dist/core/thread/thread-operation.js +21 -2
  84. package/dist/core/thread/thread-route.js +13 -2
  85. package/dist/directory/owner-directory-admission.js +40 -53
  86. package/dist/directory/owner-directory-cache.js +89 -113
  87. package/dist/directory/owner-directory-query-operation.js +8 -10
  88. package/dist/eck/kit-renderer.js +7 -5
  89. package/dist/ecweb/basic-settings-service.js +1 -1
  90. package/dist/ecweb/message-context-service.js +0 -4
  91. package/dist/ecweb/runtime/lifecycle.js +6 -2
  92. package/dist/ecweb/runtime/supervisor.js +19 -4
  93. package/dist/event-center/admission-materializer.js +114 -0
  94. package/dist/event-center/bus-gate.js +136 -0
  95. package/dist/event-center/bus-host.js +290 -0
  96. package/dist/event-center/bus-resolver.js +120 -0
  97. package/dist/event-center/center-config.js +100 -0
  98. package/dist/event-center/client-factory.js +50 -0
  99. package/dist/event-center/daemon.js +45 -0
  100. package/dist/event-center/directory-source.js +53 -0
  101. package/dist/event-center/dispatcher.js +157 -0
  102. package/dist/event-center/event-log.js +110 -0
  103. package/dist/event-center/index-generator.js +63 -0
  104. package/dist/event-center/ipc-operation.js +308 -0
  105. package/dist/event-center/ledger.js +52 -0
  106. package/dist/event-center/pack-loader.js +202 -0
  107. package/dist/event-center/pack-manager.js +85 -0
  108. package/dist/event-center/registry.js +238 -0
  109. package/dist/event-center/runtime.js +641 -0
  110. package/dist/event-center/script-runner.js +356 -0
  111. package/dist/event-center/types.js +35 -0
  112. package/dist/event-center/validation.js +413 -0
  113. package/dist/index.js +285 -99
  114. package/dist/ipc.js +66 -12
  115. package/dist/paths.js +20 -0
  116. package/dist/product.js +14 -0
  117. package/dist/proxy/manager.js +5 -1
  118. package/dist/proxy/service-supervisor.js +13 -4
  119. package/dist/response-system/engines/v1/index.js +0 -1
  120. package/dist/response-system/modes/single-session/index.js +1 -1
  121. package/dist/services/dispatcher.js +100 -0
  122. package/dist/services/idempotency.js +90 -0
  123. package/dist/services/identity.js +52 -0
  124. package/dist/services/index-generator.js +70 -0
  125. package/dist/services/index.js +449 -0
  126. package/dist/services/ipc-operation.js +458 -0
  127. package/dist/services/ledger.js +52 -0
  128. package/dist/services/message-log.js +112 -0
  129. package/dist/services/pack-manager.js +204 -0
  130. package/dist/services/reply.js +55 -0
  131. package/dist/services/router.js +95 -0
  132. package/dist/services/script-runner.js +422 -0
  133. package/dist/services/service-payload.js +70 -0
  134. package/dist/services/types.js +18 -0
  135. package/dist/services/validation.js +297 -0
  136. package/dist/trigger/application-service.js +18 -0
  137. package/dist/trigger/event-source.js +1 -1
  138. package/dist/trigger/ipc-service.js +3 -1
  139. package/dist/trigger/script-sandbox.js +118 -22
  140. package/dist/utils/cross-platform.js +24 -10
  141. package/dist/utils/evolcore-version.js +69 -27
  142. package/dist/utils/instance-registry.js +19 -13
  143. package/dist/utils/process-introspect.js +45 -9
  144. package/dist/utils/startup-trace.js +74 -37
  145. package/dist/utils/windows-shell-trust.js +80 -6
  146. package/kits/docs/INDEX.md +2 -2
  147. package/kits/docs/aun/ABILITY_CALLING.md +7 -14
  148. package/kits/docs/context-assembly.md +1 -1
  149. package/kits/docs/evolcore/INDEX.md +2 -0
  150. package/kits/docs/evolcore/ability.md +4 -0
  151. package/kits/docs/evolcore/aid.md +1 -1
  152. package/kits/docs/evolcore/event-center.md +207 -0
  153. package/kits/docs/evolcore/file-navigation.md +10 -264
  154. package/kits/docs/evolcore/fs.md +3 -2
  155. package/kits/docs/evolcore/group.md +1 -1
  156. package/kits/docs/evolcore/memory-architecture.md +2 -0
  157. package/kits/docs/evolcore/menu-protocol.md +21 -0
  158. package/kits/docs/evolcore/msg.md +15 -3
  159. package/kits/docs/evolcore/provider.md +3 -1
  160. package/kits/docs/evolcore/response.md +5 -5
  161. package/kits/docs/evolcore/services.md +277 -0
  162. package/kits/docs/evolcore/task.md +2 -0
  163. package/kits/docs/evolcore/team-workspace.md +41 -0
  164. package/kits/eck_manifest.json +26 -0
  165. package/kits/rules/02-navigation.md +10 -1
  166. package/kits/schemas/_meta.json +17 -6
  167. package/kits/schemas/agent-config.schema.19.json +5 -7
  168. package/kits/schemas/agent-config.schema.20.json +936 -0
  169. package/kits/schemas/relation-config.schema.12.json +2 -3
  170. package/kits/schemas/role-config.schema.2.json +4 -4
  171. package/kits/skills/.switches.json +1 -5
  172. package/kits/skills/ability/SKILL.md +56 -0
  173. package/kits/skills/ability/references/calling.md +56 -0
  174. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  175. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  176. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  177. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  178. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  179. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  180. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  181. package/kits/skills/personal-assistant/SKILL.md +6 -6
  182. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  183. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  184. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  185. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  186. package/kits/templates/system-fragments/channel.md +3 -3
  187. package/kits/templates/system-fragments/commands.md +5 -3
  188. package/kits/templates/system-fragments/reply.md +0 -5
  189. package/kits/templates/system-fragments/thread.md +10 -8
  190. package/package.json +3 -5
  191. package/dist/cli/pa-workspace-command.js +0 -225
  192. package/dist/core/command/pa-workspace-store.js +0 -468
  193. package/dist/core/relation/pa-team.js +0 -132
  194. package/kits/docs/evolcore/pa-workspace.md +0 -51
  195. package/kits/skills/aid-ability/SKILL.md +0 -244
  196. package/kits/skills/ec-ability/SKILL.md +0 -67
  197. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -1,3 +1,12 @@
1
+ import { CODEX_HEADER_ENV_PREFIX, SERVICE_SESSION_ENV_NAMES } from '../../product.js';
2
+ const SERVICE_SESSION_ENV = new Set(SERVICE_SESSION_ENV_NAMES);
3
+ /** Preserve infrastructure and application settings without inheriting task authority. */
4
+ export function sanitizeServiceEnvironment(input) {
5
+ return Object.fromEntries(Object.entries(input).filter(([name]) => {
6
+ const normalized = name.toUpperCase();
7
+ return !SERVICE_SESSION_ENV.has(normalized) && !normalized.startsWith(CODEX_HEADER_ENV_PREFIX);
8
+ }));
9
+ }
1
10
  const SHELL_CODE_INJECTION_ENV = new Set([
2
11
  'BASH_ENV',
3
12
  'BASHOPTS',
@@ -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
+ }
@@ -593,8 +593,7 @@ export async function readAllJsonlLinesAsync(filePath) {
593
593
  }
594
594
  return results;
595
595
  }
596
- /** Scan only one Agent/channel, with bounded asynchronous directory reads. */
597
- export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey) {
596
+ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey, options) {
598
597
  if (!selfAID || selfAID === '.' || selfAID === '..')
599
598
  throw new Error('invalid selfAID');
600
599
  const sessionsDir = path.join(sessionsRoot, encodeSegment(selfAID), 'sessions');
@@ -632,7 +631,7 @@ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey)
632
631
  if (!payload.some(isSessionPayload))
633
632
  return undefined;
634
633
  return { channelType: parsed.channelType, selfAID, channelId: parsed.channelId,
635
- channelKey: key, channelSessionKey: entry.name, dirPath };
634
+ channelKey: key, channelSessionKey: entry.name, dirPath, ...(options?.includeEntries ? { entries: payload } : {}) };
636
635
  }));
637
636
  for (const chat of batch)
638
637
  if (chat)
@@ -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())
@@ -1,6 +1,22 @@
1
1
  import { logger } from '../../utils/logger.js';
2
+ import { readAunPeerKind } from '../relation/peer-identity.js';
2
3
  import { ThreadService, normalizeThreadPeer } from './thread-service.js';
3
4
  import { isMainSessionThreadId, isTopicThreadId, safeFormatMainTopicId } from './topic-id.js';
5
+ /**
6
+ * 建话题时对端类型的默认来源:本地关系证据(agent.md 缓存 / 关系配置)。
7
+ * 证据不可用时不阻塞建话题,按私聊兜底——与发送路径的判定口径一致。
8
+ */
9
+ function inferThreadPeerKind(selfAid, peer) {
10
+ try {
11
+ const kind = readAunPeerKind(selfAid, peer).kind;
12
+ if (kind === 'group' || kind === 'private')
13
+ return kind;
14
+ }
15
+ catch {
16
+ // 关系证据读取失败不算错误。
17
+ }
18
+ return 'private';
19
+ }
4
20
  /**
5
21
  * Emit the existing cross-device rename event after a local rename succeeds.
6
22
  * Storage stays in ThreadService; transport stays in the operation layer.
@@ -140,10 +156,13 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
140
156
  case 'create': {
141
157
  if (!request.peer || !request.name)
142
158
  return { ok: false, code: 'MISSING_ARGS', error: 'peer and name required' };
159
+ // 没显式写 --group / --private 时按关系证据推断:群话题被记成 private
160
+ // 会让后续 scope 选择、群规则、通知范围全部走错。
161
+ const peerKind = request.peerKind ?? inferThreadPeerKind(selfAid, request.peer);
143
162
  const result = await threadService.createThread({
144
163
  selfAid,
145
164
  peer: request.peer,
146
- peerKind: request.peerKind ?? 'private',
165
+ peerKind,
147
166
  name: request.name,
148
167
  label: request.label ?? undefined,
149
168
  topicStatus: request.topicStatus,
@@ -155,7 +174,7 @@ async function _executeThreadOperation(request, threadService, sendSystemMsg) {
155
174
  to: request.peer,
156
175
  threadId: result.threadId,
157
176
  topicName: result.name,
158
- peerKind: request.peerKind ?? 'private',
177
+ peerKind,
159
178
  // 与 rename 相同:授权链需要托管上下文,宿主调用则留空(跳过通知)。
160
179
  originSessionId: request.originSessionId,
161
180
  delegationToken: request.delegationToken,
@@ -11,11 +11,19 @@ import { isMainSessionThreadId, resolveThreadRef } from './topic-id.js';
11
11
  *
12
12
  * 话题必须存在于本端:话题查索引,主话题查该关系的 active session。
13
13
  * 返回 undefined 表示该引用不能作为跨话题路由依据。
14
+ *
15
+ * `options.allowSelfTarget`(self-address):`target` 是本端自己的 AID 时,
16
+ * 它不是「话题对端」而是「收件人」,与 `entry.peer` 天然不一致。此时跳过
17
+ * 一致性校验,仍按引用返回话题条目——话题归属不变,变的只是投给谁。
14
18
  */
15
- export function resolveThreadRouteTarget(selfAid, threadRef, scope, target) {
19
+ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target, options = {}) {
16
20
  if (!selfAid)
17
21
  return undefined;
18
22
  const normalizedSelf = selfAid.replace(/^@/, '');
23
+ // 自发:收件人是本端,不能拿它和话题对端比。
24
+ const selfTargeted = options.allowSelfTarget === true
25
+ && target !== undefined
26
+ && target.replace(/^@/, '').toLowerCase() === normalizedSelf.toLowerCase();
19
27
  const resolved = resolveThreadRef(threadRef, normalizedSelf);
20
28
  if (resolved.kind === 'invalid' || resolved.kind === 'current')
21
29
  return undefined;
@@ -26,7 +34,7 @@ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target) {
26
34
  const effectiveTarget = peerFromRef ?? target;
27
35
  if (!effectiveTarget)
28
36
  return undefined;
29
- if (target !== undefined && peerFromRef !== undefined) {
37
+ if (target !== undefined && peerFromRef !== undefined && !selfTargeted) {
30
38
  const normalizedTarget = target.replace(/^@/, '');
31
39
  const matches = scope === 'group'
32
40
  ? sameGroupAid(peerFromRef, normalizedTarget)
@@ -76,6 +84,9 @@ export function resolveThreadRouteTarget(selfAid, threadRef, scope, target) {
76
84
  }
77
85
  if (target === undefined)
78
86
  return entry;
87
+ // 自发:收件人是本端,话题归属仍由 entry.peer 决定,不做一致性校验。
88
+ if (selfTargeted)
89
+ return entry;
79
90
  const normalizedTarget = target.replace(/^@/, '');
80
91
  const matches = scope === 'group'
81
92
  ? sameGroupAid(entry.peer, normalizedTarget)
@@ -42,11 +42,10 @@ export function liveOwnerDirectoryCache(selfAid) {
42
42
  * 时按 AID 临时读一次本地快照重新渲染,产出同样的字节。后者多一次读盘,
43
43
  * 但保证"配置一改,注入就变",不必等到下一条入站消息。
44
44
  *
45
- * **ownerAid 必须取自 authorization.json,不能用 `ownerResolver` 猜。** 离线时
46
- * 解析器只能给出 known owner(可能来自过期缓存或另一条关系),一旦与授权文件里的
47
- * grantee/owner 对不上,`scopeAccess` 就不是 authorized,`directoryGone()` 随之
48
- * 判真,`refreshMarkdown` 会把 `directory.md` 删掉——一个只读的开关变更变成删注入源。
49
- * 授权文件缺失时直接返回 false:没有授权就没有可渲染的内容,也不该动现有文件。
45
+ * **ownerAid 取自本地快照信封,不用 `ownerResolver` 猜。** 离线时解析器只能给出
46
+ * known owner(可能来自过期缓存或另一条关系),一旦与快照里的 owner 对不上,
47
+ * `directoryGone()` 会判真,`refreshMarkdown` 会把 `directory.md` 删掉——一个只读的
48
+ * 开关变更变成删注入源。快照不存在时直接返回 false:没有可渲染的内容,也不该动现有文件。
50
49
  */
51
50
  export function refreshDirectoryMarkdown(selfAid) {
52
51
  const live = liveOwnerDirectoryCache(selfAid);
@@ -55,7 +54,7 @@ export function refreshDirectoryMarkdown(selfAid) {
55
54
  return true;
56
55
  }
57
56
  const directory = path.join(agentDir(selfAid), 'directory');
58
- const ownerAid = authorizedOwnerAid(directory, selfAid);
57
+ const ownerAid = snapshotOwnerAid(directory, selfAid);
59
58
  if (!ownerAid)
60
59
  return false;
61
60
  try {
@@ -68,29 +67,12 @@ export function refreshDirectoryMarkdown(selfAid) {
68
67
  }
69
68
  }
70
69
  /**
71
- * 从 `authorization.json` 读出授权是的哪个 Owner。只认与本 agent 匹配的凭证。
70
+ * 从本地快照信封(`contacts.json`)里读出这份名录属于哪个 Owner。
72
71
  *
73
- * 与 `OwnerDirectoryCache.loadGrant` 同一条判据,但不依赖缓存实例——这里只是
74
- * 为了在无活缓存时找到一个与磁盘授权一致的 ownerAid,好让 `scopeAccess` 有据可查。
72
+ * 这是 ownerAid 的**唯一来源**:`authorization.json` 已废弃,不再读取。
73
+ * 快照自带 `ownerAid` 与 `granteeAid`,能自证归属,不需要外部凭证佐证。
75
74
  */
76
- export function authorizedOwnerAid(directory, selfAid) {
77
- try {
78
- const raw = JSON.parse(fs.readFileSync(path.join(directory, 'authorization.json'), 'utf8'));
79
- if (!raw || typeof raw !== 'object' || Array.isArray(raw))
80
- return undefined;
81
- const record = raw;
82
- if (record.granteeAid !== selfAid)
83
- return undefined;
84
- const ownerAid = typeof record.ownerAid === 'string' ? record.ownerAid.trim() : '';
85
- return ownerAid || undefined;
86
- }
87
- catch {
88
- // 没有授权文件时退到本地快照信封:预置团队只带 contacts.json,不拉远端。
89
- return snapshotOwnerAid(directory, selfAid);
90
- }
91
- }
92
- /** 从 agent 本地快照信封(`contacts.json`)里读出 ownerAid。 */
93
- function snapshotOwnerAid(directory, selfAid) {
75
+ export function snapshotOwnerAid(directory, selfAid) {
94
76
  try {
95
77
  const raw = JSON.parse(fs.readFileSync(path.join(directory, 'contacts.json'), 'utf8'));
96
78
  if (!raw || typeof raw !== 'object' || Array.isArray(raw))
@@ -118,8 +100,6 @@ export async function refreshOwnerDirectory(selfAid) {
118
100
  const live = liveOwnerDirectoryCache(selfAid);
119
101
  const scope = OWNER_DIRECTORY_SCOPES[0];
120
102
  if (live) {
121
- if (live.scopeAccess(scope) !== 'authorized')
122
- return { pulled: false, regenerated: false };
123
103
  let timer;
124
104
  try {
125
105
  // 空 digests = 无条件拉取,不做摘要比对。
@@ -152,8 +132,6 @@ export async function syncOwnerDirectoryForLookup(selfAid) {
152
132
  if (!cache)
153
133
  return false;
154
134
  const scope = OWNER_DIRECTORY_SCOPES[0];
155
- if (cache.scopeAccess(scope) !== 'authorized')
156
- return false;
157
135
  const before = cache.readSnapshot(scope)?.contentDigest;
158
136
  // 把 pending 里带的通知 digest 一起传下去:与共享缓存一致时 0 次网络请求。
159
137
  // 未命中的场景恰恰常发生在"通知刚到、共享缓存已拉过",不传等于白拉一次。
@@ -183,9 +161,16 @@ export async function prepareOwnerDirectoryAdmission(selfAid, aid) {
183
161
  if (ownerResolver.owner(selfAid) !== live.ownerAid)
184
162
  return;
185
163
  const scope = OWNER_DIRECTORY_SCOPES[0];
186
- if (live.cache.scopeAccess(scope) !== 'authorized')
187
- return;
188
- const found = live.cache.readSnapshot(scope)?.entries.some(entry => entry.aid === aid) ?? false;
164
+ // 坏快照解析会抛:这里只是准入前的预热,读不出来就当未命中,交给准入路径自己判。
165
+ const snapshotEntries = (() => {
166
+ try {
167
+ return live.cache.readSnapshot(scope)?.entries;
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ })();
173
+ const found = snapshotEntries?.some(entry => entry.aid === aid) ?? false;
189
174
  if (found) {
190
175
  // 已知成员:只允许一次后台刷新,不阻塞本条消息的处理。
191
176
  void live.cache.lookupByAid(scope, aid).catch(() => { });
@@ -226,36 +211,38 @@ export function readOwnerDirectoryMembership(selfAid, aid, appOwned = false) {
226
211
  const directory = path.join(agentDir(selfAid), 'directory');
227
212
  // "从未接入名录"与"接入过但当前不可用"是两种结论,判据是盘上有没有痕迹。
228
213
  // 原子写的热备名(`*.json_`)由 existsAtomic 负责,业务层不关心后缀。
229
- const configured = existsAtomic(path.join(directory, 'authorization.json'))
230
- || existsAtomic(path.join(directory, 'contacts.json'));
231
- if (!configured && !appOwned)
232
- return undefined;
233
- const ownerAid = ownerResolver.owner(selfAid);
214
+ const configured = existsAtomic(path.join(directory, 'contacts.json'));
215
+ if (!configured) {
216
+ // 没有名录文件:普通消息准入保持旧行为(交给调用方的开关/白名单判断);
217
+ // App 侧一律按目录不可用处理,不因"没数据"放宽。
218
+ if (!appOwned)
219
+ return undefined;
220
+ logDirectoryAdmissionUnavailable(selfAid, aid, 'snapshot_missing');
221
+ return { category: 'unavailable' };
222
+ }
223
+ // ownerAid 优先取快照信封:它自证归属,离线也能用。解析器只在没有快照时兜底。
224
+ const snapshotOwner = snapshotOwnerAid(directory, selfAid);
225
+ const resolvedOwner = ownerResolver.owner(selfAid);
226
+ // 协议 Owner 已解析、却与快照归属不同:名录是上一个 Owner 的,不能拿做过期准入。
227
+ // 解析不出来(离线、共识过期)不算冲突——那一侧交给快照信封自证。
228
+ if (snapshotOwner && resolvedOwner && snapshotOwner !== resolvedOwner) {
229
+ logDirectoryAdmissionUnavailable(selfAid, aid, 'owner_mismatch', resolvedOwner);
230
+ return { category: 'unavailable' };
231
+ }
232
+ const ownerAid = snapshotOwner ?? resolvedOwner;
234
233
  if (!ownerAid) {
235
234
  logDirectoryAdmissionUnavailable(selfAid, aid, 'owner_unresolved');
236
235
  return { category: 'unavailable' };
237
236
  }
238
237
  try {
238
+ const scope = OWNER_DIRECTORY_SCOPES[0];
239
239
  const relationVersion = appOwned ? ownerResolver.snapshot(selfAid).consensus?.relation_version : undefined;
240
240
  if (appOwned && (!Number.isSafeInteger(relationVersion) || (relationVersion ?? 0) <= 0))
241
241
  return { category: 'unavailable' };
242
242
  const cache = new OwnerDirectoryCache({ selfAid, ownerAid, directory, relationVersion });
243
- const scope = OWNER_DIRECTORY_SCOPES[0];
244
- const accessReason = cache.scopeAccessUnavailableReason(scope);
245
- // 本地快照可以脱离授权文件单独使用:预置团队(构建期写入 contacts.json、从不拉取远端)
246
- // 没有 authorization.json,只要快照本身可读,就按快照判定准入。
247
- // 授权过期(authorization_expired)仍然拦截——那是远端明确撤下的结论,不能靠本地文件续命。
248
- const localSnapshotOnly = accessReason === 'authorization_missing_or_invalid';
249
- if (accessReason && !localSnapshotOnly) {
250
- logDirectoryAdmissionUnavailable(selfAid, aid, accessReason, ownerAid);
251
- return { category: 'unavailable' };
252
- }
243
+ // 判据只有一条:快照文件在不在。授权凭证不参与任何判断。
253
244
  const snapshot = cache.readSnapshot(scope);
254
245
  if (!snapshot) {
255
- if (localSnapshotOnly) {
256
- logDirectoryAdmissionUnavailable(selfAid, aid, accessReason, ownerAid);
257
- return { category: 'unavailable' };
258
- }
259
246
  logDirectoryAdmissionUnavailable(selfAid, aid, existsAtomic(path.join(directory, `${scope}.json`)) ? 'snapshot_invalid' : 'snapshot_missing', ownerAid);
260
247
  return { category: 'unavailable' };
261
248
  }