evolcore 0.0.43-test.5 → 0.0.43-test.6

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 (116) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bin/ecmsg.js +126 -43
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +6 -6
  8. package/dist/aun/group/invite-service.js +3 -2
  9. package/dist/aun/service-proxy.js +18 -6
  10. package/dist/channels/aun.js +73 -10
  11. package/dist/cli/agent-create.js +16 -6
  12. package/dist/cli/aun-commands.js +9 -1
  13. package/dist/cli/daemon-commands.js +30 -1
  14. package/dist/cli/ecmsg-gateway.js +3 -1
  15. package/dist/cli/init.js +75 -0
  16. package/dist/cli/provider-command.js +1 -1
  17. package/dist/cli/restart-monitor.js +24 -5
  18. package/dist/cli/task-context.js +38 -1
  19. package/dist/cli/watch-logs.js +6 -4
  20. package/dist/config/boot-log.js +6 -4
  21. package/dist/config/builtin-roles.js +2 -2
  22. package/dist/config/config-manager.js +1 -1
  23. package/dist/config/peer-role-resolver.js +1 -1
  24. package/dist/config/provider-identity-migration.js +92 -17
  25. package/dist/config/provider-local-sync.js +2 -0
  26. package/dist/config/providers-config.js +13 -0
  27. package/dist/config/providers-management.js +100 -10
  28. package/dist/config/role-service.js +8 -8
  29. package/dist/config/role-store.js +22 -22
  30. package/dist/config/schema-migration.js +80 -87
  31. package/dist/config/snapshot.js +70 -41
  32. package/dist/core/agent-runtime.js +44 -7
  33. package/dist/core/baseagent-loader.js +114 -11
  34. package/dist/core/channel-loader.js +36 -13
  35. package/dist/core/channel-runtime.js +112 -42
  36. package/dist/core/command/command-handler.js +5 -5
  37. package/dist/core/command/menu-handler.js +8 -3
  38. package/dist/core/command/menu-protocol.js +82 -11
  39. package/dist/core/command/role-menu.js +27 -15
  40. package/dist/core/daemon-control.js +42 -15
  41. package/dist/core/daemon-lifecycle.js +411 -67
  42. package/dist/core/handoff/dispatcher.js +9 -3
  43. package/dist/core/handoff/runtime.js +130 -42
  44. package/dist/core/handoff/store.js +190 -2
  45. package/dist/core/handoff/types.js +5 -0
  46. package/dist/core/initialization/service.js +4 -4
  47. package/dist/core/ipc-registration.js +5 -4
  48. package/dist/core/lifecycle-notice.js +10 -4
  49. package/dist/core/message/aun-ipc-sender.js +2 -2
  50. package/dist/core/message/message-bridge.js +53 -4
  51. package/dist/core/message/message-queue.js +46 -4
  52. package/dist/core/message/pending-hints.js +4 -10
  53. package/dist/core/message/response-engine.js +10 -2
  54. package/dist/core/message/send-routing.js +12 -2
  55. package/dist/core/ownership/owner-resolver.js +1 -0
  56. package/dist/core/permission/ec-command-parser.js +11 -1
  57. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  58. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  59. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  60. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  61. package/dist/core/session/session-fs-store.js +164 -3
  62. package/dist/core/session/session-idle-monitor.js +9 -1
  63. package/dist/core/session/session-manager.js +36 -2
  64. package/dist/directory/owner-directory-admission.js +26 -1
  65. package/dist/directory/owner-directory-cache.js +57 -16
  66. package/dist/directory/owner-directory-query-operation.js +4 -1
  67. package/dist/ecweb/runtime/lifecycle.js +9 -7
  68. package/dist/ecweb/runtime/supervisor.js +44 -27
  69. package/dist/index.js +548 -251
  70. package/dist/proxy/manager.js +38 -17
  71. package/dist/proxy/service-supervisor.js +65 -31
  72. package/dist/trigger/application-service.js +3 -1
  73. package/dist/trigger/audit.js +19 -4
  74. package/dist/trigger/authorization.js +14 -5
  75. package/dist/trigger/history.js +176 -7
  76. package/dist/trigger/manager.js +1 -3
  77. package/dist/trigger/scheduler.js +78 -5
  78. package/dist/utils/cross-platform.js +152 -4
  79. package/dist/utils/host-info.js +11 -8
  80. package/dist/utils/npm-ops.js +48 -0
  81. package/dist/utils/process-introspect.js +64 -1
  82. package/dist/utils/startup-trace.js +160 -19
  83. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  84. package/kits/docs/evolcore/INDEX.md +3 -2
  85. package/kits/docs/evolcore/ctl.md +2 -1
  86. package/kits/docs/evolcore/group.md +2 -2
  87. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  88. package/kits/docs/evolcore/msg.md +13 -6
  89. package/kits/docs/evolcore/provider.md +21 -3
  90. package/kits/docs/evolcore/response.md +1 -1
  91. package/kits/eck_manifest.json +19 -7
  92. package/kits/eck_message_manifest.json +3 -3
  93. package/kits/rules/06-channel.md +5 -6
  94. package/kits/schemas/daemon.schema.1.json +5 -0
  95. package/kits/schemas/daemon.schema.2.json +5 -0
  96. package/kits/schemas/daemon.schema.3.json +2 -1
  97. package/kits/schemas/daemon.schema.4.json +2 -1
  98. package/kits/schemas/daemon.schema.5.json +2 -1
  99. package/kits/schemas/daemon.schema.6.json +1 -1
  100. package/kits/schemas/daemon.schema.7.json +1 -1
  101. package/kits/schemas/daemon.schema.8.json +2 -1
  102. package/kits/schemas/daemon.schema.9.json +2 -1
  103. package/kits/schemas/role-registry.schema.1.json +2 -2
  104. package/kits/schemas/single-session.schema.1.json +1 -1
  105. package/kits/schemas/single-session.schema.2.json +1 -1
  106. package/kits/schemas/single-session.schema.3.json +1 -1
  107. package/kits/skills/aid-ability/SKILL.md +7 -7
  108. package/kits/skills/ec-group/SKILL.md +8 -5
  109. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  110. package/kits/skills/ec-trigger/SKILL.md +4 -4
  111. package/kits/skills/thread-ops/SKILL.md +10 -10
  112. package/kits/templates/system-fragments/commands.md +5 -5
  113. package/kits/templates/system-fragments/reply.md +2 -1
  114. package/kits/templates/system-fragments/session.md +1 -1
  115. package/kits/templates/system-fragments/thread.md +1 -1
  116. package/package.json +4 -3
@@ -1,5 +1,7 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { createInterface } from 'node:readline';
4
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
3
5
  // 文件系统非法字符(Windows 最严格):< > : " / \ | ? *
4
6
  // 还有控制字符 0x00-0x1F。我们把这些字符编码为 %XX(hex 大写)。
5
7
  // `%` 本身也要转义为 %25,保证可逆。
@@ -461,6 +463,67 @@ export function readLastJsonlLine(filePath) {
461
463
  fs.closeSync(fd);
462
464
  }
463
465
  }
466
+ /** Async tail reader with the same committed-record rules as the sync readers. */
467
+ export async function readLastJsonlLineAsync(filePath, strict = false) {
468
+ let handle;
469
+ try {
470
+ handle = await fs.promises.open(filePath, 'r');
471
+ }
472
+ catch (error) {
473
+ if (error.code === 'ENOENT')
474
+ return undefined;
475
+ throw error;
476
+ }
477
+ try {
478
+ let cursor = (await handle.stat()).size;
479
+ let carry = Buffer.alloc(0);
480
+ let skipUncommitted = strict;
481
+ 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);
487
+ try {
488
+ return JSON.parse(line);
489
+ }
490
+ catch {
491
+ return undefined;
492
+ }
493
+ };
494
+ while (cursor > 0) {
495
+ const start = Math.max(0, cursor - 64 * 1024);
496
+ const chunk = Buffer.allocUnsafe(cursor - start);
497
+ let offset = 0;
498
+ while (offset < chunk.length) {
499
+ const { bytesRead } = await handle.read(chunk, offset, chunk.length - offset, start + offset);
500
+ if (!bytesRead)
501
+ throw new Error(`short JSONL read at ${filePath}:${start + offset}`);
502
+ offset += bytesRead;
503
+ }
504
+ const buffer = Buffer.concat([chunk, carry]);
505
+ let end = buffer.length;
506
+ let newline = buffer.lastIndexOf(0x0a);
507
+ while (newline >= 0) {
508
+ if (skipUncommitted)
509
+ skipUncommitted = false;
510
+ else {
511
+ const result = parse(buffer.subarray(newline + 1, end), start + newline + 1);
512
+ if (result !== undefined)
513
+ return result;
514
+ }
515
+ end = newline;
516
+ newline = end > 0 ? buffer.lastIndexOf(0x0a, end - 1) : -1;
517
+ }
518
+ carry = Buffer.from(buffer.subarray(0, end));
519
+ cursor = start;
520
+ }
521
+ return skipUncommitted ? undefined : parse(carry, 0);
522
+ }
523
+ finally {
524
+ await handle.close();
525
+ }
526
+ }
464
527
  export function readAllJsonlLines(filePath) {
465
528
  try {
466
529
  const content = fs.readFileSync(filePath, 'utf-8');
@@ -482,6 +545,101 @@ export function readAllJsonlLines(filePath) {
482
545
  throw e;
483
546
  }
484
547
  }
548
+ export async function visitSessionHistory(file, visit, onMalformed) {
549
+ const stream = fs.createReadStream(file, { encoding: 'utf8' });
550
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
551
+ let index = 0;
552
+ try {
553
+ for await (const line of lines) {
554
+ const lineIndex = index++;
555
+ if (index % 256 === 0)
556
+ await yieldToIo();
557
+ if (!line.trim())
558
+ continue;
559
+ let event;
560
+ try {
561
+ event = JSON.parse(line);
562
+ }
563
+ catch {
564
+ onMalformed?.();
565
+ continue;
566
+ }
567
+ visit(event, lineIndex);
568
+ }
569
+ }
570
+ finally {
571
+ lines.close();
572
+ stream.destroy();
573
+ }
574
+ }
575
+ export async function readAllJsonlLinesAsync(filePath) {
576
+ let content;
577
+ try {
578
+ content = await fs.promises.readFile(filePath, 'utf8');
579
+ }
580
+ catch (error) {
581
+ if (error.code === 'ENOENT')
582
+ return [];
583
+ throw error;
584
+ }
585
+ const results = [];
586
+ for (const line of content.split('\n')) {
587
+ if (!line.trim())
588
+ continue;
589
+ try {
590
+ results.push(JSON.parse(line));
591
+ }
592
+ catch { /* skip corrupt line */ }
593
+ }
594
+ return results;
595
+ }
596
+ /** Scan only one Agent/channel, with bounded asynchronous directory reads. */
597
+ export async function scanAgentChatDirsAsync(sessionsRoot, selfAID, channelKey) {
598
+ if (!selfAID || selfAID === '.' || selfAID === '..')
599
+ throw new Error('invalid selfAID');
600
+ const sessionsDir = path.join(sessionsRoot, encodeSegment(selfAID), 'sessions');
601
+ let entries;
602
+ try {
603
+ entries = await fs.promises.readdir(sessionsDir, { withFileTypes: true });
604
+ }
605
+ catch (error) {
606
+ if (error.code === 'ENOENT')
607
+ return [];
608
+ throw error;
609
+ }
610
+ 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) => {
613
+ if (!entry.isDirectory())
614
+ return undefined;
615
+ const parsed = tryParseChannelSessionKey(entry.name);
616
+ if (!parsed)
617
+ return undefined;
618
+ const key = parsed.channelType === 'daemon' ? 'daemon'
619
+ : `${parsed.channelType}#${selfAID}#${parsed.channelName}`;
620
+ if (channelKey && key !== channelKey)
621
+ return undefined;
622
+ const dirPath = path.join(sessionsDir, entry.name);
623
+ let payload;
624
+ try {
625
+ payload = await fs.promises.readdir(dirPath, { withFileTypes: true });
626
+ }
627
+ catch (error) {
628
+ if (error.code === 'ENOENT')
629
+ return undefined;
630
+ throw error;
631
+ }
632
+ 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
+ }
641
+ return results.sort((a, b) => a.dirPath < b.dirPath ? -1 : a.dirPath > b.dirPath ? 1 : 0);
642
+ }
485
643
  /**
486
644
  * Scan the current per-Agent layout:
487
645
  * `agents/<aid>/sessions/<channelSessionKey>/`.
@@ -539,14 +697,17 @@ export function scanChatDirs(sessionsRoot) {
539
697
  }
540
698
  function hasSessionPayload(dirPath) {
541
699
  try {
542
- return fs.readdirSync(dirPath, { withFileTypes: true }).some(entry => (entry.isFile() && (entry.name === 'active.json'
543
- || entry.name === 'messages.jsonl'
544
- || (entry.name.startsWith('meta_') && entry.name.endsWith('.jsonl')))) || (entry.isDirectory() && entry.name === '_threads'));
700
+ return fs.readdirSync(dirPath, { withFileTypes: true }).some(isSessionPayload);
545
701
  }
546
702
  catch {
547
703
  return false;
548
704
  }
549
705
  }
706
+ function isSessionPayload(entry) {
707
+ return (entry.isFile() && (entry.name === 'active.json' || entry.name === 'messages.jsonl'
708
+ || (entry.name.startsWith('meta_') && entry.name.endsWith('.jsonl'))))
709
+ || (entry.isDirectory() && entry.name === '_threads');
710
+ }
550
711
  /**
551
712
  * Scan non-canonical single-level v3 keys. The runtime ignores these entries;
552
713
  * only the explicit migration planner may copy them into their canonical key.
@@ -184,6 +184,7 @@ export class SessionIdleMonitor {
184
184
  generations = new Map();
185
185
  knownSessionIdleTriggerIds = new Set();
186
186
  taskEncryption = new Map();
187
+ persistedState;
187
188
  started = false;
188
189
  active = false;
189
190
  onTaskTerminal = (event) => {
@@ -664,12 +665,19 @@ export class SessionIdleMonitor {
664
665
  ...(state.onceRequestId ? { onceRequestId: state.onceRequestId } : {}),
665
666
  };
666
667
  }
668
+ const snapshot = { version: 2, sessions };
669
+ const serialized = JSON.stringify(snapshot);
670
+ // Startup restores many timers; unchanged state needs no repeated fsync.
671
+ if (serialized === this.persistedState)
672
+ return true;
667
673
  try {
668
674
  fs.mkdirSync(path.dirname(this.options.statePath), { recursive: true });
669
- atomicWriteJson(this.options.statePath, { version: 2, sessions });
675
+ atomicWriteJson(this.options.statePath, snapshot);
676
+ this.persistedState = serialized;
670
677
  return true;
671
678
  }
672
679
  catch (error) {
680
+ this.persistedState = undefined;
673
681
  this.warn(`Failed to persist session idle state at ${this.options.statePath}`, error);
674
682
  return false;
675
683
  }
@@ -5,7 +5,7 @@ import { logger } from '../../utils/logger.js';
5
5
  import { encodePath } from '../../utils/cross-platform.js';
6
6
  import { readRunnerEventSummary } from './runner-event-summary.js';
7
7
  import { isInternalInjectedUserMessage, isToolResultMessage } from './session-transcript.js';
8
- import { chatDirPath, generateSessionId, formatTimestamp, atomicWriteJson, atomicWriteText, appendJsonl, appendJsonlDurable, fsyncJsonlFile, readJsonFile, readLastJsonlLine, readLastJsonlLineStrict, readAllJsonlLines, scanChatDirs, scanMetaFiles, ensureChatDir, readThreadIndex, writeThreadIndex, compactJsonlTail, SESSION_META_COMPACT_POLICY, } from './session-fs-store.js';
8
+ import { chatDirPath, generateSessionId, formatTimestamp, atomicWriteJson, atomicWriteText, appendJsonl, appendJsonlDurable, fsyncJsonlFile, readJsonFile, readLastJsonlLine, readLastJsonlLineStrict, readAllJsonlLines, scanChatDirs, scanMetaFiles, ensureChatDir, readThreadIndex, writeThreadIndex, compactJsonlTail, SESSION_META_COMPACT_POLICY, readLastJsonlLineAsync, } from './session-fs-store.js';
9
9
  import { sessionToFile, fileToSession, formatSessionKey, DEFAULT_THREAD_ID, normalizeTopicLabel, normalizeTopicStatus, } from './session-mapper.js';
10
10
  import { tryParseChannelKey } from '../channel-loader.js';
11
11
  import { isMainSession, isMainSessionThreadId, isTopicSession, isTopicThreadId, mainTopicPeer, safeFormatMainTopicId, sessionLocalTopicId, sessionTopicThreadId, } from '../thread/topic-id.js';
@@ -949,6 +949,31 @@ export class SessionManager {
949
949
  }
950
950
  return results;
951
951
  }
952
+ async findAllSessionsInChatAsync(chatDir) {
953
+ const sessions = [];
954
+ for (const [dir, strict] of [[chatDir, false], [path.join(chatDir, '_threads'), true]]) {
955
+ let names;
956
+ try {
957
+ names = await fs.promises.readdir(dir);
958
+ }
959
+ catch (error) {
960
+ if (error.code === 'ENOENT')
961
+ continue;
962
+ throw error;
963
+ }
964
+ const files = names.filter(name => name.startsWith('meta_') && name.endsWith('.jsonl')).sort();
965
+ for (let offset = 0; offset < files.length; offset += 4) {
966
+ const batch = await Promise.all(files.slice(offset, offset + 4).map(async (name) => {
967
+ const file = await readLastJsonlLineAsync(path.join(dir, name), strict);
968
+ return file ? fileToSession(file) : undefined;
969
+ }));
970
+ for (const session of batch)
971
+ if (session)
972
+ sessions.push(session);
973
+ }
974
+ }
975
+ return sessions;
976
+ }
952
977
  /**
953
978
  * 按 sessionId 定位 meta 文件。逐个 id 全量 scanChatDirs 在几百个 chat 目录下
954
979
  * 单次约 50ms,启动时批量查询(SessionIdleMonitor 恢复 170+ 会话)会同步阻塞数秒,
@@ -2092,7 +2117,7 @@ export class SessionManager {
2092
2117
  return [];
2093
2118
  }
2094
2119
  const archiveFilter = options.archiveFilter ?? 'active';
2095
- const sessions = this.findAllSessionsInChat(chatDir, true)
2120
+ const sessions = (await this.findAllSessionsInChatAsync(chatDir))
2096
2121
  .filter(session => {
2097
2122
  if (archiveFilter === 'all')
2098
2123
  return true;
@@ -2644,6 +2669,15 @@ export class SessionManager {
2644
2669
  return null;
2645
2670
  return adapter.readFirstMessage(projectPath, agentSessionId, agentAid);
2646
2671
  }
2672
+ async readSessionMenuSummary(projectPath, agentSessionId, baseagent, agentAid) {
2673
+ const adapter = this.getFileAdapter(baseagent);
2674
+ if (!adapter)
2675
+ return { turns: 0, firstMessage: null };
2676
+ if (adapter.readMenuSummary)
2677
+ return adapter.readMenuSummary(projectPath, agentSessionId, agentAid);
2678
+ return { turns: adapter.getFileInfo(projectPath, agentSessionId, agentAid).turns,
2679
+ firstMessage: adapter.readFirstMessage(projectPath, agentSessionId, agentAid) };
2680
+ }
2647
2681
  readSessionLastUserMessage(projectPath, agentSessionId, baseagent, agentAid) {
2648
2682
  const adapter = this.getFileAdapter(baseagent);
2649
2683
  if (!adapter)
@@ -84,6 +84,23 @@ export function authorizedOwnerAid(directory, selfAid) {
84
84
  const ownerAid = typeof record.ownerAid === 'string' ? record.ownerAid.trim() : '';
85
85
  return ownerAid || undefined;
86
86
  }
87
+ catch {
88
+ // 没有授权文件时退到本地快照信封:预置团队只带 contacts.json,不拉远端。
89
+ return snapshotOwnerAid(directory, selfAid);
90
+ }
91
+ }
92
+ /** 从 agent 本地快照信封(`contacts.json`)里读出 ownerAid。 */
93
+ function snapshotOwnerAid(directory, selfAid) {
94
+ try {
95
+ const raw = JSON.parse(fs.readFileSync(path.join(directory, 'contacts.json'), 'utf8'));
96
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
97
+ return undefined;
98
+ const record = raw;
99
+ if (record.schemaVersion !== 2 || record.granteeAid !== selfAid)
100
+ return undefined;
101
+ const ownerAid = typeof record.ownerAid === 'string' ? record.ownerAid.trim() : '';
102
+ return ownerAid || undefined;
103
+ }
87
104
  catch {
88
105
  return undefined;
89
106
  }
@@ -225,12 +242,20 @@ export function readOwnerDirectoryMembership(selfAid, aid, appOwned = false) {
225
242
  const cache = new OwnerDirectoryCache({ selfAid, ownerAid, directory, relationVersion });
226
243
  const scope = OWNER_DIRECTORY_SCOPES[0];
227
244
  const accessReason = cache.scopeAccessUnavailableReason(scope);
228
- if (accessReason) {
245
+ // 本地快照可以脱离授权文件单独使用:预置团队(构建期写入 contacts.json、从不拉取远端)
246
+ // 没有 authorization.json,只要快照本身可读,就按快照判定准入。
247
+ // 授权过期(authorization_expired)仍然拦截——那是远端明确撤下的结论,不能靠本地文件续命。
248
+ const localSnapshotOnly = accessReason === 'authorization_missing_or_invalid';
249
+ if (accessReason && !localSnapshotOnly) {
229
250
  logDirectoryAdmissionUnavailable(selfAid, aid, accessReason, ownerAid);
230
251
  return { category: 'unavailable' };
231
252
  }
232
253
  const snapshot = cache.readSnapshot(scope);
233
254
  if (!snapshot) {
255
+ if (localSnapshotOnly) {
256
+ logDirectoryAdmissionUnavailable(selfAid, aid, accessReason, ownerAid);
257
+ return { category: 'unavailable' };
258
+ }
234
259
  logDirectoryAdmissionUnavailable(selfAid, aid, existsAtomic(path.join(directory, `${scope}.json`)) ? 'snapshot_invalid' : 'snapshot_missing', ownerAid);
235
260
  return { category: 'unavailable' };
236
261
  }
@@ -184,20 +184,28 @@ class OwnerDirectoryCoordinator {
184
184
  *
185
185
  * 判据是「实例还活着 + 它有授权」——授权凭证是 per-agent 的,协调者没有
186
186
  * 自己的身份,所以必须借一个。优先选最近活跃的,避免挑到一个正在停止中的。
187
+ * 被远端拒过的实例排在后面:它多半还会被拒,但全员都被拒时仍要有人去试,
188
+ * 否则名录永远不更新。被拒只影响这里,不影响任何一方能不能用名录。
187
189
  */
188
190
  pickExecutor(preferred) {
189
191
  // 优先用发起方自己:它一定想拿到这份数据,结果也直接回给它。
190
- // 只有它自身不可用(授权失效/已退役)时才退到别人,避免出现
192
+ // 只有它自身不可用(授权失效/已退役/刚被远端拒过)时才退到别人,避免出现
191
193
  // 「A 触发、却被 B 的代拉结果覆盖」这种观测不到的错配。
192
- if (preferred && !preferred.isRetired() && preferred.scopeAccessUnavailableReason() === undefined) {
194
+ const usable = (cache) => !cache.isRetired() && cache.scopeAccessUnavailableReason() === undefined;
195
+ if (preferred && usable(preferred) && !preferred.pullBlocked())
193
196
  return preferred;
194
- }
195
197
  for (const cache of this.caches) {
196
198
  if (cache.isRetired()) {
197
199
  this.caches.delete(cache);
198
200
  continue;
199
201
  }
200
- if (cache.scopeAccessUnavailableReason() === undefined)
202
+ if (usable(cache) && !cache.pullBlocked())
203
+ return cache;
204
+ }
205
+ if (preferred && usable(preferred))
206
+ return preferred;
207
+ for (const cache of this.caches) {
208
+ if (usable(cache))
201
209
  return cache;
202
210
  }
203
211
  return undefined;
@@ -469,10 +477,14 @@ export class OwnerDirectoryCache {
469
477
  void this.updateSyncState(state => ({ ...state, blockedScopes: [] })).then(() => this.refreshMarkdown());
470
478
  }
471
479
  /**
472
- * 是否具备拉取条件。
480
+ * 是否具备使用名录的条件。
481
+ *
482
+ * 只看授权本身:有没有授权、有没有过期。**不按 scope 区分**——名录只有一份文件,
483
+ * 能不能读由 storage 的 ACL 决定,不在这里重复判一次。
473
484
  *
474
- * 这就是全部判断:有授权、未过期、没被远端明确拒绝过。**不按 scope 区分**——
475
- * 名录只有一份文件,能不能读由 storage 的 ACL 决定,不在这里重复判一次。
485
+ * **拉取被拒不算不可用**:某次拉取被远端拒绝只影响「谁来拉」(见 `pullBlocked`),
486
+ * 不影响准入、查询和本地读取。数据由 owner 级共享缓存供给,别的 agent 拉到一样能用;
487
+ * 把自己锁死既救不了远端权限,也只会让本 agent 既发不出也收不进。
476
488
  */
477
489
  scopeAccess(scope) {
478
490
  return this.scopeAccessUnavailableReason(scope) ? 'unavailable' : 'authorized';
@@ -483,10 +495,17 @@ export class OwnerDirectoryCache {
483
495
  return 'authorization_missing_or_invalid';
484
496
  if (grant.expiresAt > 0 && grant.expiresAt <= this.now())
485
497
  return 'authorization_expired';
486
- if (this.readSyncState().blockedScopes.length > 0)
487
- return 'scope_blocked';
488
498
  return undefined;
489
499
  }
500
+ /**
501
+ * 本实例最近一次拉取是否被远端拒绝过。
502
+ *
503
+ * 只用于挑选执行者:被拒过一次的实例大概率还会被拒,优先让别人去拉。
504
+ * 它不是准入判据,也不删本地快照——拉不动不等于用不了。
505
+ */
506
+ pullBlocked(scope = OWNER_DIRECTORY_SCOPES[0]) {
507
+ return this.readSyncState().blockedScopes.includes(scope);
508
+ }
490
509
  // ── Pending update ──────────────────────────────────────────────────────────
491
510
  writePendingUpdate(update) {
492
511
  if (!this.canMutate())
@@ -1367,6 +1386,10 @@ export class OwnerDirectoryCache {
1367
1386
  storageUpdatedAtMs: storageUpdatedAtMs ?? numberField(parsed, 'updated_at_ms'),
1368
1387
  });
1369
1388
  logger.info(`[OwnerDirectoryCache] Fetched ${scope}: total=${result[scope].total} digest=${result[scope].contentDigest?.slice(0, 8) ?? 'none'}`);
1389
+ // 这次拉通了,撤掉之前的拉取标记(写盘失败不影响本次结果)。
1390
+ if (this.pullBlocked(scope)) {
1391
+ await this.clearScopeBlock(scope).catch(() => { });
1392
+ }
1370
1393
  }
1371
1394
  catch (error) {
1372
1395
  const normalized = toDirectoryError(error);
@@ -1795,17 +1818,35 @@ export class OwnerDirectoryCache {
1795
1818
  }
1796
1819
  }
1797
1820
  // ── Internal: authorization / sync state / paths ────────────────────────────
1821
+ /**
1822
+ * 记下「这个实例拉不动这份对象」。
1823
+ *
1824
+ * 只写 `blockedScopes`,供 `pickExecutor` 换个执行者。**不删本地快照、
1825
+ * 不改文件状态、不影响准入**:快照还在、内容由共享缓存供给,删了只会让本
1826
+ * agent 在远端权限修好之前既发不出也收不进。真正撤权走 `revokeAuthorization`。
1827
+ */
1798
1828
  async blockScope(scope) {
1799
1829
  if (!this.canMutate())
1800
1830
  return;
1801
- atomicRemove(this.cachePath(scope));
1802
- this.snapshotCache.delete(scope);
1831
+ if (this.readSyncState().blockedScopes.includes(scope))
1832
+ return;
1803
1833
  await this.updateSyncState(state => ({
1804
1834
  ...state,
1805
1835
  blockedScopes: [...new Set([...state.blockedScopes, scope])],
1806
- files: { ...state.files, [scope]: { ...state.files[scope], status: 'blocked', error: 'remote storage denied access' } },
1807
1836
  }));
1808
- this.refreshMarkdown();
1837
+ logger.info(`[OwnerDirectoryCache] Marked ${scope} as pull-blocked for ${this.options.selfAid} (other agents keep pulling)`);
1838
+ }
1839
+ /** 本实例重新拉到了:解除拉取标记,恢复执行者候选资格。 */
1840
+ async clearScopeBlock(scope) {
1841
+ if (!this.canMutate())
1842
+ return;
1843
+ if (!this.readSyncState().blockedScopes.includes(scope))
1844
+ return;
1845
+ await this.updateSyncState(state => ({
1846
+ ...state,
1847
+ blockedScopes: state.blockedScopes.filter(item => item !== scope),
1848
+ }));
1849
+ logger.info(`[OwnerDirectoryCache] Cleared pull-block for ${scope} on ${this.options.selfAid}`);
1809
1850
  }
1810
1851
  async updateFileState(scope, update) {
1811
1852
  await this.updateSyncState(state => ({
@@ -2334,9 +2375,9 @@ function isPermissionDenied(error) {
2334
2375
  /**
2335
2376
  * 把"远端明确拒绝"的各种错误形态归一成 `PERMISSION_DENIED`。
2336
2377
  *
2337
- * `blockScope` 只在远端拒绝时生效:那是权限真的被撤了,本地快照必须作废,
2338
- * 否则准入会继续拿旧名录放行。而本地写盘失败(磁盘只读、文件被占用)不是
2339
- * 权限撤销,走普通错误分支重试即可——所以两种来源必须区分开,不能一概而论。
2378
+ * 归一的用途只是把"这次拉不动"和"网络抖动"分开:前者让 `blockScope` 换个人去拉,
2379
+ * 后者走普通退避重试。两者都**不影响本 agent 能不能用名录**——撤权由
2380
+ * `revokeAuthorization` 单独表达,不靠一次拉取失败推断。
2340
2381
  *
2341
2382
  * 形态来源:
2342
2383
  * - AUN RPC 拒绝:`code` 为 `-32004` / `403` / `4030`,或错误消息里带这些词
@@ -112,7 +112,10 @@ export async function executeDirectoryQueryCommand(command) {
112
112
  }
113
113
  const cache = new OwnerDirectoryCache({ selfAid: command.selfAid, ownerAid, directory });
114
114
  const scope = OWNER_DIRECTORY_SCOPES[0];
115
- if (cache.scopeAccess(scope) !== 'authorized') {
115
+ const accessReason = cache.scopeAccessUnavailableReason(scope);
116
+ // 与准入同一条规则:本地快照可读就能查,不要求 authorization.json;
117
+ // 授权过期仍然拒绝。
118
+ if (accessReason && !(accessReason === 'authorization_missing_or_invalid' && cache.readSnapshot(scope))) {
116
119
  return { ok: false, code: 'NOT_AUTHORIZED', error: 'directory is not authorized for this agent' };
117
120
  }
118
121
  // refresh 要在快照判空之前处理:它存在的意义正是"本地没有或太旧,去拉一次"。
@@ -3,15 +3,17 @@ import path from 'node:path';
3
3
  import { createServer } from 'node:net';
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import { parseEcwebInstanceRecord, matchesEcwebInstanceHealth } from '../../contracts/ecweb-instance.js';
6
- import { getProcessSnapshot, getProcessStartTime, startTimeMatches } from '../../utils/process-introspect.js';
6
+ import { getProcessSnapshot, getProcessStartTime, getProcessStartTimeAsync, startTimeMatches } from '../../utils/process-introspect.js';
7
7
  import * as platform from '../../utils/cross-platform.js';
8
8
  import { resolveGlobalPkg } from '../../utils/npm-ops.js';
9
9
  import { resolveEcwebLaunchCommand } from './launch.js';
10
10
  import { WEB_PACKAGE_NAME } from '../../product.js';
11
- function sameProcess(identity) {
11
+ async function sameProcess(identity) {
12
+ if (!platform.isProcessRunning(identity.pid))
13
+ return false;
14
+ const actual = await getProcessStartTimeAsync(identity.pid);
12
15
  if (!platform.isProcessRunning(identity.pid))
13
16
  return false;
14
- const actual = getProcessStartTime(identity.pid);
15
17
  if (identity.startedAt === null || actual === null) {
16
18
  throw new Error(`Cannot verify ECWeb process identity (PID: ${identity.pid}); refusing to terminate it`);
17
19
  }
@@ -47,21 +49,21 @@ export async function stopEcwebProcess(identity, timeoutMs = FORCED_STOP_MS, onT
47
49
  catch { }
48
50
  }
49
51
  };
50
- if (!sameProcess(identity))
52
+ if (!await sameProcess(identity))
51
53
  return;
52
54
  if (requestGracefulStop) {
53
55
  if (await waitForExit(false, IPC_GRACEFUL_STOP_MS, requestGracefulStop))
54
56
  return;
55
- if (!sameProcess(identity))
57
+ if (!await sameProcess(identity))
56
58
  return;
57
59
  }
58
60
  if (!platform.isWindows && await waitForExit(false, POSIX_GRACEFUL_STOP_MS))
59
61
  return;
60
- if (!sameProcess(identity))
62
+ if (!await sameProcess(identity))
61
63
  return;
62
64
  if (await waitForExit(true, timeoutMs))
63
65
  return;
64
- if (!sameProcess(identity))
66
+ if (!await sameProcess(identity))
65
67
  return;
66
68
  throw new Error(`ECWeb 进程未能退出 (PID: ${identity.pid})`);
67
69
  }