evolcore 0.0.48 → 0.0.49

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 (112) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/agent-template/runtime.js +5 -2
  3. package/dist/agents/codex-runner.js +5 -1
  4. package/dist/aun/msg/p2p.js +2 -1
  5. package/dist/build-identity.json +1 -1
  6. package/dist/channels/aun.js +643 -273
  7. package/dist/cli/directory.js +6 -1
  8. package/dist/cli/index.js +7 -1
  9. package/dist/cli/managed-command-guard.js +2 -0
  10. package/dist/cli/model.js +20 -5
  11. package/dist/cli/quota.js +89 -0
  12. package/dist/cli/role.js +1 -0
  13. package/dist/cli/services-command.js +1 -0
  14. package/dist/cli/team-workspace-command.js +56 -2
  15. package/dist/config/config-field-policy.js +71 -1
  16. package/dist/config/config-manager.js +11 -1
  17. package/dist/config/providers-config.js +8 -4
  18. package/dist/config/providers-management.js +11 -3
  19. package/dist/config/resolved-config-op.js +3 -2
  20. package/dist/core/auth/delegation-authorization.js +33 -26
  21. package/dist/core/auth/operation-catalog.js +9 -0
  22. package/dist/core/command/cli-intent-parser.js +13 -0
  23. package/dist/core/command/command-handler.js +45 -2
  24. package/dist/core/command/menu-handler.js +6 -1
  25. package/dist/core/command/menu-protocol.js +24 -0
  26. package/dist/core/command/remote-shell.js +565 -0
  27. package/dist/core/daemon-control.js +57 -1
  28. package/dist/core/daemon-lifecycle.js +16 -2
  29. package/dist/core/evolagent-registry.js +6 -2
  30. package/dist/core/ipc-registration.js +1 -0
  31. package/dist/core/message/aun-ipc-sender.js +118 -56
  32. package/dist/core/message/contact-admission.js +91 -6
  33. package/dist/core/message/contact-pending-inbound.js +113 -0
  34. package/dist/core/message/contact-thread-approval.js +212 -0
  35. package/dist/core/message/im-renderer.js +40 -1
  36. package/dist/core/message/message-admission.js +5 -39
  37. package/dist/core/message/message-bridge.js +92 -39
  38. package/dist/core/message/message-log.js +24 -0
  39. package/dist/core/message/message-queue.js +97 -15
  40. package/dist/core/message/response-engine.js +151 -18
  41. package/dist/core/model/config-scope.js +6 -14
  42. package/dist/core/model/model-diagnostics.js +19 -0
  43. package/dist/core/model/model-fallback.js +13 -2
  44. package/dist/core/pack-auth.js +3 -0
  45. package/dist/core/pack-install.js +1 -1
  46. package/dist/core/permission/ec-command-parser.js +106 -19
  47. package/dist/core/permission/services-path-acl.js +451 -0
  48. package/dist/core/permission/tool-policy.js +5 -1
  49. package/dist/core/relation/peer-identity.js +13 -0
  50. package/dist/core/task/task-recovery-service.js +1 -0
  51. package/dist/core/thread/topic-id.js +15 -0
  52. package/dist/directory/owner-directory-admission.js +11 -8
  53. package/dist/directory/owner-directory-cache.js +19 -0
  54. package/dist/directory/owner-directory-markdown.js +1 -1
  55. package/dist/directory/owner-directory-policy.js +5 -30
  56. package/dist/directory/owner-directory-request-operation.js +5 -2
  57. package/dist/eck/kit-renderer.js +1 -1
  58. package/dist/eck/message-renderer.js +28 -5
  59. package/dist/ecweb/runtime/supervisor.js +36 -8
  60. package/dist/event-center/center-config.js +9 -5
  61. package/dist/event-center/dispatcher.js +10 -1
  62. package/dist/event-center/ipc-operation.js +19 -0
  63. package/dist/event-center/registry.js +20 -5
  64. package/dist/event-center/runtime.js +10 -7
  65. package/dist/index.js +4 -0
  66. package/dist/ipc.js +25 -1
  67. package/dist/outputs/authorization.js +16 -0
  68. package/dist/outputs/cards.js +336 -0
  69. package/dist/outputs/events.js +3 -2
  70. package/dist/outputs/protocol.js +1 -0
  71. package/dist/outputs/service.js +2 -15
  72. package/dist/services/index.js +29 -5
  73. package/dist/services/ipc-operation.js +84 -0
  74. package/dist/services/pack-manager.js +1 -0
  75. package/dist/services/service-payload.js +13 -7
  76. package/dist/stats/budget.js +1 -1
  77. package/dist/stats/model-resolver.js +2 -2
  78. package/dist/stats/quota-query.js +95 -0
  79. package/dist/trigger/script-sandbox.js +12 -0
  80. package/dist/utils/atomic-write.js +22 -8
  81. package/dist/utils/evolcore-version.js +2 -2
  82. package/dist/utils/host-info.js +100 -1
  83. package/dist/utils/npm-ops.js +43 -8
  84. package/dist/workbench/service.js +1 -1
  85. package/kits/docs/evolcore/INDEX.md +2 -0
  86. package/kits/docs/evolcore/aid.md +25 -0
  87. package/kits/docs/evolcore/config.md +4 -1
  88. package/kits/docs/evolcore/directory.md +8 -9
  89. package/kits/docs/evolcore/msg.md +9 -0
  90. package/kits/docs/evolcore/provider.md +1 -1
  91. package/kits/docs/evolcore/quota.md +54 -0
  92. package/kits/docs/evolcore/role.md +3 -0
  93. package/kits/docs/evolcore/stats.md +2 -0
  94. package/kits/docs/evolcore/trigger.md +2 -0
  95. package/kits/schemas/agent-config.schema.20.json +24 -0
  96. package/kits/skills/.switches.json +4 -0
  97. package/kits/skills/agent-output-cards/SKILL.md +57 -0
  98. package/kits/skills/ec-provider/SKILL.md +57 -8
  99. package/kits/templates/roles/visitor.json +1 -0
  100. package/kits/templates/system-fragments/commands.md +1 -0
  101. package/kits/templates/system-fragments/directory-contacts.md +3 -4
  102. package/kits/templates/system-fragments/thread.md +1 -0
  103. package/kits/templates/system-fragments/venue.md +11 -0
  104. package/package.json +2 -2
  105. package/scripts/agent-template/inspect.mjs +46 -10
  106. package/scripts/agent-template/shared/common.mjs +9 -3
  107. package/scripts/agent-template/shared/team-schema.json +6 -4
  108. package/scripts/agent-template/shared/template-contract.mjs +60 -10
  109. package/scripts/agent-template/shared/template-package.mjs +182 -21
  110. package/scripts/agent-template/shared/template-runtime.mjs +35 -2
  111. package/scripts/agent-template/shared/template.mjs +2 -2
  112. package/scripts/agent-template/team-pack.mjs +46 -11
@@ -334,6 +334,30 @@ export function appendMessageLog(chatDir, entry) {
334
334
  }
335
335
  notifyInbound(chatDir, entry);
336
336
  }
337
+ /** Durable replay history deduplication across daemon restarts. */
338
+ export function appendInboundMessageLogOnce(chatDir, entry, operationId) {
339
+ const file = messageLogPath(chatDir);
340
+ let lines = [];
341
+ try {
342
+ lines = fs.readFileSync(file, 'utf8').split('\n');
343
+ }
344
+ catch (error) {
345
+ if (error.code !== 'ENOENT')
346
+ throw error;
347
+ }
348
+ for (const line of lines) {
349
+ let previous;
350
+ try {
351
+ previous = JSON.parse(line);
352
+ }
353
+ catch {
354
+ continue;
355
+ }
356
+ if (previous.dir === 'in' && previous.operationId === operationId)
357
+ return;
358
+ }
359
+ appendMessageLogStrict(chatDir, { ...entry, operationId }, true);
360
+ }
337
361
  /** Strict conversation-history append used by handoff reply binding. */
338
362
  export function appendMessageLogStrict(chatDir, entry, durable = false) {
339
363
  if (isTransientProtocolMessage(entry))
@@ -1,3 +1,4 @@
1
+ import { CONTACT_RECEIPT_TTL_MS, trustedContactInboundDelivery } from './contact-pending-inbound.js';
1
2
  import path from 'path';
2
3
  import fs from 'fs';
3
4
  import { logger } from '../../utils/logger.js';
@@ -9,12 +10,15 @@ import { isTopicThreadId, normalizeTopicAid, safeFormatMainTopicId } from '../th
9
10
  /** Validate before either classification or restoration can rewrite the snapshot. */
10
11
  export function parseQueueSnapshot(value) {
11
12
  const file = value;
12
- if (!file || ![1, 2, 3].includes(file.version) || !Array.isArray(file.queues)
13
+ if (!file || ![1, 2, 3, 4].includes(file.version) || !Array.isArray(file.queues)
13
14
  || (file.active !== undefined && !Array.isArray(file.active))
14
- || (file.version === 3 && (!Array.isArray(file.recoveryIndexedAids)
15
+ || (file.version >= 3 && (!Array.isArray(file.recoveryIndexedAids)
15
16
  || file.recoveryIndexedAids.some(aid => typeof aid !== 'string' || !aid) || !Array.isArray(file.active)))) {
16
17
  throw new Error('invalid message queue snapshot');
17
18
  }
19
+ if (file.version === 4 && (!Array.isArray(file.contactReceipts) || file.contactReceipts.some(receipt => !receipt || !/^[a-f0-9]{64}$/.test(receipt.key) || !Number.isFinite(receipt.acceptedAt)
20
+ || !['queued', 'handled'].includes(receipt.outcome))))
21
+ throw new Error('invalid contact receipts');
18
22
  const validPart = (part) => !!part && typeof part.projectPath === 'string'
19
23
  && !!part.projectPath && !!part.message && typeof part.message === 'object'
20
24
  && typeof part.message.channel === 'string' && typeof part.message.channelId === 'string';
@@ -28,7 +32,7 @@ export function parseQueueSnapshot(value) {
28
32
  return file;
29
33
  }
30
34
  export function hasIndexedRecovery(file, aid) {
31
- return file?.version === 3 && file.recoveryIndexedAids?.includes(aid) === true;
35
+ return (file?.version ?? 0) >= 3 && file?.recoveryIndexedAids?.includes(aid) === true;
32
36
  }
33
37
  const DEFAULT_AGENT_NAME = '<unknown>';
34
38
  const RESTART_RESUME_CONTENT = 'evolcore 服务已重启,请继续之前未完成的任务。';
@@ -87,6 +91,42 @@ export class MessageQueue {
87
91
  blockedReason;
88
92
  wasObserverHintConsumed;
89
93
  recoveryIndexedAids = [];
94
+ contactReceipts = new Map();
95
+ contactReceiptsLoaded = false;
96
+ contactDeliveryReceipt(key) {
97
+ if (!this.persistencePath)
98
+ throw new Error('durable contact queue unavailable');
99
+ if (!this.contactReceiptsLoaded) {
100
+ let snapshot;
101
+ try {
102
+ snapshot = parseQueueSnapshot(JSON.parse(fs.readFileSync(this.persistencePath, 'utf8')));
103
+ }
104
+ catch (error) {
105
+ if (error.code !== 'ENOENT')
106
+ throw error;
107
+ }
108
+ for (const receipt of snapshot?.contactReceipts ?? [])
109
+ this.contactReceipts.set(receipt.key, receipt);
110
+ this.contactReceiptsLoaded = true;
111
+ }
112
+ return this.contactReceipts.get(key);
113
+ }
114
+ finishContactDelivery(delivery) {
115
+ if (!trustedContactInboundDelivery(delivery))
116
+ throw new Error('untrusted contact delivery');
117
+ const previous = this.contactDeliveryReceipt(delivery.key);
118
+ if (previous) {
119
+ delivery.receipt = previous;
120
+ return;
121
+ }
122
+ const receipt = { key: delivery.key, acceptedAt: Date.now(), outcome: 'handled' };
123
+ this.contactReceipts.set(delivery.key, receipt);
124
+ if (!this.persistQueuesSync()) {
125
+ this.contactReceipts.delete(delivery.key);
126
+ throw new Error('failed to persist contact terminal outcome');
127
+ }
128
+ delivery.receipt = receipt;
129
+ }
90
130
  blockedQueues = new Map();
91
131
  readinessRetry;
92
132
  shutdownPromise;
@@ -847,8 +887,13 @@ export class MessageQueue {
847
887
  });
848
888
  }
849
889
  fs.mkdirSync(path.dirname(this.persistencePath), { recursive: true });
890
+ for (const [key, receipt] of this.contactReceipts) {
891
+ if (receipt.acceptedAt + CONTACT_RECEIPT_TTL_MS <= Date.now())
892
+ this.contactReceipts.delete(key);
893
+ }
850
894
  const data = {
851
- version: 3,
895
+ version: 4,
896
+ contactReceipts: [...this.contactReceipts.values()],
852
897
  recoveryIndexedAids: this.recoveryIndexedAids,
853
898
  updatedAt: Date.now(),
854
899
  queues: buckets,
@@ -976,7 +1021,10 @@ export class MessageQueue {
976
1021
  }
977
1022
  }
978
1023
  const parsed = parseQueueSnapshot(captured);
979
- this.recoveryIndexedAids = parsed.version === 3 ? [...parsed.recoveryIndexedAids] : [];
1024
+ this.recoveryIndexedAids = parsed.version >= 3 ? [...parsed.recoveryIndexedAids] : [];
1025
+ for (const receipt of parsed.contactReceipts ?? [])
1026
+ this.contactReceipts.set(receipt.key, receipt);
1027
+ this.contactReceiptsLoaded = true;
980
1028
  // Version-1 snapshots did not carry per-item enqueue times. Preserve
981
1029
  // their last durable snapshot time instead of making restored history
982
1030
  // look newly queued at the moment of daemon restart.
@@ -1095,14 +1143,24 @@ export class MessageQueue {
1095
1143
  // broadcast object must be cloned per agent before dedup/cancel logic.
1096
1144
  message = { ...message, selfAID: options.selfAID };
1097
1145
  }
1146
+ const contactDelivery = trustedContactInboundDelivery(options?.contactDelivery);
1147
+ if (contactDelivery) {
1148
+ const receipt = this.contactDeliveryReceipt(contactDelivery.key);
1149
+ if (receipt) {
1150
+ contactDelivery.receipt = receipt;
1151
+ options?.onPersisted?.();
1152
+ return;
1153
+ }
1154
+ contactDelivery.validate();
1155
+ }
1098
1156
  // 消息去重检查
1099
- if (message.source !== 'owner-inject' && !this.shouldProcess(sessionKey, message, options?.selfAID)) {
1157
+ if (!contactDelivery && message.source !== 'owner-inject' && !this.shouldProcess(sessionKey, message, options?.selfAID)) {
1100
1158
  options?.onPersisted?.();
1101
1159
  return Promise.resolve();
1102
1160
  }
1103
1161
  // 拦截器检查:AskUserQuestion 等场景的一次性消息拦截
1104
1162
  const interceptor = this.interceptors.get(sessionKey);
1105
- const canAnswerInteraction = !message.executionPermissionOverride && (message.source === undefined
1163
+ const canAnswerInteraction = !contactDelivery && !message.executionPermissionOverride && (message.source === undefined
1106
1164
  || message.source === 'user'
1107
1165
  || message.source === 'card-trigger');
1108
1166
  if (interceptor && canAnswerInteraction) {
@@ -1217,7 +1275,23 @@ export class MessageQueue {
1217
1275
  abortHandler();
1218
1276
  return;
1219
1277
  }
1278
+ let contactReceipt;
1279
+ if (contactDelivery) {
1280
+ try {
1281
+ contactDelivery.validate();
1282
+ }
1283
+ catch (error) {
1284
+ queue.splice(queue.indexOf(queuedItem), 1);
1285
+ this.logicalQueue.removeProcessed(queueKey, message.messageId ? [message.messageId] : []);
1286
+ rejectOnce(error);
1287
+ return;
1288
+ }
1289
+ contactReceipt = { key: contactDelivery.key, sessionId: sessionKey, acceptedAt: Date.now(), outcome: 'queued' };
1290
+ this.contactReceipts.set(contactDelivery.key, contactReceipt);
1291
+ }
1220
1292
  if (!this.persistQueues()) {
1293
+ if (contactDelivery)
1294
+ this.contactReceipts.delete(contactDelivery.key);
1221
1295
  const index = queue.indexOf(queuedItem);
1222
1296
  if (index >= 0)
1223
1297
  queue.splice(index, 1);
@@ -1226,6 +1300,8 @@ export class MessageQueue {
1226
1300
  rejectOnce(new Error('failed to persist message queue'));
1227
1301
  return;
1228
1302
  }
1303
+ if (contactDelivery && contactReceipt)
1304
+ contactDelivery.receipt = contactReceipt;
1229
1305
  // A duplicate must not re-enter a runner after the queue entry has
1230
1306
  // survived its write-ahead snapshot. Keep this separate from the queue
1231
1307
  // snapshot because deduplication must survive task completion.
@@ -1235,14 +1311,20 @@ export class MessageQueue {
1235
1311
  options?.onPersisted?.();
1236
1312
  }
1237
1313
  catch (error) {
1238
- const index = queue.indexOf(queuedItem);
1239
- if (index >= 0)
1240
- queue.splice(index, 1);
1241
- this.logicalQueue.removeProcessed(queueKey, message.messageId ? [message.messageId] : []);
1242
- this.forgetProcessed(sessionKey, message);
1243
- this.persistQueues();
1244
- rejectOnce(error);
1245
- return;
1314
+ if (contactDelivery) {
1315
+ // Persistence is already committed; a diagnostic/release callback must not retract acceptance.
1316
+ logger.warn('[Queue] Contact onPersisted callback failed:', error);
1317
+ }
1318
+ else {
1319
+ const index = queue.indexOf(queuedItem);
1320
+ if (index >= 0)
1321
+ queue.splice(index, 1);
1322
+ this.logicalQueue.removeProcessed(queueKey, message.messageId ? [message.messageId] : []);
1323
+ this.forgetProcessed(sessionKey, message);
1324
+ this.persistQueues();
1325
+ rejectOnce(error);
1326
+ return;
1327
+ }
1246
1328
  }
1247
1329
  if (options?.resolveOnPersist)
1248
1330
  resolveOnce();
@@ -23,7 +23,6 @@ import { notifyWorkbenchRuntimeChanged } from '../../workbench/service.js';
23
23
  import { createSendFileMarkerPattern } from './file-markers.js';
24
24
  import { hasOwnerDirectoryMarkdown } from '../../directory/owner-directory-markdown.js';
25
25
  import { EMPTY_IDENTITY, readOwnerDirectoryIdentity } from '../../directory/owner-directory-identity.js';
26
- import { resolveContactsState } from '../../directory/owner-directory-policy.js';
27
26
  import { createDecisionInferenceProvider, createTextInferenceProvider } from '../inference/text-inference.js';
28
27
  import { StreamIdleMonitor } from './stream-idle-monitor.js';
29
28
  import { logger } from '../../utils/logger.js';
@@ -92,6 +91,24 @@ import { aunMessageTranscriptUuid } from '../session/session-transcript.js';
92
91
  import { assertAgentPolicyAuthorization } from '../role/runtime-policy.js';
93
92
  import { auditFullAccessEvent } from '../auth/authorization-audit.js';
94
93
  import { REPLY_DELIVERY_FAILED_REASON, TaskRecoveryService, isTaskRecoveryCurrent } from '../task/task-recovery-service.js';
94
+ /** Keep diagnostic logs useful without dumping command bodies or tool output. */
95
+ function diagnosticPreview(value, maxLength = 240) {
96
+ if (value === undefined || value === null)
97
+ return '';
98
+ let text;
99
+ if (typeof value === 'string')
100
+ text = value;
101
+ else {
102
+ try {
103
+ text = JSON.stringify(value);
104
+ }
105
+ catch {
106
+ text = String(value);
107
+ }
108
+ }
109
+ text = text.replace(/[\r\n\u2028\u2029]/g, ' ');
110
+ return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}…`;
111
+ }
95
112
  /** Resolve the channel type separately from a channel instance name. */
96
113
  export function resolveMessageChannelType(options, message) {
97
114
  return options?.channelType || message.channelType || message.channel;
@@ -4027,6 +4044,12 @@ export class ResponseEngine {
4027
4044
  ? (peerRoleDetail.effectiveRole ?? 'visitor')
4028
4045
  : (isOwnerDirectoryContact(selfAid || '', configActorId || '') ? 'member' : 'visitor'))
4029
4046
  : peerRole;
4047
+ const sameOwnerQualificationResult = configChannelType === 'aun'
4048
+ && configChatType === 'private'
4049
+ && !!selfAid
4050
+ && !!configActorId
4051
+ ? sameOwnerQualification(selfAid, configActorId)
4052
+ : 'not_applicable';
4030
4053
  let effectiveAgentConfigError;
4031
4054
  const effectiveAgentConfig = (() => {
4032
4055
  try {
@@ -4650,17 +4673,39 @@ export class ResponseEngine {
4650
4673
  send: async (payload) => {
4651
4674
  if (turnLease && !this.turnCoordinator.canPublish(turnLease)) {
4652
4675
  snapshot.pushOutbound(session.id, taskId, { kind: payload.kind, decision: 'suppressed-stale-turn' });
4676
+ logger.info(`[ResponseEngine] outbound.suppressed ${JSON.stringify({
4677
+ reason: 'stale_turn',
4678
+ kind: payload.kind,
4679
+ taskId,
4680
+ sessionId: session.id,
4681
+ messageId: message.messageId ?? 'none',
4682
+ })}`);
4653
4683
  return;
4654
4684
  }
4655
4685
  // proactive 模式:activity.batch 是 thought 协议内容,只发给支持 thought 的 channel
4656
4686
  // (不支持 thought 的 channel 静默丢弃,避免降级为普通消息)
4657
4687
  if (isProactive && payload.kind === 'activity.batch' && !adapter.capabilities?.thought) {
4658
4688
  snapshot.pushOutbound(session.id, taskId, { kind: payload.kind, decision: 'suppressed-thought' });
4689
+ logger.info(`[ResponseEngine] outbound.suppressed ${JSON.stringify({
4690
+ reason: 'channel_without_thought_capability',
4691
+ kind: payload.kind,
4692
+ chatmode,
4693
+ activityTransport,
4694
+ taskId,
4695
+ sessionId: session.id,
4696
+ })}`);
4659
4697
  return;
4660
4698
  }
4661
4699
  const isCurrentlyBackground = this.isBackgroundSession(session, message.channel, message.channelId);
4662
4700
  if (isCurrentlyBackground) {
4663
4701
  snapshot.pushOutbound(session.id, taskId, { kind: payload.kind, decision: 'suppressed-bg' });
4702
+ logger.info(`[ResponseEngine] outbound.suppressed ${JSON.stringify({
4703
+ reason: 'background_session',
4704
+ kind: payload.kind,
4705
+ chatmode,
4706
+ taskId,
4707
+ sessionId: session.id,
4708
+ })}`);
4664
4709
  return;
4665
4710
  }
4666
4711
  const opts = {};
@@ -4702,7 +4747,46 @@ export class ResponseEngine {
4702
4747
  }
4703
4748
  const enrichedEnvelope = withEnvelopeReplyContext(envelope, opts);
4704
4749
  snapshot.pushOutbound(session.id, taskId, { kind: payload.kind, decision: 'sent' });
4705
- return await adapter.send(enrichedEnvelope, payload);
4750
+ const shouldTraceDelivery = payload.kind === 'result.text'
4751
+ || (payload.kind === 'activity.batch' && payload.isFinal === true);
4752
+ if (shouldTraceDelivery) {
4753
+ logger.info(`[ResponseEngine] outbound.attempt ${JSON.stringify({
4754
+ kind: payload.kind,
4755
+ isFinal: payload.isFinal === true,
4756
+ chatmode,
4757
+ activityTransport,
4758
+ taskId,
4759
+ sessionId: session.id,
4760
+ messageId: message.messageId ?? 'none',
4761
+ textLength: typeof payload.text === 'string' ? payload.text.length : undefined,
4762
+ })}`);
4763
+ }
4764
+ try {
4765
+ const receipt = await adapter.send(enrichedEnvelope, payload);
4766
+ if (shouldTraceDelivery) {
4767
+ logger.info(`[ResponseEngine] outbound.accepted ${JSON.stringify({
4768
+ kind: payload.kind,
4769
+ isFinal: payload.isFinal === true,
4770
+ taskId,
4771
+ sessionId: session.id,
4772
+ })}`);
4773
+ }
4774
+ return receipt;
4775
+ }
4776
+ catch (error) {
4777
+ logger.error(`[ResponseEngine] outbound.failed ${JSON.stringify({
4778
+ kind: payload.kind,
4779
+ isFinal: payload.isFinal === true,
4780
+ chatmode,
4781
+ activityTransport,
4782
+ taskId,
4783
+ sessionId: session.id,
4784
+ messageId: message.messageId ?? 'none',
4785
+ error: diagnosticPreview(error instanceof Error ? error.message : error),
4786
+ code: error?.code,
4787
+ })}`);
4788
+ throw error;
4789
+ }
4706
4790
  },
4707
4791
  });
4708
4792
  this.activeRenderers.set(session.id, {
@@ -5319,6 +5403,25 @@ export class ResponseEngine {
5319
5403
  // records all observe the same normalized value.
5320
5404
  permissionContext.permissionMode = effectivePermissionMode;
5321
5405
  permissionContext.executionPermission = fullAccessAuthorization;
5406
+ logger.info(`[ResponseEngine] authorization.resolved ${JSON.stringify({
5407
+ messageId: message.messageId ?? 'none',
5408
+ taskId,
5409
+ sessionId: session.id,
5410
+ selfAid: selfAid ?? 'none',
5411
+ actorId: configActorId ?? 'none',
5412
+ peerKey: peerKey ?? 'none',
5413
+ peerType: peerType ?? 'unknown',
5414
+ peerRole,
5415
+ speakerRelation,
5416
+ roleSource: authorizationIdentity ? 'execution-identity' : peerRoleDetail?.source ?? 'session-fallback',
5417
+ roleExists: peerRoleDetail?.roleExists,
5418
+ allowAccess: peerRoleDetail?.allowAccess,
5419
+ authenticated: peerRoleDetail?.isAuthenticated ?? hasTrustedPrincipal(authenticatedActor),
5420
+ principalStatus: authenticatedActor.principalStatus,
5421
+ sameOwnerQualification: sameOwnerQualificationResult,
5422
+ permissionMode: effectivePermissionMode,
5423
+ permissionOverride: triggerPermissionModeOverride ?? commandFullAccess?.permissionMode ?? 'none',
5424
+ })}`);
5322
5425
  const showFullAccessPrompt = fullAccessAuthorization?.source === 'fullaccess-command'
5323
5426
  || (fullAccessAuthorization?.source === 'session-policy'
5324
5427
  && readSessionFullAccessOverride(session)?.promptedSessionId !== session.id);
@@ -5678,21 +5781,7 @@ export class ResponseEngine {
5678
5781
  // isOwner 与 ownerAid 同源(归属协议),避免名录快照滞后时把自封 Owner 的角色注入进去。
5679
5782
  isPersonalAssistant: !!personalAssistantAid && personalAssistantAid === selfAid,
5680
5783
  isOwner: !!protocolOwnerAid && protocolOwnerAid === selfAid,
5681
- // 准入现状压成一句话:只列能联系谁,说不通的档位直接不提。
5682
- // 只说"能",不说"谁关的"——默认关与显式关在结果上没区别。
5683
- ...(() => {
5684
- if (!selfAid)
5685
- return {};
5686
- const state = resolveContactsState(selfAid, personalAssistantAid);
5687
- const open = ['Owner', '个人助理'];
5688
- if (state.internalContacts)
5689
- open.push('内部联系人');
5690
- if (state.externalContacts)
5691
- open.push('外部联系人');
5692
- if (state.strangerContacts)
5693
- open.push('名录外的人');
5694
- return { contactsState: `现在可联系:${open.join('、')}` };
5695
- })(),
5784
+ contactsState: '普通出站消息可直接按 AID 发送;入站按联系人范围与许可准入',
5696
5785
  // 记忆系统开关变量(来自 effectiveAgentConfig.memory,默认全部启用)。
5697
5786
  // enableRelation 是总开关:relation 是所有记忆的唯一出生地。
5698
5787
  // memory.enableRelation 在 relation-config schema 里声明了 x-merge-logic: AND,
@@ -6901,6 +6990,20 @@ export class ResponseEngine {
6901
6990
  throw tagged;
6902
6991
  }
6903
6992
  }
6993
+ logger.info(`[ResponseEngine] output.decision ${JSON.stringify({
6994
+ sessionId: session.id,
6995
+ taskId,
6996
+ messageId: message.messageId ?? 'none',
6997
+ chatmode,
6998
+ activityTransport: activityTransport ?? 'none',
6999
+ isProactive,
7000
+ streamIsError: streamResult.isError,
7001
+ terminalInterrupt,
7002
+ isNoopReply,
7003
+ streamTextLength: (streamResult.lastReplyText || streamResult.fullText || '').length,
7004
+ rendererTextLength: renderer.getFinalText().length,
7005
+ rendererSentContent: renderer.hasSentContent(),
7006
+ })}`);
6904
7007
  if (!streamResult.isError && !terminalInterrupt) {
6905
7008
  const commitDecision = await this.turnCoordinator.commit(session, turnLease, this.buildTurnCommitEvidence(session, streamResult));
6906
7009
  if (!commitDecision.ok) {
@@ -8281,7 +8384,12 @@ export class ResponseEngine {
8281
8384
  ?? (decision === 'deny' ? 'blocked' : event.isError ? 'failed' : 'completed');
8282
8385
  eventDetail = ` tool=${event.name} ok=${decision === 'allow' && executed}`
8283
8386
  + ` decision=${decision} executed=${executed} executionState=${executionState}`
8284
- + (event.policyCode ? ` policy=${event.policyCode}` : '');
8387
+ + (event.policyCode ? ` policy=${event.policyCode}` : '')
8388
+ + (event.exitCode !== undefined ? ` exitCode=${event.exitCode}` : '')
8389
+ + (event.errorCode ? ` errorCode=${event.errorCode}` : '')
8390
+ + (event.error ? ` error="${diagnosticPreview(event.error, 180)}"` : '')
8391
+ + (event.result !== undefined && (event.isError || event.exitCode !== undefined)
8392
+ ? ` result="${diagnosticPreview(event.result, 180)}"` : '');
8285
8393
  }
8286
8394
  const frameworkEvents = new Set(['session_id', 'state_changed', 'status']);
8287
8395
  if (frameworkEvents.has(event.type)) {
@@ -8718,6 +8826,31 @@ export class ResponseEngine {
8718
8826
  }
8719
8827
  if (original)
8720
8828
  removePendingToolInput(original);
8829
+ if (event.isError || event.error || event.exitCode !== undefined) {
8830
+ const command = typeof original?.input?.command === 'string'
8831
+ ? original.input.command
8832
+ : typeof original?.input?.input === 'string'
8833
+ ? original.input.input
8834
+ : undefined;
8835
+ logger.warn(`[ResponseEngine] tool.result.diagnostic ${JSON.stringify({
8836
+ sessionId: session.id,
8837
+ taskId: turnLease?.taskId ?? 'none',
8838
+ toolName: event.name,
8839
+ callId: event.callId ?? 'none',
8840
+ correlationId: event.correlationId ?? 'none',
8841
+ command: command ? diagnosticPreview(command) : undefined,
8842
+ isError: event.isError === true,
8843
+ decision: event.decision ?? 'error',
8844
+ decisionSource: event.decisionSource ?? 'runner',
8845
+ executed: event.executed,
8846
+ executionState: event.executionState,
8847
+ exitCode: event.exitCode,
8848
+ errorCode: event.errorCode,
8849
+ errorDetailCode: event.errorDetailCode,
8850
+ error: diagnosticPreview(event.error),
8851
+ result: diagnosticPreview(event.result),
8852
+ })}`);
8853
+ }
8721
8854
  if (original && modeHooks?.mode?.onToolResult) {
8722
8855
  const proactiveState = modeHooks.state.get('proactive');
8723
8856
  await modeHooks.mode.onToolResult({
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * 详见 docs/config/
16
16
  */
17
- import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
17
+ import { normalizePeerKey } from '../relation/peer-identity.js';
18
18
  import { ConfigTarget, read, write, ensureFile, resolveEffective, } from '../../config/config-manager.js';
19
19
  import { resolveRuntimePermissionMode } from '../role/runtime-policy.js';
20
20
  export class ModelScopeError extends Error {
@@ -35,20 +35,12 @@ export function normalizePeer(input) {
35
35
  const raw = (input || '').trim();
36
36
  if (!raw)
37
37
  throw new ModelScopeError('INVALID_PEER', '--peer 不能为空');
38
- if (raw.includes('#')) {
39
- let parsed;
40
- try {
41
- parsed = parsePeerKey(raw);
42
- }
43
- catch {
44
- throw new ModelScopeError('INVALID_PEER', `无法解析 --peer: ${raw}`);
45
- }
46
- if (!parsed.channelType || !parsed.channelId) {
47
- throw new ModelScopeError('INVALID_PEER', `无法解析 --peer: ${raw}`);
48
- }
49
- return formatPeerKey(parsed.channelType, parsed.channelId);
38
+ try {
39
+ return normalizePeerKey(raw);
40
+ }
41
+ catch {
42
+ throw new ModelScopeError('INVALID_PEER', `无法解析 --peer: ${raw}`);
50
43
  }
51
- return formatPeerKey('aun', raw);
52
44
  }
53
45
  // ── 作用域判定(CLI 写入目标)─────────────────────────────────────────────
54
46
  /**
@@ -4,6 +4,7 @@ import { appendV1RequestPath } from '../../agents/request-identity.js';
4
4
  import { resolveEffective, resolveEffectiveFieldWithSource } from '../../config/config-manager.js';
5
5
  import { constrainResolvedModelForRole } from './model-permission.js';
6
6
  import { getCatalog } from './model-catalog.js';
7
+ import { eligibleFallbackModels } from './model-fallback.js';
7
8
  async function fetchWithTimeout(url, opts, timeoutMs) {
8
9
  const controller = new AbortController();
9
10
  const timer = setTimeout(() => controller.abort(), timeoutMs);
@@ -172,6 +173,24 @@ export async function runModelCheck(input) {
172
173
  log(configuredModel
173
174
  ? { label: '配置模型', ok: true, detail: `${configuredModel}(来源: ${configuredModelSource ?? '未知'})` }
174
175
  : { label: '配置模型', ok: false, detail: '无法解析当前基座的模型' });
176
+ // 降级链的候选会被静默过滤(不在目录、effort 不支持、重复等),这里把过滤结果显式报出来。
177
+ const fallbackResolution = await eligibleFallbackModels({
178
+ selfAid: input.self,
179
+ baseagent: input.baseagent,
180
+ currentModel: configuredModel,
181
+ currentProvider: resolveEffective(selector, { cache: true }).baseagents?.[input.baseagent]?.provider,
182
+ isAllowed: () => true,
183
+ });
184
+ if (fallbackResolution.candidates.length || fallbackResolution.rejected.length) {
185
+ const admitted = fallbackResolution.candidates.length;
186
+ const dropped = fallbackResolution.rejected
187
+ .map(item => `${item.model ?? '<invalid>'}:${item.reason}`);
188
+ log({
189
+ label: '降级链',
190
+ ok: fallbackResolution.rejected.length === 0,
191
+ detail: `${admitted} 条生效${dropped.length ? `,丢弃 ${dropped.length} 条(${dropped.join('、')})` : ''}`,
192
+ });
193
+ }
175
194
  const probeResults = [];
176
195
  if (baseUrl) {
177
196
  const aliases = new Map();
@@ -104,12 +104,23 @@ async function eligibleCandidates(input) {
104
104
  const efforts = input.serviceType === 'text'
105
105
  ? catalog.models.find(entry => entry.id === resolvedModel)?.reasoningLevels ?? []
106
106
  : catalogEfforts(catalog, resolvedModel, input.serviceType);
107
- if (candidate.effort && !efforts.includes(candidate.effort)) {
107
+ // 目录未声明任何推理强度(supports_effort=false 的模型):effort 无从校验,
108
+ // 保留候选并丢弃该字段,降级时走模型默认强度,而不是整条丢掉这条兜底。
109
+ const hasDeclaredEfforts = efforts.length > 0;
110
+ if (hasDeclaredEfforts && candidate.effort && !efforts.includes(candidate.effort)) {
108
111
  rejected.push({ model: candidate.model, reason: 'unsupported_effort' });
109
112
  continue;
110
113
  }
111
114
  seen.add(key);
112
- candidates.push({ ...candidate, ...(provider ? { provider } : {}), model: resolvedModel });
115
+ const admitted = {
116
+ ...candidate,
117
+ ...(provider ? { provider } : {}),
118
+ model: resolvedModel,
119
+ };
120
+ // 未声明强度的模型上,显式保留 effort 会被当成"该模型确实支持这个强度"。
121
+ if (!hasDeclaredEfforts)
122
+ delete admitted.effort;
123
+ candidates.push(admitted);
113
124
  }
114
125
  return { candidates, rejected };
115
126
  }
@@ -214,6 +214,9 @@ const PACK_OPERATIONS = {
214
214
  'pack:remove': 'manage',
215
215
  'pack:enable': 'manage',
216
216
  'pack:disable': 'manage',
217
+ // ACL 加固:只改 services 树的 DACL,不碰内容,但属于改防护配置——
218
+ // 与 pack 同档,避免 member 自己去收/放权限。
219
+ 'repair-acl': 'manage',
217
220
  },
218
221
  };
219
222
  /** `pack` 需要带上子动作(list/add/remove/enable/disable),其余命令名本身就是操作键。 */
@@ -13,7 +13,7 @@ import fs from 'node:fs';
13
13
  import path from 'node:path';
14
14
  import { atomicWriteJson } from '../utils/atomic-write.js';
15
15
  /** 包安装期间的运行时产物:不该被拷进新包,也不该被 `pack add` 覆盖。 */
16
- const PACK_RUNTIME_ENTRIES = new Set(['ledger.jsonl', '.idempotency.jsonl', 'logs', '.state.json', '.index.md']);
16
+ export const PACK_RUNTIME_ENTRIES = new Set(['ledger.jsonl', '.idempotency.jsonl', 'logs', '.state.json', '.index.md']);
17
17
  /** 包名:英文短横线/下划线,防止 `..` 或路径分隔符把写入引出目标根。 */
18
18
  const PACK_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
19
19
  function assertPackName(name) {