evolcore 0.0.43-test.3 → 0.0.43-test.4

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 (109) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/ecmsg.js +229 -0
  3. package/bin/install-codex-managed-hooks.mjs +130 -8
  4. package/dist/ability/application-service.js +37 -0
  5. package/dist/ability/resources.js +28 -0
  6. package/dist/ability/runtime.js +6 -1
  7. package/dist/agents/claude-runner.js +7 -5
  8. package/dist/agents/codex/app-server-client.js +0 -12
  9. package/dist/agents/codex-runner.js +0 -37
  10. package/dist/agents/ecagent-runner.js +130 -35
  11. package/dist/aun/aid/agentmd.js +31 -12
  12. package/dist/aun/menu/client.js +8 -7
  13. package/dist/aun/menu/index.js +1 -1
  14. package/dist/aun/menu/transport.js +8 -5
  15. package/dist/aun/service-proxy.js +3 -0
  16. package/dist/channels/aun.js +26 -5
  17. package/dist/channels/daemon.js +10 -2
  18. package/dist/cli/agent-command.js +5 -0
  19. package/dist/cli/agent-create.js +28 -6
  20. package/dist/cli/agent.js +9 -3
  21. package/dist/cli/aun-commands.js +2 -2
  22. package/dist/cli/daemon-commands.js +30 -18
  23. package/dist/cli/directory.js +4 -7
  24. package/dist/cli/getmeta-command.js +2 -1
  25. package/dist/cli/init.js +13 -5
  26. package/dist/cli/trigger-command.js +20 -14
  27. package/dist/config/boot-log.js +12 -2
  28. package/dist/config/config-field-policy.js +2 -0
  29. package/dist/config/config-manager.js +9 -4
  30. package/dist/config/peer-role-resolver.js +1 -1
  31. package/dist/config/role-schema.js +3 -3
  32. package/dist/config/schema-migration.js +121 -0
  33. package/dist/core/agent-application-service.js +11 -0
  34. package/dist/core/agent-ipc-registration.js +2 -0
  35. package/dist/core/agent-runtime.js +41 -9
  36. package/dist/core/auth/auth-gateway.js +3 -3
  37. package/dist/core/auth/operation-authorizer.js +2 -1
  38. package/dist/core/baseagent-loader.js +11 -3
  39. package/dist/core/bootstrap-service.js +8 -0
  40. package/dist/core/channel-loader.js +61 -23
  41. package/dist/core/command/agent-control.js +4 -1
  42. package/dist/core/command/chatmode-config.js +46 -0
  43. package/dist/core/command/command-handler.js +5 -14
  44. package/dist/core/command/daemon-diagnostics.js +2 -1
  45. package/dist/core/command/menu-catalog.js +1 -1
  46. package/dist/core/command/menu-handler.js +16 -16
  47. package/dist/core/command/slash-handler.js +4 -26
  48. package/dist/core/daemon-lifecycle.js +35 -17
  49. package/dist/core/event-catalog.js +19 -0
  50. package/dist/core/evolagent-registry.js +3 -0
  51. package/dist/core/ipc-registration.js +6 -0
  52. package/dist/core/message/im-renderer.js +24 -19
  53. package/dist/core/message/message-admission.js +11 -2
  54. package/dist/core/message/response-engine.js +17 -18
  55. package/dist/core/model/model-capabilities.js +37 -0
  56. package/dist/core/model/model-catalog.js +6 -2
  57. package/dist/core/ownership/owner-resolver.js +6 -6
  58. package/dist/core/permission/ec-command-parser.js +47 -12
  59. package/dist/core/plugin-lifecycle.js +6 -2
  60. package/dist/core/relation/pa-team.js +7 -2
  61. package/dist/directory/owner-directory-cache.js +4 -2
  62. package/dist/directory/owner-directory-query-operation.js +5 -7
  63. package/dist/ecweb/runtime/lifecycle.js +29 -5
  64. package/dist/ecweb/runtime/supervisor.js +83 -27
  65. package/dist/index.js +198 -38
  66. package/dist/proxy/service-supervisor.js +377 -141
  67. package/dist/trigger/audit.js +3 -2
  68. package/dist/trigger/authorization.js +2 -3
  69. package/dist/trigger/history.js +4 -3
  70. package/dist/trigger/ipc-service.js +24 -19
  71. package/dist/trigger/manager.js +3 -5
  72. package/dist/trigger/parser.js +4 -21
  73. package/dist/trigger/patch.js +3 -15
  74. package/dist/trigger/scheduler.js +45 -10
  75. package/dist/trigger/validation.js +0 -13
  76. package/dist/utils/error-utils.js +8 -0
  77. package/dist/utils/macos-autostart.js +31 -0
  78. package/dist/utils/model-prices.jsonl +15 -8
  79. package/dist/utils/process-introspect.js +21 -1
  80. package/dist/utils/startup-trace.js +7 -1
  81. package/dist/utils/windows-autostart.js +1 -0
  82. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  83. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  84. package/kits/docs/evolcore/INDEX.md +1 -1
  85. package/kits/docs/evolcore/file-navigation.md +63 -49
  86. package/kits/docs/evolcore/menu-protocol.md +1 -0
  87. package/kits/docs/evolcore/model.md +5 -3
  88. package/kits/docs/evolcore/response.md +2 -0
  89. package/kits/docs/evolcore/thread-chain.md +1 -1
  90. package/kits/docs/evolcore/tool-authorization.md +4 -1
  91. package/kits/docs/evolcore/trigger.md +10 -7
  92. package/kits/eck_manifest.json +0 -21
  93. package/kits/rules/01-overview.md +42 -44
  94. package/kits/rules/02-navigation.md +44 -53
  95. package/kits/rules/03-identity.md +21 -25
  96. package/kits/rules/04-relation.md +23 -33
  97. package/kits/rules/05-venue.md +24 -25
  98. package/kits/schemas/_meta.json +13 -26
  99. package/kits/schemas/agent-config.schema.19.json +10 -6
  100. package/kits/schemas/relation-config.schema.12.json +2 -2
  101. package/kits/schemas/role-config.schema.2.json +5 -5
  102. package/kits/skills/ec-service-proxy/SKILL.md +10 -0
  103. package/kits/skills/ec-trigger/SKILL.md +1 -1
  104. package/kits/templates/system-fragments/commands.md +1 -1
  105. package/kits/templates/system-fragments/identity.md +0 -1
  106. package/package.json +18 -13
  107. package/kits/schemas/agent-config.schema.20.json +0 -925
  108. package/kits/schemas/relation-config.schema.13.json +0 -289
  109. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -15,7 +15,6 @@ import { logger } from '../utils/logger.js';
15
15
  import { resolveProviderService } from '../config/providers.js';
16
16
  import { catalogHash } from '../core/model/catalog-service.js';
17
17
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
18
- import { renderToolTime } from './tool-time-context.js';
19
18
  import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
20
19
  import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
21
20
  import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
@@ -5689,45 +5688,9 @@ export class CodexRunner {
5689
5688
  return;
5690
5689
  if (event.type === 'tool_use') {
5691
5690
  state.openToolCalls.set(event.callId, event.name);
5692
- // 批次起点:本批第一个工具开始执行时记一次,后续并行工具不覆盖。
5693
- if (state.toolBatchStartedAt === undefined)
5694
- state.toolBatchStartedAt = Date.now();
5695
5691
  }
5696
5692
  else if (event.type === 'tool_result') {
5697
5693
  state.openToolCalls.delete(event.callId);
5698
- if (state.openToolCalls.size === 0)
5699
- this.injectToolTime(state);
5700
- }
5701
- }
5702
- /**
5703
- * 工具批次结束后把时间行注入 Codex thread 的模型可见历史。
5704
- *
5705
- * Codex 的时间感知没有 Claude PostToolBatch 那种同步钩子:turn loop 在 app-server 内部,
5706
- * 客户端只能在收到 item/completed、且本批 openToolCalls 清空后主动追加一条 item。
5707
- * 用 Responses API 的 user message + input_text,模型下一次推理即可读到。
5708
- *
5709
- * 失败不影响主流程(注入是增值能力,不是正确性依赖),只记 debug 日志。
5710
- */
5711
- injectToolTime(state) {
5712
- state.toolBatchStartedAt = undefined;
5713
- if (!state.threadId)
5714
- return;
5715
- const items = [{
5716
- type: 'message',
5717
- role: 'user',
5718
- content: [{ type: 'input_text', text: renderToolTime() }],
5719
- }];
5720
- try {
5721
- const client = this.getAppServerClientForThread(state.threadId);
5722
- state.toolTimeInjectedBatches = (state.toolTimeInjectedBatches ?? 0) + 1;
5723
- void client.threadInjectItems(state.threadId, items).catch(error => {
5724
- logger.debug(`[CodexRunner] tool time injection failed: thread=${state.threadId} `
5725
- + `error=${error instanceof Error ? error.message : String(error)}`);
5726
- });
5727
- }
5728
- catch (error) {
5729
- logger.debug(`[CodexRunner] tool time injection skipped: thread=${state.threadId} `
5730
- + `error=${error instanceof Error ? error.message : String(error)}`);
5731
5694
  }
5732
5695
  }
5733
5696
  *reconcileOpenAppServerToolCalls(state, turnId) {
@@ -1,14 +1,16 @@
1
- import { getRunnerCatalog, catalogEfforts, assertCatalogSelectable, } from '../core/model/model-catalog.js';
1
+ import { getRunnerCatalog, catalogEfforts, assertCatalogSelectable, resolveCatalogModel, } from '../core/model/model-catalog.js';
2
2
  // Ecagent/OpenAI API 不认识 Claude Code SDK 的窗口后缀,必须传入基础模型 ID。
3
3
  import { stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
4
4
  import fs from 'fs';
5
5
  import { assertOwnershipAuthorization } from '../core/ownership/owner-resolver.js';
6
6
  import path from 'path';
7
- import { AgentHarness, JsonlSessionRepo, NodeExecutionEnv, } from '../../ecagent/dist/node.js';
7
+ import { AgentHarness, DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, JsonlSessionRepo, NodeExecutionEnv, } from '../../ecagent/dist/node.js';
8
8
  import { Type, createModels, createProvider, } from '../../ecagent/dist/runtime/index.js';
9
9
  import { AssistantMessageEventStream } from '../../ecagent/dist/runtime/utils/event-stream.js';
10
10
  import { DEFAULT_PERMISSION_MODE } from '../types.js';
11
11
  import { agentSessionsDir, resolveRoot } from '../paths.js';
12
+ import { isValidAid } from '../aun/aid/identity.js';
13
+ import { getExistingRelationAttachmentDirs } from '../core/permission/protected-paths.js';
12
14
  import { requestDangerousCommandPermission } from '../core/permission/approval-gateway.js';
13
15
  import { normalizeExecutionPermissionMode, normalizePermissionMode } from '../core/permission/mode.js';
14
16
  import { checkBashDescription, checkDangerousCommand, checkReadonly, evaluateToolPreflight } from '../core/permission/tool-policy.js';
@@ -20,10 +22,11 @@ import { auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
20
22
  import { resolveEcagentConfig, resolveRuntimeBaseagentModelSelection } from './baseagent.js';
21
23
  import { resolveProviderServiceForBaseagent } from '../config/providers.js';
22
24
  import { buildModelRequestHeaders } from './request-identity.js';
23
- import { getGatewayPricing as getSharedGatewayPricing, resolveModelSpec } from '../stats/price-resolver.js';
25
+ import { getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
26
+ import { resolveAutoCompactWindow, resolveModelCapabilities } from '../core/model/model-capabilities.js';
24
27
  import { appendRequestPath } from './request-identity.js';
25
28
  import { getManagedTaskTempDir } from '../cli/task-context.js';
26
- import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext, isOneMillionContextModel, autoCompactWindowForModel, sdkAutoCompactWindowForModel } from './runner-types.js';
29
+ import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext, isOneMillionContextModel } from './runner-types.js';
27
30
  const PROVIDER_ID = 'evolcore-gateway';
28
31
  const DEFAULT_SYSTEM_PROMPT = `You are ecagent, the coding agent built into EvolCore.
29
32
  Work directly in the current project. Inspect relevant files before changing them, keep edits scoped, and verify the result.
@@ -33,6 +36,7 @@ const MAX_TOOL_OUTPUT = 200_000;
33
36
  const MAX_SCAN_FILES = 5_000;
34
37
  const MAX_SEARCH_RESULTS = 500;
35
38
  const DEFAULT_BASH_TIMEOUT_MS = 120_000;
39
+ const INVALID_TOOL_ARGUMENTS_MARKER = '__evolcoreInvalidToolArguments';
36
40
  class AsyncEventQueue {
37
41
  values = [];
38
42
  waiters = [];
@@ -252,7 +256,10 @@ function createOpenAiTransport(config) {
252
256
  onAbort();
253
257
  else
254
258
  options?.signal?.addEventListener('abort', onAbort, { once: true });
255
- const timeout = setTimeout(() => controller.abort(new Error(`Gateway request timed out after ${config.timeoutMs}ms`)), config.timeoutMs);
259
+ const requestType = options?.metadata?.requestType;
260
+ const timeout = requestType === 'compaction' || requestType === 'branch_summary'
261
+ ? undefined
262
+ : setTimeout(() => controller.abort(new Error(`Gateway request timed out after ${config.timeoutMs}ms`)), config.timeoutMs);
256
263
  try {
257
264
  controller.signal.throwIfAborted();
258
265
  let payload = {
@@ -317,7 +324,8 @@ function createOpenAiTransport(config) {
317
324
  }
318
325
  }
319
326
  finally {
320
- clearTimeout(timeout);
327
+ if (timeout)
328
+ clearTimeout(timeout);
321
329
  options?.signal?.removeEventListener('abort', onAbort);
322
330
  }
323
331
  if (retryScheduled) {
@@ -363,7 +371,7 @@ async function consumeOpenAiStream(output, body, model) {
363
371
  args = call.arguments.trim() ? JSON.parse(call.arguments) : {};
364
372
  }
365
373
  catch {
366
- throw new Error(`[network] Invalid tool arguments for ${call.name}`);
374
+ args = { [INVALID_TOOL_ARGUMENTS_MARKER]: true };
367
375
  }
368
376
  const toolCall = { type: 'toolCall', id: call.id, name: call.name, arguments: args };
369
377
  message.content[call.contentIndex] = toolCall;
@@ -456,13 +464,8 @@ async function consumeOpenAiStream(output, body, model) {
456
464
  }
457
465
  throw new Error('[network] Gateway stream ended without a terminal event');
458
466
  }
459
- function createModel(id, baseUrl) {
460
- const modelId = stripContextWindowSuffix(id);
461
- const isClaude = modelId.toLowerCase().startsWith('claude-');
462
- const fallback = isClaude
463
- ? { context_window: isOneMillionContextModel(id) ? 1_000_000 : 200_000, max_output_tokens: 8_192 }
464
- : { context_window: isOneMillionContextModel(id) ? 1_000_000 : 128_000, max_output_tokens: 16_384 };
465
- const spec = resolveModelSpec(resolveRoot(), id, undefined, fallback);
467
+ function createModel(capabilities, baseUrl) {
468
+ const modelId = stripContextWindowSuffix(capabilities.model);
466
469
  return {
467
470
  id: modelId,
468
471
  name: modelId,
@@ -472,8 +475,10 @@ function createModel(id, baseUrl) {
472
475
  reasoning: true,
473
476
  input: ['text', 'image'],
474
477
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
475
- contextWindow: spec.context_window,
476
- maxTokens: spec.max_output_tokens,
478
+ contextWindow: capabilities.contextWindow,
479
+ maxTokens: capabilities.maxOutputTokens,
480
+ capabilities,
481
+ autoCompactWindow: resolveAutoCompactWindow(capabilities.contextWindow, capabilities.maxOutputTokens, DEFAULT_COMPACTION_SETTINGS.reserveTokens),
477
482
  compat: {
478
483
  maxTokensField: 'max_tokens',
479
484
  supportsUsageInStreaming: true,
@@ -494,7 +499,12 @@ function isWithin(root, candidate) {
494
499
  function isWithinAny(candidate, roots) {
495
500
  return roots.some(root => isWithin(path.resolve(root), candidate));
496
501
  }
497
- export function resolveEcagentToolPath(projectPath, candidate, forWrite = false, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants) {
502
+ function getEcagentAttachmentReadRoots(selfAid) {
503
+ return selfAid && isValidAid(selfAid)
504
+ ? getExistingRelationAttachmentDirs(resolveRoot(), { selfAid })
505
+ : [];
506
+ }
507
+ export function resolveEcagentToolPath(projectPath, candidate, forWrite = false, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants, selfAid) {
498
508
  const root = fs.realpathSync(projectPath);
499
509
  const resolved = path.resolve(root, candidate || '.');
500
510
  const allowedBootstrapFile = bootstrapAgentMdPath
@@ -511,7 +521,10 @@ export function resolveEcagentToolPath(projectPath, candidate, forWrite = false,
511
521
  .some(file => path.resolve(file) === resolved);
512
522
  const sessionReads = !forWrite && isWithinAny(resolved, sessionGrants?.readRoots ?? []);
513
523
  const isSessionTarget = sessionReads || sessionWrites;
514
- if (!fullaccess && !isWithin(root, resolved) && !isManagedIdentityFile && !isSessionTarget) {
524
+ const attachmentReadRoot = !forWrite && !sessionGrants
525
+ ? getEcagentAttachmentReadRoots(selfAid).find(directory => isWithin(directory, resolved))
526
+ : undefined;
527
+ if (!fullaccess && !isWithin(root, resolved) && !isManagedIdentityFile && !isSessionTarget && !attachmentReadRoot) {
515
528
  throw new Error(`Path is outside the project: ${candidate}`);
516
529
  }
517
530
  if (isManagedIdentityFile) {
@@ -542,6 +555,16 @@ export function resolveEcagentToolPath(projectPath, candidate, forWrite = false,
542
555
  }
543
556
  // 可写文件尚未创建时,以父目录的真实路径为准;已存在时以文件自身的真实路径为准。
544
557
  const canonicalSelf = fs.existsSync(resolved) ? fs.realpathSync(resolved) : canonical;
558
+ if (attachmentReadRoot) {
559
+ const canonicalAttachmentRoot = fs.realpathSync(attachmentReadRoot);
560
+ if (!isWithin(attachmentReadRoot, canonicalAttachmentRoot)
561
+ || !isWithin(canonicalAttachmentRoot, attachmentReadRoot)
562
+ || !isWithin(canonicalAttachmentRoot, canonical)
563
+ || !isWithin(canonicalAttachmentRoot, canonicalSelf)) {
564
+ throw new Error(`Path resolves outside its attachment root: ${candidate}`);
565
+ }
566
+ return resolved;
567
+ }
545
568
  if (isSessionTarget) {
546
569
  const grantedRoots = [
547
570
  ...(sessionReads ? sessionGrants?.readRoots ?? [] : []),
@@ -613,16 +636,16 @@ async function walkFiles(root, signal) {
613
636
  function textResult(text, details = {}) {
614
637
  return { content: [{ type: 'text', text: truncate(text) }], details };
615
638
  }
616
- function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants) {
639
+ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants, selfAid) {
617
640
  const read = {
618
- name: 'Read', label: 'Read', description: 'Read a UTF-8 text file from the project.',
641
+ name: 'Read', label: 'Read', description: 'Read a UTF-8 text file from the project or this Agent\'s incoming attachments.',
619
642
  parameters: Type.Object({
620
643
  file_path: Type.String(),
621
644
  offset: Type.Optional(Type.Number({ minimum: 1 })),
622
645
  limit: Type.Optional(Type.Number({ minimum: 1 })),
623
646
  }),
624
647
  async execute(_id, params, signal) {
625
- const file = resolveEcagentToolPath(projectPath, params.file_path, false, bootstrapAgentMdPath, fullaccess, personalSoulDir, sessionGrants);
648
+ const file = resolveEcagentToolPath(projectPath, params.file_path, false, bootstrapAgentMdPath, fullaccess, personalSoulDir, sessionGrants, selfAid);
626
649
  const stat = await fs.promises.stat(file);
627
650
  if (stat.size > MAX_READ_BYTES)
628
651
  throw new Error(`File exceeds ${MAX_READ_BYTES} byte read limit`);
@@ -636,10 +659,10 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
636
659
  },
637
660
  };
638
661
  const glob = {
639
- name: 'Glob', label: 'Glob', description: 'Find project files matching a glob pattern.',
662
+ name: 'Glob', label: 'Glob', description: 'Find files matching a glob pattern in the project or this Agent\'s incoming attachments.',
640
663
  parameters: Type.Object({ pattern: Type.String(), path: Type.Optional(Type.String()) }),
641
664
  async execute(_id, params, signal) {
642
- const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants);
665
+ const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants, selfAid);
643
666
  const matcher = globRegex(params.pattern.replaceAll('\\', '/'));
644
667
  const files = (await walkFiles(root, signal))
645
668
  .map(file => path.relative(root, file).replaceAll(path.sep, '/'))
@@ -649,13 +672,13 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
649
672
  },
650
673
  };
651
674
  const grep = {
652
- name: 'Grep', label: 'Grep', description: 'Search text files in the project.',
675
+ name: 'Grep', label: 'Grep', description: 'Search text files in the project or this Agent\'s incoming attachments.',
653
676
  parameters: Type.Object({
654
677
  pattern: Type.String(), path: Type.Optional(Type.String()), glob: Type.Optional(Type.String()),
655
678
  case_insensitive: Type.Optional(Type.Boolean()), literal: Type.Optional(Type.Boolean()),
656
679
  }),
657
680
  async execute(_id, params, signal) {
658
- const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants);
681
+ const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants, selfAid);
659
682
  const files = (await fs.promises.stat(root)).isFile() ? [root] : await walkFiles(root, signal);
660
683
  const fileMatcher = params.glob ? globRegex(params.glob.replaceAll('\\', '/')) : undefined;
661
684
  const flags = params.case_insensitive ? 'i' : '';
@@ -738,7 +761,16 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
738
761
  return textResult(combined || `Command exited with ${result.value.exitCode}`, { exitCode: result.value.exitCode });
739
762
  },
740
763
  };
741
- return [read, glob, grep, write, edit, bash];
764
+ const tools = [read, glob, grep, write, edit, bash];
765
+ return tools.map((tool) => ({
766
+ ...tool,
767
+ prepareArguments(args) {
768
+ if (args && typeof args === 'object' && args[INVALID_TOOL_ARGUMENTS_MARKER] === true) {
769
+ throw new Error(`The model returned malformed JSON arguments for ${tool.name}; no command was executed. Return valid JSON arguments and try again.`);
770
+ }
771
+ return tool.prepareArguments ? tool.prepareArguments(args) : args;
772
+ },
773
+ }));
742
774
  }
743
775
  function extractToolResult(result) {
744
776
  const content = Array.isArray(result?.content) ? result.content : [];
@@ -746,6 +778,8 @@ function extractToolResult(result) {
746
778
  }
747
779
  function errorType(message) {
748
780
  const normalized = message.toLowerCase();
781
+ if (normalized.includes('summarization failed') || normalized.includes('turn prefix summarization failed'))
782
+ return ErrorType.COMPACTION_FAILED;
749
783
  if (normalized.includes('invalid jsonl session file') || normalized.includes('session file'))
750
784
  return ErrorType.SESSION_UNAVAILABLE;
751
785
  if (normalized.includes('[auth]') || normalized.includes('401') || normalized.includes('403'))
@@ -829,6 +863,7 @@ export class EcagentRunner {
829
863
  throw new Error(`Provider ${providerId} has no API key`);
830
864
  return {
831
865
  ...this.config,
866
+ providerId,
832
867
  apiKey: provider.apiKey,
833
868
  baseUrl: provider.baseUrl,
834
869
  headers: buildModelRequestHeaders({
@@ -852,7 +887,24 @@ export class EcagentRunner {
852
887
  ];
853
888
  }
854
889
  getModelCatalog() {
855
- return getRunnerCatalog('ecagent', this.agentAid, this.config);
890
+ return getRunnerCatalog('ecagent', this.agentAid, this.currentProviderConfig());
891
+ }
892
+ async resolveRunModel(modelId, connection) {
893
+ const catalog = await getRunnerCatalog('ecagent', undefined, connection);
894
+ assertCatalogSelectable(catalog);
895
+ const canonicalModel = resolveCatalogModel(catalog, modelId);
896
+ const isClaude = stripContextWindowSuffix(canonicalModel).toLowerCase().startsWith('claude-');
897
+ const capabilities = resolveModelCapabilities(resolveRoot(), modelId, {
898
+ catalog,
899
+ fallbackContextWindow: isOneMillionContextModel(canonicalModel) ? 1_000_000 : isClaude ? 200_000 : 128_000,
900
+ fallbackMaxOutputTokens: isClaude ? 8192 : 16384,
901
+ });
902
+ const model = createModel(capabilities, connection.baseUrl);
903
+ logger.info('[EcagentRunner] Resolved model capabilities', {
904
+ ...capabilities, autoCompactWindow: model.autoCompactWindow,
905
+ providerId: connection.providerId, catalogSource: catalog?.source, catalogFreshness: catalog?.freshness,
906
+ });
907
+ return model;
856
908
  }
857
909
  async listModels() {
858
910
  const catalog = await this.getModelCatalog();
@@ -957,6 +1009,8 @@ export class EcagentRunner {
957
1009
  startedAt: Date.now(), text: '', textBlocks: new Map(), numTurns: 0, usage: {}, modelCalls: [],
958
1010
  };
959
1011
  let completeSent = false;
1012
+ let compactHeartbeatTimer;
1013
+ let compactStartedAt;
960
1014
  try {
961
1015
  const connection = this.currentProviderConfig(request.modelOverride?.provider);
962
1016
  await fs.promises.mkdir(request.projectPath, { recursive: true });
@@ -982,7 +1036,15 @@ export class EcagentRunner {
982
1036
  if (fullaccess && !hasTrustedFullAccessContext(this.permissionContexts.get(request.sessionId))) {
983
1037
  throw new Error('Ecagent fullaccess requires a trusted per-call execution authorization');
984
1038
  }
985
- const model = createModel(modelId, connection.baseUrl);
1039
+ const model = await this.resolveRunModel(modelId, connection);
1040
+ if (lifecycle.cancelled)
1041
+ throw new Error('ecagent run interrupted');
1042
+ if (model.capabilities.contextWindowSource === 'safe-fallback') {
1043
+ queue.push({
1044
+ type: 'notice', severity: 'warn', subtype: 'model_context_fallback',
1045
+ message: '未取得模型上下文参数,暂按保守窗口 ' + model.contextWindow + ' tokens 运行;这不代表模型官方上限。',
1046
+ });
1047
+ }
986
1048
  const nodeEnv = new NodeExecutionEnv({ cwd: request.projectPath, shellEnv: { ...process.env, ...request.runtimeEnv, EVOLCORE_SESSION_ID: request.sessionId, EVOLCORE_HOME: resolveRoot() } });
987
1049
  const models = createModels();
988
1050
  const transport = createOpenAiTransport(connection);
@@ -1004,8 +1066,8 @@ export class EcagentRunner {
1004
1066
  models,
1005
1067
  model,
1006
1068
  thinkingLevel: normalizeThinkingLevel(effort),
1007
- autoCompactWindow: sdkAutoCompactWindowForModel(modelId, model.contextWindow),
1008
- tools: createTools(nodeEnv, request.projectPath, request.runtimeEnv, request.modelOverride?.bootstrapAgentMdPath, fullaccess, request.modelOverride?.personalSoulDir, this.permissionContexts.get(request.sessionId)?.systemSessionGrants),
1069
+ autoCompactWindow: model.autoCompactWindow,
1070
+ tools: createTools(nodeEnv, request.projectPath, request.runtimeEnv, request.modelOverride?.bootstrapAgentMdPath, fullaccess, request.modelOverride?.personalSoulDir, this.permissionContexts.get(request.sessionId)?.systemSessionGrants, this.permissionContexts.get(request.sessionId)?.systemSessionCheck ? undefined : this.agentAid),
1009
1071
  systemPrompt: [DEFAULT_SYSTEM_PROMPT, request.systemPromptAppend].filter(Boolean).join('\n\n'),
1010
1072
  streamOptions: {
1011
1073
  timeoutMs: connection.timeoutMs,
@@ -1016,6 +1078,10 @@ export class EcagentRunner {
1016
1078
  runtime.harness = harness;
1017
1079
  harness.on('session_before_compact', () => {
1018
1080
  this.onCompactStart?.(request.sessionId);
1081
+ compactStartedAt = Date.now();
1082
+ compactHeartbeatTimer ??= setInterval(() => {
1083
+ queue.push({ type: 'heartbeat', source: 'compaction', turn: stats.numTurns + 1 });
1084
+ }, 30_000);
1019
1085
  return undefined;
1020
1086
  });
1021
1087
  if (this.pendingInterrupts.get(request.sessionId) === queue) {
@@ -1057,7 +1123,27 @@ export class EcagentRunner {
1057
1123
  return messages ? { messages } : undefined;
1058
1124
  });
1059
1125
  let inputAccepted = false;
1060
- const unsubscribe = harness.subscribe(event => {
1126
+ const unsubscribe = harness.subscribe(async (event) => {
1127
+ if (event.type === 'session_compact') {
1128
+ if (compactHeartbeatTimer)
1129
+ clearInterval(compactHeartbeatTimer);
1130
+ compactHeartbeatTimer = undefined;
1131
+ const durationMs = compactStartedAt === undefined ? undefined : Date.now() - compactStartedAt;
1132
+ compactStartedAt = undefined;
1133
+ try {
1134
+ const context = await runtime.session.buildContext();
1135
+ queue.push({
1136
+ type: 'compact',
1137
+ preTokens: event.compactionEntry.tokensBefore,
1138
+ postTokens: estimateContextTokens(context.messages).tokens,
1139
+ durationMs,
1140
+ });
1141
+ }
1142
+ catch (error) {
1143
+ logger.warn(`[EcagentRunner] Could not measure compacted context: ${error instanceof Error ? error.message : String(error)}`);
1144
+ queue.push({ type: 'compact', preTokens: event.compactionEntry.tokensBefore, durationMs });
1145
+ }
1146
+ }
1061
1147
  if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
1062
1148
  logger.info('[EcagentRunner] Tool lifecycle', {
1063
1149
  sessionId: request.sessionId, taskId: request.modelOverride?.turn?.taskId,
@@ -1149,6 +1235,8 @@ export class EcagentRunner {
1149
1235
  completeSent = true;
1150
1236
  }
1151
1237
  finally {
1238
+ if (compactHeartbeatTimer)
1239
+ clearInterval(compactHeartbeatTimer);
1152
1240
  if (!completeSent)
1153
1241
  queue.push({ type: 'complete', isError: true, terminalReason: 'error', durationMs: Date.now() - stats.startedAt });
1154
1242
  if (this.activeStreams.get(request.sessionId) === queue) {
@@ -1339,7 +1427,8 @@ export class EcagentRunner {
1339
1427
  return {
1340
1428
  totalTokens, maxTokens: model.contextWindow,
1341
1429
  percentage: model.contextWindow > 0 ? totalTokens / model.contextWindow * 100 : 0,
1342
- autoCompactTokens: autoCompactWindowForModel(model.id),
1430
+ autoCompactTokens: model.autoCompactWindow,
1431
+ contextWindowSource: model.capabilities.contextWindowSource,
1343
1432
  model: model.id, effort,
1344
1433
  };
1345
1434
  }
@@ -1454,8 +1543,14 @@ export class EcagentRunner {
1454
1543
  return {};
1455
1544
  const checkedInput = preflight.input;
1456
1545
  if (mode === 'readonly') {
1546
+ const attachmentReadRoots = ['Read', 'Glob', 'Grep'].includes(toolName)
1547
+ ? getEcagentAttachmentReadRoots(permissionContext?.selfAid)
1548
+ : [];
1457
1549
  const decision = checkReadonly(toolName, checkedInput, projectPath, {
1458
- sessionId, managedTempDir: permissionContext?.managedTempDir, grantedReadRoots: permissionContext?.grantedReadRoots, channel: permissionContext?.channel, peerId: permissionContext?.userId, role: permissionContext?.role,
1550
+ sessionId, managedTempDir: permissionContext?.managedTempDir,
1551
+ grantedReadRoots: [...(permissionContext?.grantedReadRoots ?? []), ...attachmentReadRoots],
1552
+ channel: permissionContext?.channel, peerId: permissionContext?.userId, role: permissionContext?.role,
1553
+ selfAid: permissionContext?.selfAid,
1459
1554
  allowReadonlySourceDiagnostics: permissionContext?.allowReadonlySourceDiagnostics === true,
1460
1555
  });
1461
1556
  if (decision.behavior === 'deny') {
@@ -1582,8 +1677,8 @@ export class EcagentRunner {
1582
1677
  const compactEffort = modelOverride?.effortMode === 'model_default'
1583
1678
  ? undefined
1584
1679
  : modelOverride?.effort ?? this.effort;
1585
- const connection = this.currentProviderConfig();
1586
- const model = createModel(compactModel, connection.baseUrl);
1680
+ const connection = this.currentProviderConfig(modelOverride?.provider);
1681
+ const model = await this.resolveRunModel(compactModel, connection);
1587
1682
  const env = new NodeExecutionEnv({ cwd: runtime.projectPath });
1588
1683
  const models = createModels();
1589
1684
  const transport = createOpenAiTransport(connection);
@@ -147,9 +147,6 @@ async function withAgentMdWriteLock(key, operation) {
147
147
  agentMdWriteLocks.delete(key);
148
148
  }
149
149
  }
150
- // A process can host agents that deliberately use different AUN keystore
151
- // roots. Keep their display-name state separate so one root cannot shadow the
152
- // other with a same-named AID.
153
150
  const displayNameCache = new Map();
154
151
  const displayNamePending = new Map();
155
152
  const displayNameRevision = new Map();
@@ -180,18 +177,34 @@ function displayNameKey(aid, aunPath) {
180
177
  const root = path.resolve(aunPath ?? resolveRoot());
181
178
  return `${root}\u0000${aid.toLowerCase()}`;
182
179
  }
180
+ /** agent.md 的廉价指纹;文件不存在时返回 null。 */
181
+ function agentMdStamp(aid, aunPath) {
182
+ try {
183
+ const st = fs.statSync(agentMdPath(aid, aunPath));
184
+ return `${st.mtimeMs}:${st.size}`;
185
+ }
186
+ catch {
187
+ return null;
188
+ }
189
+ }
183
190
  function readLocalAgentDisplayName(aid, aunPath) {
191
+ // 先取指纹再读内容:并发写入时只会让下一次多读一遍,不会留下过期条目。
192
+ const stamp = agentMdStamp(aid, aunPath);
184
193
  try {
185
- return parseAgentDisplayName(fs.readFileSync(agentMdPath(aid, aunPath), 'utf-8'));
194
+ return { name: parseAgentDisplayName(fs.readFileSync(agentMdPath(aid, aunPath), 'utf-8')), stamp };
186
195
  }
187
196
  catch {
188
- return undefined;
197
+ return { name: undefined, stamp: null };
189
198
  }
190
199
  }
191
200
  /**
192
201
  * Resolve an agent.md display name without blocking on the network.
193
202
  * Local content is returned immediately; a missing value starts one shared
194
203
  * background refresh and remains undefined until a later lookup.
204
+ *
205
+ * The cache is validated against agent.md's mtime+size on every lookup, so a
206
+ * rename written by any path (CLI, App, peer sync) is visible on the next read
207
+ * instead of waiting for a process-level invalidate hook or a daemon restart.
195
208
  */
196
209
  export function resolveAgentDisplayName(aid, opts) {
197
210
  const normalizedAid = normalizeAid(aid);
@@ -200,13 +213,19 @@ export function resolveAgentDisplayName(aid, opts) {
200
213
  const aunPath = resolveAgentMdAunPath(opts);
201
214
  const key = displayNameKey(normalizedAid, aunPath);
202
215
  const cached = displayNameCache.get(key);
203
- if (cached)
204
- return cached;
205
- const localName = readLocalAgentDisplayName(normalizedAid, aunPath);
206
- if (localName) {
207
- displayNameCache.set(key, localName);
208
- return localName;
216
+ if (cached) {
217
+ // 指纹未知(当初 stat 不到)或此刻 stat 不到文件时,沿用缓存,避免反复回源。
218
+ const current = cached.stamp === null ? null : agentMdStamp(normalizedAid, aunPath);
219
+ if (current === null || current === cached.stamp)
220
+ return cached.name;
221
+ displayNameCache.delete(key);
222
+ }
223
+ const local = readLocalAgentDisplayName(normalizedAid, aunPath);
224
+ if (local.name) {
225
+ displayNameCache.set(key, { name: local.name, stamp: local.stamp });
226
+ return local.name;
209
227
  }
228
+ displayNameCache.delete(key);
210
229
  void refreshAgentDisplayName(normalizedAid, opts);
211
230
  return undefined;
212
231
  }
@@ -228,7 +247,7 @@ export function refreshAgentDisplayName(aid, opts) {
228
247
  if ((displayNameRevision.get(key) ?? 0) !== revision)
229
248
  return undefined;
230
249
  if (name)
231
- displayNameCache.set(key, name);
250
+ displayNameCache.set(key, { name, stamp: agentMdStamp(normalizedAid, aunPath) });
232
251
  return name;
233
252
  })
234
253
  .catch(() => undefined)
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import crypto from 'node:crypto';
4
4
  import { createShortConnection } from '../rpc/client.js';
5
- import { MENU_MESSAGE_TTL_SECONDS } from './transport.js';
5
+ import { MENU_MESSAGE_CLASS, MENU_MESSAGE_TTL_SECONDS } from './transport.js';
6
6
  import { SLOT } from '../aid/store.js';
7
7
  import { isValidAid } from '../aid/validation.js';
8
8
  import { resolveRoot } from '../../paths.js';
@@ -125,7 +125,7 @@ export class ManagedMenuClient {
125
125
  });
126
126
  const sent = this.send({
127
127
  to: options.targetAid, payload: request, encrypt: true,
128
- ttl: MENU_MESSAGE_TTL_SECONDS, protected_headers: headers,
128
+ message_class: MENU_MESSAGE_CLASS, ttl: MENU_MESSAGE_TTL_SECONDS, protected_headers: headers,
129
129
  }, options.beforeSend)
130
130
  .then(result => {
131
131
  if (!(result?.message_id ?? result?.message?.message_id))
@@ -276,7 +276,7 @@ async function pollResponse(conn, targetAid, requestId, timeoutMs, initialAfterS
276
276
  const deadline = Date.now() + timeoutMs;
277
277
  let afterSeq = initialAfterSeq;
278
278
  while (Date.now() < deadline) {
279
- const result = await callClient(conn, 'message.pull', { after_seq: afterSeq, limit: PULL_LIMIT });
279
+ const result = await callClient(conn, 'message.pull', { message_class: MENU_MESSAGE_CLASS, after_seq: afterSeq, limit: PULL_LIMIT });
280
280
  const messages = Array.isArray(result?.messages) ? result.messages : [];
281
281
  let maxSeq = afterSeq;
282
282
  for (const message of messages) {
@@ -290,7 +290,7 @@ async function pollResponse(conn, targetAid, requestId, timeoutMs, initialAfterS
290
290
  if (response && messageFrom === targetAid && response.id === requestId) {
291
291
  if (Number.isSafeInteger(maxSeq) && maxSeq > afterSeq) {
292
292
  try {
293
- await callClient(conn, 'message.ack', { seq: maxSeq });
293
+ await callClient(conn, 'message.ack', { message_class: MENU_MESSAGE_CLASS, seq: maxSeq });
294
294
  }
295
295
  catch (error) {
296
296
  throw new MenuClientError('ACK_FAILED', error?.message ?? String(error));
@@ -302,7 +302,7 @@ async function pollResponse(conn, targetAid, requestId, timeoutMs, initialAfterS
302
302
  if (Number.isSafeInteger(maxSeq) && maxSeq > afterSeq) {
303
303
  afterSeq = maxSeq;
304
304
  try {
305
- await callClient(conn, 'message.ack', { seq: afterSeq });
305
+ await callClient(conn, 'message.ack', { message_class: MENU_MESSAGE_CLASS, seq: afterSeq });
306
306
  }
307
307
  catch (error) {
308
308
  throw new MenuClientError('ACK_FAILED', error?.message ?? String(error));
@@ -316,7 +316,7 @@ async function pollResponse(conn, targetAid, requestId, timeoutMs, initialAfterS
316
316
  async function drainBaseline(conn) {
317
317
  let afterSeq = 0;
318
318
  for (let page = 0; page < 200; page += 1) {
319
- const result = await callClient(conn, 'message.pull', { after_seq: afterSeq, limit: PULL_LIMIT });
319
+ const result = await callClient(conn, 'message.pull', { message_class: MENU_MESSAGE_CLASS, after_seq: afterSeq, limit: PULL_LIMIT });
320
320
  const messages = Array.isArray(result?.messages) ? result.messages : [];
321
321
  let maxSeq = Math.max(afterSeq, Number(result?.server_ack_seq) || 0);
322
322
  for (const message of messages) {
@@ -326,7 +326,7 @@ async function drainBaseline(conn) {
326
326
  }
327
327
  if (maxSeq > afterSeq) {
328
328
  try {
329
- await callClient(conn, 'message.ack', { seq: maxSeq });
329
+ await callClient(conn, 'message.ack', { message_class: MENU_MESSAGE_CLASS, seq: maxSeq });
330
330
  }
331
331
  catch (error) {
332
332
  throw new MenuClientError('ACK_FAILED', error?.message ?? String(error));
@@ -363,6 +363,7 @@ async function sendOnce(options, request, timeoutMs) {
363
363
  to: options.targetAid,
364
364
  payload: request,
365
365
  encrypt,
366
+ message_class: MENU_MESSAGE_CLASS,
366
367
  ttl: MENU_MESSAGE_TTL_SECONDS,
367
368
  ...(encrypt ? { protected_headers: headers } : {}),
368
369
  });
@@ -1,2 +1,2 @@
1
1
  export { ManagedMenuClient, MenuClientError, executeMenuClientRequest } from './client.js';
2
- export { MENU_MESSAGE_TTL_SECONDS, MENU_VOLATILE_SDK_VERSION, menuSenderDeviceId, menuTransportParams, supportsMenuVolatileTransport, } from './transport.js';
2
+ export { MENU_MESSAGE_TTL_SECONDS, MENU_MESSAGE_CLASS, MENU_VOLATILE_SDK_VERSION, menuSenderDeviceId, menuTransportParams, supportsMenuVolatileTransport, } from './transport.js';
@@ -1,5 +1,7 @@
1
1
  /** Message Service TTL in seconds; unrelated to Menu execution/client timeouts. */
2
2
  export const MENU_MESSAGE_TTL_SECONDS = 60;
3
+ /** Menu is an application control protocol, so it uses the AUN control stream. */
4
+ export const MENU_MESSAGE_CLASS = 'control';
3
5
  export const MENU_VOLATILE_SDK_VERSION = '0.5.17';
4
6
  function parseSdkVersion(value) {
5
7
  if (typeof value !== 'string' || !/^\d+\.\d+\.\d+$/.test(value.trim()))
@@ -30,22 +32,23 @@ export function menuTransportParams(method, params) {
30
32
  if (method !== 'message.send' || typeof params.payload?.type !== 'string'
31
33
  || !params.payload.type.startsWith('menu.'))
32
34
  return params;
33
- if (params.payload.type !== 'menu.response' && params.payload.type !== 'menu.event')
34
- return { ...params, ttl: MENU_MESSAGE_TTL_SECONDS };
35
+ if (params.payload.type !== 'menu.response' && params.payload.type !== 'menu.event') {
36
+ return { ...params, message_class: MENU_MESSAGE_CLASS, ttl: MENU_MESSAGE_TTL_SECONDS };
37
+ }
35
38
  const { to_device_id: target, menu_client_sdk_version: sdkVersion, menu_client_volatile_v1: capability, ...rest } = params;
36
39
  delete rest.device_id;
37
40
  if (!supportsMenuVolatileTransport(sdkVersion ?? params.protected_headers?.sdk_version, capability)) {
38
41
  // Evol App versions backed by fastaun < 0.5.17 do not consume the
39
42
  // volatile cursor or understand device-targeted Menu responses.
40
- return rest;
43
+ return { ...rest, message_class: MENU_MESSAGE_CLASS };
41
44
  }
42
45
  if (target === undefined)
43
- return { ...rest, ttl: MENU_MESSAGE_TTL_SECONDS };
46
+ return { ...rest, message_class: MENU_MESSAGE_CLASS, ttl: MENU_MESSAGE_TTL_SECONDS };
44
47
  const deviceId = menuSenderDeviceId(target);
45
48
  if (!deviceId) {
46
49
  throw Object.assign(new Error('Invalid Menu reply device'), { code: 'INVALID_MENU_REPLY_DEVICE', retryable: false });
47
50
  }
48
51
  // device_id takes precedence in the SDK; do not let it override the captured
49
52
  // request sender. A rejected target is never retried as an AID broadcast.
50
- return { ...rest, ttl: MENU_MESSAGE_TTL_SECONDS, to_device_id: deviceId };
53
+ return { ...rest, message_class: MENU_MESSAGE_CLASS, ttl: MENU_MESSAGE_TTL_SECONDS, to_device_id: deviceId };
51
54
  }
@@ -62,6 +62,9 @@ function discoverInstancePort(serviceName, expectedPort) {
62
62
  && isProcessAlive(rec.pid)
63
63
  && typeof rec.startedAt === 'number'
64
64
  && Number.isFinite(rec.startedAt)
65
+ && (raw.owner !== 'evolcore-service-supervisor'
66
+ || ((raw.state === undefined || raw.state === 'ready')
67
+ && startTimeMatches(rec.startedAt, getProcessStartTime(rec.pid))))
65
68
  && (serviceName !== 'ecweb' || !('schemaVersion' in rec) || startTimeMatches(rec.startedAt, getProcessStartTime(rec.pid)))
66
69
  && rec.startedAt >= 0
67
70
  && Number.isInteger(rec.port)