evolcore 0.0.43-test.4 → 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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  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 +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
@@ -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.
@@ -10,6 +10,20 @@ import { createRootCausation } from '../causation/context.js';
10
10
  export const DEFAULT_SESSION_LOOP_SECONDS = 300;
11
11
  export const MIN_SESSION_LOOP_SECONDS = 30;
12
12
  export const MAX_SESSION_LOOP_SECONDS = 86400;
13
+ export const MAX_SESSION_LOOP_PROMPT_LENGTH = 4096;
14
+ export function normalizeSessionLoopOnceConfig(value) {
15
+ if (!value || typeof value !== 'object' || Array.isArray(value))
16
+ return undefined;
17
+ const raw = value;
18
+ if (Object.keys(raw).some(key => key !== 'idleSeconds' && key !== 'prompt'))
19
+ return undefined;
20
+ if (!isValidIdleSeconds(raw.idleSeconds) || typeof raw.prompt !== 'string')
21
+ return undefined;
22
+ const prompt = raw.prompt.trim();
23
+ if (!prompt || prompt.length > MAX_SESSION_LOOP_PROMPT_LENGTH)
24
+ return undefined;
25
+ return { idleSeconds: raw.idleSeconds, prompt };
26
+ }
13
27
  export function normalizeSessionLoopConfig(value) {
14
28
  if (!value || typeof value !== 'object' || Array.isArray(value))
15
29
  return undefined;
@@ -64,6 +78,16 @@ export function readSessionLoopConfigForSession(session) {
64
78
  const target = resolveSessionLoopTarget(session);
65
79
  return target ? readSessionLoopConfig(target) : undefined;
66
80
  }
81
+ export function readSessionLoopOnceConfig(session) {
82
+ const request = session.metadata?.sessionLoopOnce;
83
+ if (!request || typeof request.requestId !== 'string' || !request.requestId.trim()
84
+ || typeof request.peerId !== 'string' || !request.peerId.trim()
85
+ || !Number.isFinite(request.requestedAt))
86
+ return undefined;
87
+ const config = normalizeSessionLoopOnceConfig({ idleSeconds: request.idleSeconds, prompt: request.prompt });
88
+ return config ? { ...config, requestId: request.requestId, requestedAt: request.requestedAt, peerId: request.peerId,
89
+ ...(typeof request.encrypted === 'boolean' ? { encrypted: request.encrypted } : {}) } : undefined;
90
+ }
67
91
  export function updateRelationSessionLoop(session, config) {
68
92
  const target = resolveSessionLoopTarget(session);
69
93
  if (!target || target.level !== 'relation-main')
@@ -117,11 +141,19 @@ export function writeSessionLoopConfig(store, target, config) {
117
141
  }
118
142
  export function sessionLoopPayload(target) {
119
143
  const config = readSessionLoopConfig(target);
144
+ const once = readSessionLoopOnceConfig(target.session);
120
145
  return {
121
146
  target: { level: target.level, sessionId: target.session.id },
122
147
  sessionId: target.session.id,
123
148
  value: config?.enabled === true,
124
149
  ...(config?.enabled ? { idleSeconds: config.idleSeconds } : {}),
150
+ ...(once ? {
151
+ once: {
152
+ pending: true,
153
+ idleSeconds: once.idleSeconds,
154
+ promptPreview: once.prompt.replace(/\s+/g, ' ').slice(0, 120),
155
+ },
156
+ } : {}),
125
157
  };
126
158
  }
127
159
  export function sessionLoopError(code, message) {
@@ -152,6 +184,7 @@ export class SessionIdleMonitor {
152
184
  generations = new Map();
153
185
  knownSessionIdleTriggerIds = new Set();
154
186
  taskEncryption = new Map();
187
+ persistedState;
155
188
  started = false;
156
189
  active = false;
157
190
  onTaskTerminal = (event) => {
@@ -159,7 +192,8 @@ export class SessionIdleMonitor {
159
192
  return;
160
193
  this.refreshSessionIdleTriggerIds();
161
194
  const triggerPath = event.causation?.trigger?.path ?? [];
162
- if (triggerPath.some(node => this.knownSessionIdleTriggerIds.has(node.triggerId))) {
195
+ if (triggerPath.some(node => this.knownSessionIdleTriggerIds.has(node.triggerId))
196
+ && this.sessions.get(event.sessionId)?.emitted !== false) {
163
197
  this.taskEncryption.delete(event.sessionId);
164
198
  return;
165
199
  }
@@ -176,6 +210,8 @@ export class SessionIdleMonitor {
176
210
  onTaskStarted = (event) => {
177
211
  if (event.type !== 'task:started' || !event.sessionId)
178
212
  return;
213
+ this.clearTimers(event.sessionId);
214
+ this.generations.set(event.sessionId, (this.generations.get(event.sessionId) ?? 0) + 1);
179
215
  if (typeof event.encrypt === 'boolean')
180
216
  this.taskEncryption.set(event.sessionId, event.encrypt);
181
217
  else
@@ -199,7 +235,7 @@ export class SessionIdleMonitor {
199
235
  };
200
236
  onSessionLoopChanged = (event) => {
201
237
  if (event.type === 'session:loop-changed')
202
- void this.refreshSession(event.sessionId, event.timestamp);
238
+ void this.refreshSession(event.sessionId, event.timestamp, true);
203
239
  };
204
240
  constructor(options) {
205
241
  this.options = options;
@@ -226,7 +262,20 @@ export class SessionIdleMonitor {
226
262
  this.active = true;
227
263
  this.refreshSessionIdleTriggerIds();
228
264
  for (const sessionId of this.sessions.keys())
265
+ void this.restorePendingSession(sessionId);
266
+ }
267
+ async restorePendingSession(sessionId) {
268
+ try {
269
+ const session = await this.options.getSessionById(sessionId);
270
+ const state = this.sessions.get(sessionId);
271
+ const pending = session && readSessionLoopOnceConfig(session);
272
+ if (state && pending && state.onceRequestId === pending.requestId)
273
+ state.emitted = false;
229
274
  this.scheduleSession(sessionId);
275
+ }
276
+ catch (error) {
277
+ this.warn(`Failed to restore pending idle check for ${sessionId}`, error);
278
+ }
230
279
  }
231
280
  /**
232
281
  * 重新采集 session:idle trigger 身份。
@@ -238,6 +287,11 @@ export class SessionIdleMonitor {
238
287
  refreshTriggerIdentities() {
239
288
  this.refreshSessionIdleTriggerIds();
240
289
  }
290
+ isCurrentLoopOnceEvent(sessionId, requestId, generation) {
291
+ const state = this.sessions.get(sessionId);
292
+ return this.active && state?.emitted === true && state.onceRequestId === requestId
293
+ && (this.generations.get(sessionId) ?? 0) === generation;
294
+ }
241
295
  /** Re-read relation configuration and re-arm every restored/current session. */
242
296
  refresh() {
243
297
  if (!this.active)
@@ -248,10 +302,15 @@ export class SessionIdleMonitor {
248
302
  this.scheduleSession(sessionId);
249
303
  }
250
304
  }
251
- async refreshSession(sessionId, changedAt = this.now()) {
252
- const state = this.sessions.get(sessionId);
253
- if (!state || !this.active)
254
- return;
305
+ async refreshSession(sessionId, changedAt = this.now(), force = false) {
306
+ let state = this.sessions.get(sessionId);
307
+ if (!state) {
308
+ state = { lastEndedAt: changedAt, armedAt: changedAt, emitted: false };
309
+ this.sessions.set(sessionId, state);
310
+ this.persistState();
311
+ }
312
+ this.clearTimers(sessionId);
313
+ this.generations.set(sessionId, (this.generations.get(sessionId) ?? 0) + 1);
255
314
  const generation = this.generations.get(sessionId) ?? 0;
256
315
  try {
257
316
  const session = await this.options.getSessionById(sessionId);
@@ -260,13 +319,14 @@ export class SessionIdleMonitor {
260
319
  const seconds = await this.readIdleSeconds(session);
261
320
  if (this.sessions.get(sessionId) !== state || (this.generations.get(sessionId) ?? 0) !== generation)
262
321
  return;
263
- if (state.idleSeconds === seconds)
264
- return;
265
- this.clearTimers(sessionId);
266
- this.generations.set(sessionId, generation + 1);
322
+ const pending = readSessionLoopOnceConfig(session);
323
+ const changed = force || state.idleSeconds !== seconds || state.onceRequestId !== pending?.requestId;
267
324
  state.idleSeconds = seconds;
268
- state.armedAt = changedAt;
269
- state.emitted = false;
325
+ state.onceRequestId = pending?.requestId;
326
+ if (changed) {
327
+ state.armedAt = changedAt;
328
+ state.emitted = false;
329
+ }
270
330
  this.persistState();
271
331
  if (seconds !== undefined && !await this.options.isSessionBusy(sessionId))
272
332
  this.scheduleSession(sessionId);
@@ -366,6 +426,7 @@ export class SessionIdleMonitor {
366
426
  return;
367
427
  const idleMs = toIdleMs(idleSeconds);
368
428
  state.idleSeconds = idleSeconds;
429
+ state.onceRequestId = readSessionLoopOnceConfig(session)?.requestId;
369
430
  this.persistState();
370
431
  if (idleMs === undefined)
371
432
  return;
@@ -435,12 +496,24 @@ export class SessionIdleMonitor {
435
496
  this.clearSession(sessionId);
436
497
  return;
437
498
  }
499
+ try {
500
+ session = await this.options.getSessionById(sessionId);
501
+ }
502
+ catch (error) {
503
+ this.warn(`Failed to revalidate idle session ${sessionId}`, error);
504
+ return;
505
+ }
506
+ if (!session?.selfAID || !this.isEligibleSession(session) || !this.isCurrentCycle(sessionId, lastEndedAt, generation))
507
+ return;
438
508
  const state = this.sessions.get(sessionId);
439
509
  if (!state || state.emitted)
440
510
  return;
511
+ const once = readSessionLoopOnceConfig(session);
441
512
  state.emitted = true;
442
- if (!this.persistState())
513
+ if (!this.persistState()) {
514
+ state.emitted = false;
443
515
  return;
516
+ }
444
517
  const topicThreadId = sessionTopicThreadId(session);
445
518
  this.options.eventBus.publish({
446
519
  type: 'session:idle',
@@ -451,12 +524,13 @@ export class SessionIdleMonitor {
451
524
  channelId: session.channelId,
452
525
  chatType: session.chatType,
453
526
  ...(topicThreadId ? { threadId: topicThreadId } : {}),
454
- ...(session.metadata?.peerId || session.channelId ? { peerId: session.metadata?.peerId || session.channelId } : {}),
455
- ...(typeof state.encrypted === 'boolean'
456
- ? { encrypted: state.encrypted }
527
+ peerId: once?.peerId ?? session.metadata?.peerId ?? session.channelId,
528
+ ...(typeof (once?.encrypted ?? state.encrypted) === 'boolean'
529
+ ? { encrypted: once?.encrypted ?? state.encrypted }
457
530
  : typeof session.metadata?.replyContext?.metadata?.encrypted === 'boolean'
458
531
  ? { encrypted: session.metadata.replyContext.metadata.encrypted }
459
532
  : {}),
533
+ ...(once ? { loopPrompt: once.prompt, loopOnceRequestId: once.requestId, loopIdleGeneration: generation } : {}),
460
534
  idleMs,
461
535
  lastEndedAt,
462
536
  timestamp: this.now(),
@@ -493,6 +567,9 @@ export class SessionIdleMonitor {
493
567
  }
494
568
  }
495
569
  async readIdleSeconds(session) {
570
+ const once = readSessionLoopOnceConfig(session);
571
+ if (once)
572
+ return once.idleSeconds;
496
573
  try {
497
574
  return await this.options.getSessionIdleSeconds(session);
498
575
  }
@@ -568,6 +645,7 @@ export class SessionIdleMonitor {
568
645
  ...(typeof rawState.encrypted === 'boolean' ? { encrypted: rawState.encrypted } : {}),
569
646
  ...(typeof rawState.armedAt === 'number' && Number.isFinite(rawState.armedAt) ? { armedAt: rawState.armedAt } : {}),
570
647
  ...(typeof rawState.idleSeconds === 'number' ? { idleSeconds: rawState.idleSeconds } : {}),
648
+ ...(typeof rawState.onceRequestId === 'string' ? { onceRequestId: rawState.onceRequestId } : {}),
571
649
  });
572
650
  }
573
651
  }
@@ -584,14 +662,22 @@ export class SessionIdleMonitor {
584
662
  ...(typeof state.encrypted === 'boolean' ? { encrypted: state.encrypted } : {}),
585
663
  ...(state.armedAt !== undefined ? { armedAt: state.armedAt } : {}),
586
664
  ...(state.idleSeconds !== undefined ? { idleSeconds: state.idleSeconds } : {}),
665
+ ...(state.onceRequestId ? { onceRequestId: state.onceRequestId } : {}),
587
666
  };
588
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;
589
673
  try {
590
674
  fs.mkdirSync(path.dirname(this.options.statePath), { recursive: true });
591
- atomicWriteJson(this.options.statePath, { version: 2, sessions });
675
+ atomicWriteJson(this.options.statePath, snapshot);
676
+ this.persistedState = serialized;
592
677
  return true;
593
678
  }
594
679
  catch (error) {
680
+ this.persistedState = undefined;
595
681
  this.warn(`Failed to persist session idle state at ${this.options.statePath}`, error);
596
682
  return false;
597
683
  }
@@ -1,11 +1,11 @@
1
- import { normalizeSessionLoopConfig, resolveSessionLoopTarget, sessionLoopError } from './session-idle-monitor.js';
1
+ import { normalizeSessionLoopConfig, normalizeSessionLoopOnceConfig, readSessionLoopOnceConfig, resolveSessionLoopTarget, sessionLoopError } from './session-idle-monitor.js';
2
2
  import { ensureDir } from '../../utils/atomic-write.js';
3
3
  import { resolvePaths, agentThreadIndexPath } from '../../paths.js';
4
4
  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';
@@ -13,7 +13,7 @@ import { isSystemControlChannel } from '../system-channels.js';
13
13
  import path from 'path';
14
14
  import fs from 'fs';
15
15
  import os from 'os';
16
- import { createHash } from 'node:crypto';
16
+ import { createHash, randomUUID } from 'node:crypto';
17
17
  import { appendSessionCapsuleEvent, capsuleHistory, fallbackCapsuleContent, findSessionCapsule, generateCapsuleContent, generateCapsuleId, renderCapsuleInput, withoutBackendSessionId } from './session-capsule.js';
18
18
  import { associateMessageCapsule } from '../message/message-log.js';
19
19
  function forkHistoryRecord(value) {
@@ -753,17 +753,25 @@ export class SessionManager {
753
753
  * @returns 是否真的写入了 .jsonl(去重命中时返回 false)
754
754
  */
755
755
  persistSession(session, intent, opts) {
756
- if (!opts?.sessionLoopMutation && !opts?.sessionFullAccessMutation) {
756
+ if (!opts?.sessionLoopMutation || !opts?.sessionFullAccessMutation) {
757
757
  const latest = this.readMetaLatest(this.metaPathForSession(session));
758
758
  const metadata = { ...(session.metadata ?? {}) };
759
- if (latest?.metadata?.sessionLoop !== undefined)
760
- metadata.sessionLoop = latest.metadata.sessionLoop;
761
- else
762
- delete metadata.sessionLoop;
763
- if (latest?.metadata?.sessionFullAccess !== undefined)
764
- metadata.sessionFullAccess = latest.metadata.sessionFullAccess;
765
- else
766
- delete metadata.sessionFullAccess;
759
+ if (!opts?.sessionLoopMutation) {
760
+ if (latest?.metadata?.sessionLoop !== undefined)
761
+ metadata.sessionLoop = latest.metadata.sessionLoop;
762
+ else
763
+ delete metadata.sessionLoop;
764
+ if (latest?.metadata?.sessionLoopOnce !== undefined)
765
+ metadata.sessionLoopOnce = latest.metadata.sessionLoopOnce;
766
+ else
767
+ delete metadata.sessionLoopOnce;
768
+ }
769
+ if (!opts?.sessionFullAccessMutation) {
770
+ if (latest?.metadata?.sessionFullAccess !== undefined)
771
+ metadata.sessionFullAccess = latest.metadata.sessionFullAccess;
772
+ else
773
+ delete metadata.sessionFullAccess;
774
+ }
767
775
  session.metadata = metadata;
768
776
  }
769
777
  // Topic session snapshots can be written by synchronous legacy paths
@@ -809,6 +817,10 @@ export class SessionManager {
809
817
  delete mergedMetadata[key];
810
818
  }
811
819
  }
820
+ for (const key of ['sessionLoop', 'sessionLoopOnce', 'sessionFullAccess']) {
821
+ if (!Object.hasOwn(requestedMetadata, key))
822
+ delete mergedMetadata[key];
823
+ }
812
824
  session.metadata = mergedMetadata;
813
825
  }
814
826
  }
@@ -937,6 +949,31 @@ export class SessionManager {
937
949
  }
938
950
  return results;
939
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
+ }
940
977
  /**
941
978
  * 按 sessionId 定位 meta 文件。逐个 id 全量 scanChatDirs 在几百个 chat 目录下
942
979
  * 单次约 50ms,启动时批量查询(SessionIdleMonitor 恢复 170+ 会话)会同步阻塞数秒,
@@ -1503,8 +1540,8 @@ export class SessionManager {
1503
1540
  if (updates.name !== undefined)
1504
1541
  current.name = updates.name;
1505
1542
  if (updates.metadata !== undefined) {
1506
- if (Object.hasOwn(updates.metadata, 'sessionLoop') || Object.hasOwn(updates.metadata, 'sessionFullAccess')) {
1507
- throw topicMetadataOwnershipError(Object.hasOwn(updates.metadata, 'sessionLoop') ? 'sessionLoop' : 'sessionFullAccess');
1543
+ if (Object.hasOwn(updates.metadata, 'sessionLoop') || Object.hasOwn(updates.metadata, 'sessionLoopOnce') || Object.hasOwn(updates.metadata, 'sessionFullAccess')) {
1544
+ throw topicMetadataOwnershipError(Object.hasOwn(updates.metadata, 'sessionLoop') ? 'sessionLoop' : Object.hasOwn(updates.metadata, 'sessionLoopOnce') ? 'sessionLoopOnce' : 'sessionFullAccess');
1508
1545
  }
1509
1546
  if (isTopicSession(current)) {
1510
1547
  for (const key of Object.keys(updates.metadata)) {
@@ -1535,7 +1572,7 @@ export class SessionManager {
1535
1572
  return;
1536
1573
  const { current } = loaded;
1537
1574
  for (const key of Object.keys(patch)) {
1538
- if (key === 'sessionLoop' || key === 'sessionFullAccess')
1575
+ if (key === 'sessionLoop' || key === 'sessionLoopOnce' || key === 'sessionFullAccess')
1539
1576
  throw topicMetadataOwnershipError(key);
1540
1577
  if (isTopicSession(current) && TOPIC_METADATA_PROTECTED_KEYS.has(key)) {
1541
1578
  throw topicMetadataOwnershipError(key);
@@ -1566,6 +1603,45 @@ export class SessionManager {
1566
1603
  return current;
1567
1604
  });
1568
1605
  }
1606
+ updateSessionLoopOnce(sessionId, config, context) {
1607
+ const normalized = normalizeSessionLoopOnceConfig(config);
1608
+ if (!normalized) {
1609
+ throw sessionLoopError('INVALID_ARGUMENT', 'invalid one-shot session loop configuration');
1610
+ }
1611
+ return this.mutateLatestTopicSession(sessionId, current => {
1612
+ const target = resolveSessionLoopTarget(current);
1613
+ if (!target)
1614
+ throw sessionLoopError('INVALID_CONTEXT', '会话不存在或已不可用');
1615
+ const peerId = context?.peerId?.trim() || current.metadata?.peerId || (current.chatType === 'private' ? current.channelId : undefined);
1616
+ if (!peerId)
1617
+ throw sessionLoopError('INVALID_CONTEXT', '单次 loop 缺少原始请求者身份');
1618
+ current.metadata = { ...(current.metadata ?? {}), sessionLoopOnce: {
1619
+ ...normalized,
1620
+ requestId: randomUUID(),
1621
+ requestedAt: Date.now(),
1622
+ peerId,
1623
+ ...(typeof context?.encrypted === 'boolean' ? { encrypted: context.encrypted } : {}),
1624
+ } };
1625
+ const changed = this.persistSession(current, 'sync', { sessionLoopMutation: true });
1626
+ if (changed)
1627
+ this.eventBus.publish({ type: 'session:loop-changed', sessionId, timestamp: Date.now() });
1628
+ return current;
1629
+ });
1630
+ }
1631
+ consumeSessionLoopOnce(sessionId, expectedRequestId) {
1632
+ return this.mutateLatestTopicSession(sessionId, current => {
1633
+ const value = readSessionLoopOnceConfig(current);
1634
+ if (!value || (expectedRequestId !== undefined && value.requestId !== expectedRequestId))
1635
+ return undefined;
1636
+ const metadata = { ...(current.metadata ?? {}) };
1637
+ delete metadata.sessionLoopOnce;
1638
+ current.metadata = metadata;
1639
+ this.persistSession(current, 'sync', { sessionLoopMutation: true });
1640
+ if (expectedRequestId === undefined)
1641
+ this.eventBus.publish({ type: 'session:loop-changed', sessionId, timestamp: Date.now() });
1642
+ return value;
1643
+ });
1644
+ }
1569
1645
  updateSessionFullAccess(sessionId, config) {
1570
1646
  if (typeof config.enabled !== 'boolean' || !config.authorizedBy.trim()) {
1571
1647
  throw Object.assign(new Error('invalid session fullaccess configuration'), { code: 'INVALID_ARGUMENT' });
@@ -1604,6 +1680,7 @@ export class SessionManager {
1604
1680
  getOrCreateThreadSession(channel, channelId, threadId, defaultProjectPath, metadata, name, baseagent, selfAID, channelType, peerType, chatType, label, topicStatus) {
1605
1681
  const topicMetadata = { ...(metadata ?? {}) };
1606
1682
  delete topicMetadata.sessionLoop;
1683
+ delete topicMetadata.sessionLoopOnce;
1607
1684
  delete topicMetadata.sessionFullAccess;
1608
1685
  // 使用精确路径(channelType + selfAID)
1609
1686
  const chatDir = (channelType && selfAID)
@@ -2040,7 +2117,7 @@ export class SessionManager {
2040
2117
  return [];
2041
2118
  }
2042
2119
  const archiveFilter = options.archiveFilter ?? 'active';
2043
- const sessions = this.findAllSessionsInChat(chatDir, true)
2120
+ const sessions = (await this.findAllSessionsInChatAsync(chatDir))
2044
2121
  .filter(session => {
2045
2122
  if (archiveFilter === 'all')
2046
2123
  return true;
@@ -2100,8 +2177,8 @@ export class SessionManager {
2100
2177
  return target;
2101
2178
  }
2102
2179
  updateMetadata(sessionId, metadata) {
2103
- if (Object.hasOwn(metadata, 'sessionLoop'))
2104
- throw topicMetadataOwnershipError('sessionLoop');
2180
+ if (Object.hasOwn(metadata, 'sessionLoop') || Object.hasOwn(metadata, 'sessionLoopOnce'))
2181
+ throw topicMetadataOwnershipError(Object.hasOwn(metadata, 'sessionLoop') ? 'sessionLoop' : 'sessionLoopOnce');
2105
2182
  const loaded = this.loadSessionForUpdate(sessionId);
2106
2183
  if (!loaded)
2107
2184
  return;
@@ -2496,6 +2573,7 @@ export class SessionManager {
2496
2573
  delete metadata.capsuleId;
2497
2574
  delete metadata.replyContext;
2498
2575
  delete metadata.sessionLoop;
2576
+ delete metadata.sessionLoopOnce;
2499
2577
  delete metadata.sessionFullAccess;
2500
2578
  metadata.__sessionRenewedAt = Date.now();
2501
2579
  const session = {
@@ -2591,6 +2669,15 @@ export class SessionManager {
2591
2669
  return null;
2592
2670
  return adapter.readFirstMessage(projectPath, agentSessionId, agentAid);
2593
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
+ }
2594
2681
  readSessionLastUserMessage(projectPath, agentSessionId, baseagent, agentAid) {
2595
2682
  const adapter = this.getFileAdapter(baseagent);
2596
2683
  if (!adapter)