evolcore 0.0.47 → 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.
- package/CHANGELOG.md +90 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +143 -40
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +34 -17
- package/dist/agents/codex-runner.js +36 -17
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +722 -295
- package/dist/channels/daemon.js +9 -25
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +44 -43
- package/dist/cli/directory.js +13 -2
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +9 -9
- package/dist/cli/init-channel.js +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +62 -17
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/stats.js +3 -3
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +13 -7
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +67 -12
- package/dist/config/providers-management.js +477 -51
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +36 -26
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +37 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +126 -87
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +67 -150
- package/dist/core/command/menu-protocol.js +31 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +26 -43
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +8 -1
- package/dist/core/daemon-control.js +64 -8
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +20 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +3 -1
- package/dist/core/message/aun-ipc-sender.js +279 -107
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +41 -2
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +140 -370
- package/dist/core/message/message-log.js +29 -0
- package/dist/core/message/message-queue.js +119 -15
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +580 -134
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +328 -50
- package/dist/core/pack-auth.js +3 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +106 -19
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/permission/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +36 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-recovery-service.js +13 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +12 -9
- package/dist/directory/owner-directory-cache.js +64 -28
- package/dist/directory/owner-directory-markdown.js +14 -2
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +112 -29
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +36 -6
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +29 -3
- package/dist/event-center/runtime.js +106 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +96 -59
- package/dist/ipc.js +38 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +63 -0
- package/dist/outputs/protocol.js +103 -0
- package/dist/outputs/service.js +266 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +114 -5
- package/dist/services/ipc-operation.js +88 -15
- package/dist/services/pack-manager.js +13 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +2 -2
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/quota-query.js +95 -0
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +21 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +4 -2
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +16 -1
- package/kits/docs/evolcore/directory.md +30 -12
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +124 -4
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +83 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +12 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +8 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +270 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +7 -5
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +50 -11
- package/scripts/agent-template/shared/common.mjs +11 -6
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +62 -11
- package/scripts/agent-template/shared/template-package.mjs +189 -21
- package/scripts/agent-template/shared/template-runtime.mjs +54 -6
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +52 -14
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { initializationBlocksTasks } from '../../cli/agent-create.js';
|
|
2
2
|
import { assertOwnershipAuthorization, getDaemonOwners, refreshOwnershipForAuthorization, resolveContextOwner, OWNERSHIP_CACHE_MAX_AGE_MS } from '../ownership/owner-resolver.js';
|
|
3
|
+
import { currentTriggerExecutionIdentity } from '../../trigger/authorization.js';
|
|
3
4
|
import path from 'path';
|
|
4
5
|
import fs from 'fs';
|
|
5
6
|
import os from 'os';
|
|
6
7
|
import crypto from 'crypto';
|
|
7
8
|
import { MAIN_CLI_BIN } from '../../product.js';
|
|
8
|
-
import { BaseagentRunnerUnavailableError, hasCompact,
|
|
9
|
+
import { BaseagentRunnerUnavailableError, hasCompact, contextTokensForUsage, numericToken, formatAsyncQuestionAnswer, parseAsyncUserQuestions, } from '../../agents/runner-types.js';
|
|
9
10
|
import { loadedBaseagentIds } from '../../agents/baseagent-availability.js';
|
|
10
11
|
import { isDiagnosticSessionActive } from '../command/diag-service.js';
|
|
11
12
|
import { evaluateInboundAdmissionPreflight, evaluateOrdinaryInboundAdmission } from './message-admission.js';
|
|
12
|
-
import { authorizeAccess, authorizeOperation, buildAuthSubject } from '../auth/auth-gateway.js';
|
|
13
|
+
import { authorizeAccess, authorizeOperation, authorizeFreshOperation, buildAuthSubject } from '../auth/auth-gateway.js';
|
|
13
14
|
import { prepareSameOwnerProof, sameOwnerQualification, requiresSameOwnerProof } from '../relation/same-owner-proof.js';
|
|
14
15
|
import { getRoleDefinition } from '../../config/roles.js';
|
|
15
16
|
import { buildTaskRuntimeEnv, ensureRuntimeLockDir, ensureSessionRuntimeDirAsync } from '../../cli/task-context.js';
|
|
@@ -17,11 +18,11 @@ import { BUILTIN_SESSION_PATH_GRANTS, mergeRuntimeGrantsForSession, resolveGrant
|
|
|
17
18
|
import { buildSystemSessionContext, getSystemSessionModule, isSystemSessionType, readSystemSessionMarker } from '../system-session/registry.js';
|
|
18
19
|
import { IMRenderer } from './im-renderer.js';
|
|
19
20
|
import { projectSubtaskStarted, projectSubtaskTerminal } from './subtask-tool-projection.js';
|
|
20
|
-
import { TaskActivityStore } from '../task/task-activity-store.js';
|
|
21
|
+
import { TaskActivityStore, taskActivityTitle } from '../task/task-activity-store.js';
|
|
22
|
+
import { notifyWorkbenchRuntimeChanged } from '../../workbench/service.js';
|
|
21
23
|
import { createSendFileMarkerPattern } from './file-markers.js';
|
|
22
24
|
import { hasOwnerDirectoryMarkdown } from '../../directory/owner-directory-markdown.js';
|
|
23
25
|
import { EMPTY_IDENTITY, readOwnerDirectoryIdentity } from '../../directory/owner-directory-identity.js';
|
|
24
|
-
import { resolveContactsState } from '../../directory/owner-directory-policy.js';
|
|
25
26
|
import { createDecisionInferenceProvider, createTextInferenceProvider } from '../inference/text-inference.js';
|
|
26
27
|
import { StreamIdleMonitor } from './stream-idle-monitor.js';
|
|
27
28
|
import { logger } from '../../utils/logger.js';
|
|
@@ -44,7 +45,7 @@ import { recordCausationLink, recordCausationSpan } from '../causation/audit.js'
|
|
|
44
45
|
import { normalizeBaseagent, resolveBaseagentModelSelection, resolveRuntimeBaseagentModelSelection } from '../../agents/baseagent.js';
|
|
45
46
|
import { renderActionAsText } from '../interaction-router.js';
|
|
46
47
|
import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
|
|
47
|
-
import { buildEnvelope, isInteractionSendAccepted, isNoopText, replyContextFromSession, sendInteractionPayload, withEnvelopeReplyContext } from './message-utils.js';
|
|
48
|
+
import { buildEnvelope, isInteractionSendAccepted, isNoopText, messageNoopSentinel, replyContextFromSession, sendInteractionPayload, withEnvelopeReplyContext } from './message-utils.js';
|
|
48
49
|
import { chatModeForScene, isSystemOrServicePeer, resolveChatMode } from './peer-mode.js';
|
|
49
50
|
import { AGENT_DELEGATION_TOKEN_ENV } from '../auth/agent-delegation.js';
|
|
50
51
|
import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
|
|
@@ -59,12 +60,20 @@ import { constrainResolvedModelForRole, isModelAllowedForRoleBaseagent } from '.
|
|
|
59
60
|
import { eligibleFallbackModels } from '../model/model-fallback.js';
|
|
60
61
|
import { isRecoverableProtocolFailure, RetryScheduler } from './retry-scheduler.js';
|
|
61
62
|
import { assertSessionFullAccessAuthorization, constrainRuntimePermissionMode, readSessionFullAccessOverride, resolveRuntimeStringField, updateRelationSessionFullAccess } from '../role/runtime-policy.js';
|
|
62
|
-
import { resolveEffective, resolveEffectiveFieldWithSource } from '../../config/config-manager.js';
|
|
63
|
+
import { ConfigTarget, mutateConfig, resolveEffective, resolveEffectiveFieldWithSource } from '../../config/config-manager.js';
|
|
64
|
+
import { ProviderConnectionQuestions, providerConnectionContext } from '../../config/providers-management.js';
|
|
65
|
+
import { errorQuestionRule } from '../../utils/error-utils.js';
|
|
66
|
+
import { catalogHash, clearModelCatalogCache, getRunnerCatalog } from '../model/model-catalog.js';
|
|
67
|
+
import { probeTextModel } from '../invoke/executors/text.js';
|
|
68
|
+
import { assertProviderModelAllowed } from '../../config/providers-config.js';
|
|
69
|
+
import { resolveCatalogAutoCompactPolicy } from '../model/model-capabilities.js';
|
|
70
|
+
import { resolveNativeConnectionForRepair } from '../../agents/baseagent.js';
|
|
71
|
+
import { resolveProviderService, resolveProviderServiceForBaseagent } from '../../config/providers.js';
|
|
63
72
|
import { resolveAgentLifecycle } from '../../config/lifecycle.js';
|
|
64
73
|
import { authorizationConfigRevision, checkRoleAccess, getFirstStaticAgentOwner, listStaticAgentAdmins, listStaticAgentOwners, resolvePeerRoleDetail, roleToSessionIdentity, } from '../../config/peer-role-resolver.js';
|
|
65
74
|
import { insertUsageEvent, insertContextBreakdown, insertModelCalls } from '../../stats/writer.js';
|
|
66
75
|
import { normalizeUsage } from '../../stats/normalizer.js';
|
|
67
|
-
import { resolvePrices, roundCostForOutput } from '../../stats/
|
|
76
|
+
import { resolvePrices, roundCostForOutput } from '../../stats/model-resolver.js';
|
|
68
77
|
import { getBudgetStatus } from '../../stats/budget.js';
|
|
69
78
|
import { formatUsageSubjectKey, getRoleBudgetStatus } from '../../stats/role-budget.js';
|
|
70
79
|
import { snapshot } from './response-snapshot.js';
|
|
@@ -82,6 +91,24 @@ import { aunMessageTranscriptUuid } from '../session/session-transcript.js';
|
|
|
82
91
|
import { assertAgentPolicyAuthorization } from '../role/runtime-policy.js';
|
|
83
92
|
import { auditFullAccessEvent } from '../auth/authorization-audit.js';
|
|
84
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
|
+
}
|
|
85
112
|
/** Resolve the channel type separately from a channel instance name. */
|
|
86
113
|
export function resolveMessageChannelType(options, message) {
|
|
87
114
|
return options?.channelType || message.channelType || message.channel;
|
|
@@ -92,6 +119,8 @@ const QUESTION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
|
92
119
|
function isThreadRoutedSendForSelf(toolName, toolInput, selfAid) {
|
|
93
120
|
return isThreadRoutedEvolcoreSendCommand(toolName, toolInput, selfAid, (scope, threadId, target) => !!selfAid && !!resolveThreadRouteTarget(selfAid, threadId, scope, target));
|
|
94
121
|
}
|
|
122
|
+
class AsyncQuestionCancelledError extends Error {
|
|
123
|
+
}
|
|
95
124
|
export class AsyncQuestionService {
|
|
96
125
|
deps;
|
|
97
126
|
registered = new Map();
|
|
@@ -157,7 +186,9 @@ export class AsyncQuestionService {
|
|
|
157
186
|
if (!waiter)
|
|
158
187
|
return;
|
|
159
188
|
this.blockingWaiters.delete(id);
|
|
160
|
-
|
|
189
|
+
const message = `用户交互已结束(${reason})`;
|
|
190
|
+
waiter.reject(['user_cancelled', 'stop', 'explicit_cancel', 'new_message', 'recalled'].includes(reason)
|
|
191
|
+
? new AsyncQuestionCancelledError(message) : new Error(message));
|
|
161
192
|
}
|
|
162
193
|
async present(session, request, message, adapter, envelope) {
|
|
163
194
|
if (!session.selfAID || !message.peerId)
|
|
@@ -195,6 +226,8 @@ export class AsyncQuestionService {
|
|
|
195
226
|
createdAt: Date.now(),
|
|
196
227
|
...(question.blocking === true ? {} : { expiresAt: Date.now() + QUESTION_TTL_MS }),
|
|
197
228
|
blocking: question.blocking !== false,
|
|
229
|
+
...(question.blocking !== false && request.interruptedTools?.length
|
|
230
|
+
? { interruptedTools: request.interruptedTools } : {}),
|
|
198
231
|
status: 'pending',
|
|
199
232
|
};
|
|
200
233
|
if (!existing)
|
|
@@ -279,6 +312,7 @@ export class AsyncQuestionService {
|
|
|
279
312
|
&& ['submitting', 'answered', 'uncertain'].includes(record.status)
|
|
280
313
|
&& record.providerThreadId === answer.providerThreadId
|
|
281
314
|
&& record.itemId === answer.questionItemId && record.question.title === answer.question
|
|
315
|
+
&& JSON.stringify(record.interruptedTools ?? []) === JSON.stringify(answer.interruptedTools ?? [])
|
|
282
316
|
&& record.answer === answer.answer && !!(await this.validSession(record));
|
|
283
317
|
}
|
|
284
318
|
async deliver(record, adapter) {
|
|
@@ -361,6 +395,7 @@ export class AsyncQuestionService {
|
|
|
361
395
|
await this.deps.submit(current, session, {
|
|
362
396
|
requestId: current.id, providerThreadId: current.providerThreadId,
|
|
363
397
|
questionItemId: current.itemId, question: current.question.title, answer,
|
|
398
|
+
...(current.interruptedTools?.length ? { interruptedTools: current.interruptedTools } : {}),
|
|
364
399
|
});
|
|
365
400
|
current.status = 'answered';
|
|
366
401
|
this.save(current);
|
|
@@ -1117,6 +1152,35 @@ function isExpectedTerminalInterrupt(reason) {
|
|
|
1117
1152
|
export function isExpectedStreamInterrupt(terminalReason, interruptReason) {
|
|
1118
1153
|
return isExpectedTerminalInterrupt(terminalReason) || isNonErrorInterruptReason(interruptReason);
|
|
1119
1154
|
}
|
|
1155
|
+
/**
|
|
1156
|
+
* 给「打断上一轮的那一条」打中断插入标记:模板段 msg-interrupt-insert 据此只渲染一行提示,
|
|
1157
|
+
* 其余条目照常出信封。已有专属 kind(trigger / thread-context…)的条目不覆盖 kind,
|
|
1158
|
+
* 改用 interruptInsert 布尔位,两者在渲染层等价。原因随条目带下去:渲染层拿不到
|
|
1159
|
+
* interruptedSessions,模板据 interruptReason 选文案。
|
|
1160
|
+
*/
|
|
1161
|
+
export function markInterruptInsertItem(item, reason) {
|
|
1162
|
+
return item.kind
|
|
1163
|
+
? { ...item, interruptInsert: true, interruptReason: reason }
|
|
1164
|
+
: { ...item, kind: 'interrupt-insert', interruptReason: reason };
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* 把标记打在「打断上一轮的那一条」上。
|
|
1168
|
+
*
|
|
1169
|
+
* 只接受真正的对端消息:渲染列表前面可能排着 thread-context 注入、handoff 上下文、
|
|
1170
|
+
* owner 插话提示或断点恢复提示,它们不是「被插入的那条」,标记落到它们身上会指向错误的消息。
|
|
1171
|
+
* 用白名单而非排除名单,新增 kind 默认不命中。
|
|
1172
|
+
*
|
|
1173
|
+
* `interruptedByMessageId` 给出时优先按 ID 精确落点:未提交的旧输入回队后与打断者同批
|
|
1174
|
+
* (见 message-queue 的 disposeInterruptedBatch),此时第一条可标记条目是被中断的那条旧消息。
|
|
1175
|
+
*/
|
|
1176
|
+
export function markInterruptInsert(items, reason, interruptedByMessageId) {
|
|
1177
|
+
const isMarkable = (item) => (!item.kind || item.kind === 'trigger') && item.interruptInsert !== true;
|
|
1178
|
+
const byId = interruptedByMessageId
|
|
1179
|
+
? items.findIndex(item => isMarkable(item) && item.messageId === interruptedByMessageId)
|
|
1180
|
+
: -1;
|
|
1181
|
+
const idx = byId >= 0 ? byId : items.findIndex(isMarkable);
|
|
1182
|
+
return idx < 0 ? items : items.map((item, i) => (i === idx ? markInterruptInsertItem(item, reason) : item));
|
|
1183
|
+
}
|
|
1120
1184
|
export async function projectTerminalReply(projection) {
|
|
1121
1185
|
if (!projection.isCurrent() || projection.isInterrupted())
|
|
1122
1186
|
return false;
|
|
@@ -1420,6 +1484,8 @@ export class ResponseEngine {
|
|
|
1420
1484
|
/** sessionId → interruptible task-level API retry delays. */
|
|
1421
1485
|
retryDelayWaiters = new Map();
|
|
1422
1486
|
interactionRouter;
|
|
1487
|
+
connectionQuestions;
|
|
1488
|
+
connectionAttempts = new WeakMap();
|
|
1423
1489
|
asyncQuestions;
|
|
1424
1490
|
messageQueue;
|
|
1425
1491
|
taskRecoveryService;
|
|
@@ -1655,16 +1721,22 @@ export class ResponseEngine {
|
|
|
1655
1721
|
if ('sessionId' in event && event.sessionId) {
|
|
1656
1722
|
const taskId = event.taskId;
|
|
1657
1723
|
const active = this.activeTaskSpans.get(event.sessionId);
|
|
1658
|
-
if (!taskId || active?.taskId === taskId)
|
|
1724
|
+
if (!taskId || active?.taskId === taskId) {
|
|
1659
1725
|
this.activeTaskSpans.delete(event.sessionId);
|
|
1726
|
+
if (active?.workbench)
|
|
1727
|
+
notifyWorkbenchRuntimeChanged(active.workbench.selfAid);
|
|
1728
|
+
}
|
|
1660
1729
|
}
|
|
1661
1730
|
});
|
|
1662
1731
|
this.eventBus.subscribe('task:error', event => {
|
|
1663
1732
|
if ('sessionId' in event && event.sessionId) {
|
|
1664
1733
|
const taskId = event.taskId;
|
|
1665
1734
|
const active = this.activeTaskSpans.get(event.sessionId);
|
|
1666
|
-
if (!taskId || active?.taskId === taskId)
|
|
1735
|
+
if (!taskId || active?.taskId === taskId) {
|
|
1667
1736
|
this.activeTaskSpans.delete(event.sessionId);
|
|
1737
|
+
if (active?.workbench)
|
|
1738
|
+
notifyWorkbenchRuntimeChanged(active.workbench.selfAid);
|
|
1739
|
+
}
|
|
1668
1740
|
}
|
|
1669
1741
|
});
|
|
1670
1742
|
this.eventBus.subscribe('session:backend-recovery', event => {
|
|
@@ -1696,8 +1768,41 @@ export class ResponseEngine {
|
|
|
1696
1768
|
}
|
|
1697
1769
|
return controller;
|
|
1698
1770
|
}
|
|
1699
|
-
|
|
1700
|
-
|
|
1771
|
+
notifyWorkbenchSession(sessionId) {
|
|
1772
|
+
const workbench = this.activeTaskSpans.get(sessionId)?.workbench;
|
|
1773
|
+
if (workbench)
|
|
1774
|
+
notifyWorkbenchRuntimeChanged(workbench.selfAid);
|
|
1775
|
+
}
|
|
1776
|
+
/** Authoritative process-local tasks; persisted running markers are never adopted. */
|
|
1777
|
+
getWorkbenchTasks(selfAid) {
|
|
1778
|
+
return [...this.activeTaskSpans.values()].flatMap(span => {
|
|
1779
|
+
const workbench = span.workbench;
|
|
1780
|
+
if (!workbench || workbench.selfAid !== selfAid)
|
|
1781
|
+
return [];
|
|
1782
|
+
const turn = this.turnCoordinator.current(workbench.session);
|
|
1783
|
+
const active = turn.active;
|
|
1784
|
+
if (active && active.taskId !== span.taskId)
|
|
1785
|
+
return [];
|
|
1786
|
+
if (!active && turn.lastTerminal?.taskId === span.taskId)
|
|
1787
|
+
return [];
|
|
1788
|
+
return [{ ...workbench.task, state: this.isPauseRequested(workbench.session.id) ? 'paused'
|
|
1789
|
+
: active?.status === 'interrupting' ? 'interrupting'
|
|
1790
|
+
: active?.status === 'waiting_interaction' || active?.interactions.some(item => !item.settlement) ? 'waiting'
|
|
1791
|
+
: active ? 'running' : 'starting' }];
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
pauseSession(sessionId) {
|
|
1795
|
+
const changed = this.getPauseController(sessionId).requestPause();
|
|
1796
|
+
if (changed)
|
|
1797
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1798
|
+
return changed;
|
|
1799
|
+
}
|
|
1800
|
+
resumeSession(sessionId) {
|
|
1801
|
+
const changed = this.pauseControllers.get(sessionId)?.resume() ?? false;
|
|
1802
|
+
if (changed)
|
|
1803
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1804
|
+
return changed;
|
|
1805
|
+
}
|
|
1701
1806
|
isPauseRequested(sessionId) {
|
|
1702
1807
|
const controller = this.pauseControllers.get(sessionId);
|
|
1703
1808
|
return !!controller && (controller.isPauseRequested() || controller.isPaused());
|
|
@@ -1711,6 +1816,7 @@ export class ResponseEngine {
|
|
|
1711
1816
|
}
|
|
1712
1817
|
setInteractionRouter(router) {
|
|
1713
1818
|
this.interactionRouter = router;
|
|
1819
|
+
this.connectionQuestions = new ProviderConnectionQuestions(router);
|
|
1714
1820
|
this.asyncQuestions = new AsyncQuestionService({
|
|
1715
1821
|
router,
|
|
1716
1822
|
getSession: id => this.sessionManager.getSessionById(id),
|
|
@@ -1722,14 +1828,20 @@ export class ResponseEngine {
|
|
|
1722
1828
|
router.setWaitHooks({
|
|
1723
1829
|
onWaitStart: (sessionId) => {
|
|
1724
1830
|
this.activeMonitors.get(sessionId)?.pause();
|
|
1831
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1725
1832
|
},
|
|
1726
1833
|
onWaitEnd: (sessionId) => {
|
|
1727
1834
|
this.activeMonitors.get(sessionId)?.resume();
|
|
1835
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1728
1836
|
},
|
|
1729
1837
|
});
|
|
1730
1838
|
for (const { adapter } of this.channels.values())
|
|
1731
1839
|
this.restoreAsyncQuestions(adapter);
|
|
1732
1840
|
}
|
|
1841
|
+
roleQuotaNotifier;
|
|
1842
|
+
setRoleQuotaNotifier(notify) {
|
|
1843
|
+
this.roleQuotaNotifier = notify;
|
|
1844
|
+
}
|
|
1733
1845
|
/**
|
|
1734
1846
|
* 注入能力清单查询(ECK 的 hasServicePacks / hasEventPacks)。
|
|
1735
1847
|
*
|
|
@@ -2155,6 +2267,8 @@ export class ResponseEngine {
|
|
|
2155
2267
|
});
|
|
2156
2268
|
}
|
|
2157
2269
|
this.activeTaskSpans.delete(sessionId);
|
|
2270
|
+
if (taskSpan?.workbench)
|
|
2271
|
+
notifyWorkbenchRuntimeChanged(taskSpan.workbench.selfAid);
|
|
2158
2272
|
this.sessionManager.clearProcessingIfTask(sessionId, taskId);
|
|
2159
2273
|
if (this.activeTaskRuntimeContexts.get(sessionId)?.taskId === taskId) {
|
|
2160
2274
|
this.activeTaskRuntimeContexts.delete(sessionId);
|
|
@@ -2512,7 +2626,7 @@ export class ResponseEngine {
|
|
|
2512
2626
|
const active = this.activeRenderers.get(sessionId);
|
|
2513
2627
|
if (!active || active.suppressActivities)
|
|
2514
2628
|
return;
|
|
2515
|
-
void this.emitOperationalNotice(active.renderer, '
|
|
2629
|
+
void this.emitOperationalNotice(active.renderer, '会话压缩中...', 'info', 'compact-start')
|
|
2516
2630
|
.catch(error => logger.warn(`[ResponseEngine] compact-start notice send failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
2517
2631
|
}
|
|
2518
2632
|
async emitOperationalNotice(renderer, text, severity, subtype) {
|
|
@@ -2580,7 +2694,7 @@ export class ResponseEngine {
|
|
|
2580
2694
|
}
|
|
2581
2695
|
const compactResult = compacted;
|
|
2582
2696
|
if (compactResult === true || compactResult?.ok === true) {
|
|
2583
|
-
await this.emitOperationalNotice(renderer, '
|
|
2697
|
+
await this.emitOperationalNotice(renderer, '压缩完成,继续处理...', 'info', 'compact-retry');
|
|
2584
2698
|
await renderer.flush();
|
|
2585
2699
|
await beforeRunQuery?.();
|
|
2586
2700
|
const rawRetryStream = await agent.runQuery(session.id, insertMessagePromptContext(prompt, messagePromptContext), absoluteProjectPath, session.agentSessionId, undefined, effectiveSystemPrompt, this.sessionManager, recoveryModelOverride, runtimeEnv);
|
|
@@ -2788,51 +2902,15 @@ export class ResponseEngine {
|
|
|
2788
2902
|
throw new Error(`baseagent ${agent.name} does not provide a complete fullaccess execution profile`);
|
|
2789
2903
|
}
|
|
2790
2904
|
}
|
|
2791
|
-
resolveTriggerExecutionIdentity(message, selfAid) {
|
|
2905
|
+
async resolveTriggerExecutionIdentity(message, selfAid) {
|
|
2792
2906
|
if (message.source !== 'trigger' || !message.triggerMeta?.triggerId)
|
|
2793
2907
|
return undefined;
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
return undefined;
|
|
2799
|
-
const chatType = message.triggerMeta.originChatType ?? 'private';
|
|
2800
|
-
if (chatType === 'group' && !message.triggerMeta.originConversationId)
|
|
2801
|
-
return undefined;
|
|
2802
|
-
const conversationId = message.triggerMeta.originConversationId ?? actorId;
|
|
2803
|
-
const control = message.triggerMeta.originControl === true;
|
|
2804
|
-
let actor;
|
|
2805
|
-
let resolvedRole = 'none';
|
|
2806
|
-
try {
|
|
2807
|
-
const detail = resolvePeerRoleDetail({
|
|
2808
|
-
selfAid,
|
|
2809
|
-
channelKey: originChannelKey,
|
|
2810
|
-
channelType,
|
|
2811
|
-
chatType,
|
|
2812
|
-
actorId,
|
|
2813
|
-
conversationId,
|
|
2814
|
-
});
|
|
2815
|
-
actor = detail.actor;
|
|
2816
|
-
resolvedRole = detail.effectiveRole || 'none';
|
|
2817
|
-
}
|
|
2818
|
-
catch {
|
|
2819
|
-
actor = {
|
|
2820
|
-
operatorId: actorId,
|
|
2821
|
-
operatorChannelKey: originChannelKey,
|
|
2822
|
-
operatorChannelType: channelType,
|
|
2823
|
-
principalStatus: 'error',
|
|
2824
|
-
};
|
|
2908
|
+
if (selfAid) {
|
|
2909
|
+
const bound = await currentTriggerExecutionIdentity(message, selfAid);
|
|
2910
|
+
if (bound)
|
|
2911
|
+
return bound;
|
|
2825
2912
|
}
|
|
2826
|
-
return
|
|
2827
|
-
role: control ? 'owner' : resolvedRole,
|
|
2828
|
-
actor,
|
|
2829
|
-
actorId,
|
|
2830
|
-
channelType,
|
|
2831
|
-
originChannelKey,
|
|
2832
|
-
conversationId: chatType === 'group' ? conversationId : actorId,
|
|
2833
|
-
control,
|
|
2834
|
-
peerKey: formatPeerKey(channelType, chatType === 'group' ? conversationId : actorId),
|
|
2835
|
-
};
|
|
2913
|
+
return undefined;
|
|
2836
2914
|
}
|
|
2837
2915
|
resolveTaskApprovalInteractionPolicy(message) {
|
|
2838
2916
|
if (message.taskRecovery) {
|
|
@@ -3008,9 +3086,113 @@ export class ResponseEngine {
|
|
|
3008
3086
|
return content === '/s' || content === '/pair' ||
|
|
3009
3087
|
ResponseEngine.COMMAND_PREFIXES.some(cmd => content.startsWith(cmd));
|
|
3010
3088
|
}
|
|
3011
|
-
/**
|
|
3012
|
-
|
|
3013
|
-
|
|
3089
|
+
/** Keep connection facts beside the exact attempt that can fail. */
|
|
3090
|
+
captureConnectionAttempt(message, baseagent, providerId, projectPath, model) {
|
|
3091
|
+
try {
|
|
3092
|
+
const self = message.selfAID || this.agentRegistry?.resolveByChannel(message.channel)?.aid;
|
|
3093
|
+
const selected = resolveEffective({ self }, { cache: true })?.baseagents?.[baseagent];
|
|
3094
|
+
const native = !(providerId ?? selected?.provider)
|
|
3095
|
+
? resolveNativeConnectionForRepair(baseagent, selected, { agentAid: self,
|
|
3096
|
+
projectPath: projectPath ?? this.agentRegistry?.resolveByChannel(message.channel)?.projectPath }) : undefined;
|
|
3097
|
+
const context = providerConnectionContext(baseagent, providerId ?? selected?.provider, native?.baseUrl, native?.apiKey, native);
|
|
3098
|
+
if (context)
|
|
3099
|
+
this.connectionAttempts.set(message, { ...context, model: model ?? selected?.model, selectedProvider: selected?.provider,
|
|
3100
|
+
nativeRevision: native ? catalogHash([native.baseUrl, native.apiKey, native.headers, native.queryParams]) : undefined });
|
|
3101
|
+
else
|
|
3102
|
+
this.connectionAttempts.delete(message);
|
|
3103
|
+
}
|
|
3104
|
+
catch {
|
|
3105
|
+
this.connectionAttempts.delete(message);
|
|
3106
|
+
}
|
|
3107
|
+
}
|
|
3108
|
+
async askForConnection(error, message, session) {
|
|
3109
|
+
const rule = errorQuestionRule(error);
|
|
3110
|
+
const context = this.connectionAttempts.get(message);
|
|
3111
|
+
if (!rule || !context || !this.connectionQuestions
|
|
3112
|
+
|| (message.source !== undefined && !['user', 'card-trigger'].includes(message.source))
|
|
3113
|
+
|| message.chatType === 'group' || message.peerType !== 'human')
|
|
3114
|
+
return false;
|
|
3115
|
+
const info = this.resolveChannelInfo(message.channel);
|
|
3116
|
+
if (!info)
|
|
3117
|
+
return false;
|
|
3118
|
+
const currentSession = session ?? (message.boundSessionId
|
|
3119
|
+
? await this.sessionManager.getSessionById(message.boundSessionId) : undefined);
|
|
3120
|
+
if (!currentSession)
|
|
3121
|
+
return false;
|
|
3122
|
+
const self = currentSession.selfAID ?? message.selfAID;
|
|
3123
|
+
const sessionBinding = { ...currentSession, metadata: { ...currentSession.metadata } };
|
|
3124
|
+
const generation = this.turnCoordinator.current(currentSession).generation;
|
|
3125
|
+
let selectedProvider = context.selectedProvider;
|
|
3126
|
+
const binding = async () => {
|
|
3127
|
+
const live = await this.sessionManager.getSessionById(currentSession.id);
|
|
3128
|
+
const selected = resolveEffective({ self }, { cache: false })?.baseagents?.[context.baseagent];
|
|
3129
|
+
const native = context.nativeRevision && selected?.provider === undefined
|
|
3130
|
+
? resolveNativeConnectionForRepair(context.baseagent, selected, { agentAid: self,
|
|
3131
|
+
projectPath: sessionBinding.projectPath }) : undefined;
|
|
3132
|
+
return !!live && !live.deletedAt && live.selfAID === sessionBinding.selfAID
|
|
3133
|
+
&& live.baseagent === sessionBinding.baseagent && live.agentSessionId === sessionBinding.agentSessionId
|
|
3134
|
+
&& live.channel === sessionBinding.channel && live.channelId === sessionBinding.channelId
|
|
3135
|
+
&& live.projectPath === sessionBinding.projectPath && live.channelType === sessionBinding.channelType
|
|
3136
|
+
&& this.turnCoordinator.current(live).generation === generation
|
|
3137
|
+
&& sessionTopicThreadId(live) === sessionTopicThreadId(sessionBinding)
|
|
3138
|
+
&& selected?.provider === selectedProvider
|
|
3139
|
+
&& (!context.nativeRevision || selectedProvider !== undefined
|
|
3140
|
+
|| !!native && catalogHash([native.baseUrl, native.apiKey, native.headers, native.queryParams]) === context.nativeRevision);
|
|
3141
|
+
};
|
|
3142
|
+
const authorize = async () => {
|
|
3143
|
+
const subject = buildAuthSubject({ selfAid: self, actorId: message.peerId, channel: message.channel,
|
|
3144
|
+
channelType: message.channelType ?? 'aun', channelId: message.channelId, chatType: 'private',
|
|
3145
|
+
peerType: 'human', sessionId: currentSession.id });
|
|
3146
|
+
const decision = await authorizeFreshOperation({ source: 'menu', subject,
|
|
3147
|
+
intent: { operation: 'provider.connection.repair', source: 'menu', scope: 'process',
|
|
3148
|
+
args: context.providerId ? { providerId: context.providerId } : {} } });
|
|
3149
|
+
return decision.allow;
|
|
3150
|
+
};
|
|
3151
|
+
try {
|
|
3152
|
+
if (!(await binding()))
|
|
3153
|
+
return false;
|
|
3154
|
+
return await this.connectionQuestions.present({ rule, context, message, session: currentSession,
|
|
3155
|
+
adapter: info.adapter, authorize, isCurrent: binding,
|
|
3156
|
+
envelope: buildEnvelope({ channel: message.channel, channelId: message.channelId,
|
|
3157
|
+
sessionId: currentSession.id, agentName: self, delivery: { chatType: 'private' },
|
|
3158
|
+
replyContext: this.getReplyContext(message) }),
|
|
3159
|
+
verify: async (providerId, serviceType) => {
|
|
3160
|
+
clearModelCatalogCache();
|
|
3161
|
+
const connection = resolveProviderService(providerId, serviceType);
|
|
3162
|
+
// Test the exact failed model. Directory membership or a manual list proves no inference capability.
|
|
3163
|
+
if (!context.model)
|
|
3164
|
+
return false;
|
|
3165
|
+
assertProviderModelAllowed(context.model, connection);
|
|
3166
|
+
return (await probeTextModel(connection, context.model)).ok;
|
|
3167
|
+
},
|
|
3168
|
+
bindCreated: async (providerId) => {
|
|
3169
|
+
if (!self || !(await binding()))
|
|
3170
|
+
throw new Error('Connection binding changed');
|
|
3171
|
+
mutateConfig(ConfigTarget.Agent, { self }, config => {
|
|
3172
|
+
const effective = resolveEffective({ self }, { cache: false });
|
|
3173
|
+
if (effective?.baseagents?.[context.baseagent]?.provider !== selectedProvider) {
|
|
3174
|
+
throw new Error('Connection binding changed');
|
|
3175
|
+
}
|
|
3176
|
+
config.baseagents ??= {};
|
|
3177
|
+
config.baseagents[context.baseagent] = { ...config.baseagents[context.baseagent], provider: providerId };
|
|
3178
|
+
});
|
|
3179
|
+
selectedProvider = providerId;
|
|
3180
|
+
},
|
|
3181
|
+
...(this.messageQueue ? { retry: async () => {
|
|
3182
|
+
if (!(await binding()))
|
|
3183
|
+
throw new Error('Session binding changed');
|
|
3184
|
+
const { executionPermissionOverride: _permission, triggerMeta: _trigger, asyncQuestionAnswer: _answer, ...original } = message;
|
|
3185
|
+
await this.messageQueue.enqueuePersisted(currentSession.id, { ...original,
|
|
3186
|
+
source: 'card-trigger', boundSessionId: currentSession.id, messageId: `connection-retry-${crypto.randomUUID()}`,
|
|
3187
|
+
timestamp: Date.now(), receivedAt: Date.now() }, currentSession.projectPath, { interruptible: false, interruptSamePeer: false, selfAID: self, sessionKeyField: currentSession.sessionKey });
|
|
3188
|
+
} } : {}),
|
|
3189
|
+
});
|
|
3190
|
+
}
|
|
3191
|
+
catch {
|
|
3192
|
+
return false;
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
/** 处理消息(主入口)。 */
|
|
3014
3196
|
async processMessage(message) {
|
|
3015
3197
|
const fallbackFullAccessAudit = await this.resolveFullAccessAuditCandidate(message);
|
|
3016
3198
|
let outerFailureReason;
|
|
@@ -3019,6 +3201,7 @@ export class ResponseEngine {
|
|
|
3019
3201
|
}
|
|
3020
3202
|
catch (error) {
|
|
3021
3203
|
outerFailureReason = error instanceof Error ? error.message : String(error);
|
|
3204
|
+
await this.askForConnection(error, message);
|
|
3022
3205
|
if (message.source === 'owner-inject') {
|
|
3023
3206
|
this.reportObserverHintFailureForMessage(message, this.observerHintFailureCodeForError(error));
|
|
3024
3207
|
}
|
|
@@ -3131,7 +3314,7 @@ export class ResponseEngine {
|
|
|
3131
3314
|
delete message.handoffDelivery;
|
|
3132
3315
|
}
|
|
3133
3316
|
}
|
|
3134
|
-
const triggerExecutionIdentity = this.resolveTriggerExecutionIdentity(message, selfAidForAccess);
|
|
3317
|
+
const triggerExecutionIdentity = await this.resolveTriggerExecutionIdentity(message, selfAidForAccess);
|
|
3135
3318
|
const handoffExecutionIdentity = this.resolveHandoffOriginExecutionIdentity(message, selfAidForAccess);
|
|
3136
3319
|
const executionIdentity = triggerExecutionIdentity ?? handoffExecutionIdentity;
|
|
3137
3320
|
if (message.source === 'trigger' && !triggerExecutionIdentity) {
|
|
@@ -3157,11 +3340,9 @@ export class ResponseEngine {
|
|
|
3157
3340
|
this.publishTriggerExecutionFailure(message, 'trigger_identity_missing');
|
|
3158
3341
|
return;
|
|
3159
3342
|
}
|
|
3160
|
-
|
|
3161
|
-
session.identity = roleToSessionIdentity(executionIdentity.role);
|
|
3162
|
-
}
|
|
3343
|
+
// Trigger authority belongs to the run, never to the recipient's persistent session object.
|
|
3163
3344
|
// ── 角色访问控制检查:读取该用户角色的 allowAccess 配置,false 则拦截并回复权限不足 ──
|
|
3164
|
-
const userRole = session.identity?.role
|
|
3345
|
+
const userRole = executionIdentity?.role ?? session.identity?.role ?? 'none';
|
|
3165
3346
|
const isInternalHandoff = message.source === 'handoff';
|
|
3166
3347
|
const fullAccessAuditCandidate = await this.resolveFullAccessAuditCandidate(message);
|
|
3167
3348
|
const isCurrentFullAccessCommand = (fullAccessAuditCandidate?.authorization.source === 'fullaccess-command'
|
|
@@ -3173,6 +3354,7 @@ export class ResponseEngine {
|
|
|
3173
3354
|
if (!isInternalHandoff
|
|
3174
3355
|
&& !isCurrentFullAccessCommand
|
|
3175
3356
|
&& !isCurrentFullAccessTrigger
|
|
3357
|
+
&& !triggerExecutionIdentity?.control
|
|
3176
3358
|
&& !checkRoleAccess(userRole, selfAidForAccess)) {
|
|
3177
3359
|
logger.warn(`[ResponseEngine] Access denied: role=${userRole} peerKey=${message.channelId} session=${session.id}`);
|
|
3178
3360
|
const channelKey = session.metadata?.channelKey || message.channel;
|
|
@@ -3240,6 +3422,7 @@ export class ResponseEngine {
|
|
|
3240
3422
|
// 按 session.baseagent 选择 agent 后端(idle-kill 路径需要 interrupt)
|
|
3241
3423
|
let agent;
|
|
3242
3424
|
try {
|
|
3425
|
+
this.captureConnectionAttempt(message, session.baseagent, undefined, session.projectPath);
|
|
3243
3426
|
const runnerSelfAid = this.agentRegistry?.resolveByChannel(channelKey)?.aid
|
|
3244
3427
|
|| session.selfAID
|
|
3245
3428
|
|| message.selfAID;
|
|
@@ -3251,6 +3434,7 @@ export class ResponseEngine {
|
|
|
3251
3434
|
agent = loaded;
|
|
3252
3435
|
}
|
|
3253
3436
|
catch (error) {
|
|
3437
|
+
await this.askForConnection(error, message, session);
|
|
3254
3438
|
if (error instanceof BaseagentRunnerUnavailableError) {
|
|
3255
3439
|
logger.error(`[ResponseEngine] baseagent mismatch blocked: session=${session.id} channel=${channelKey} requested=${session.baseagent} owner=${error.evolagentName} available=${error.availableBaseagents.join(',') || '<none>'}`);
|
|
3256
3440
|
this.reportObserverHintFailureForMessage(message, 'RUNNER_START_FAILED');
|
|
@@ -3697,6 +3881,8 @@ export class ResponseEngine {
|
|
|
3697
3881
|
...(activityChatType === 'group' ? { groupId: activityChannelId } : {}),
|
|
3698
3882
|
...(activityChatType === 'private' ? { peerId: activityChannelId } : {}),
|
|
3699
3883
|
taskStatus: taskActivityStatus,
|
|
3884
|
+
...(sessionTopicThreadId(session) ? { threadId: sessionTopicThreadId(session) } : {}),
|
|
3885
|
+
...(taskActivityTitle(session.name) ? { title: taskActivityTitle(session.name) } : {}),
|
|
3700
3886
|
});
|
|
3701
3887
|
}
|
|
3702
3888
|
catch (error) {
|
|
@@ -3714,7 +3900,17 @@ export class ResponseEngine {
|
|
|
3714
3900
|
taskId,
|
|
3715
3901
|
messageId: message.messageId,
|
|
3716
3902
|
causation: taskCausation,
|
|
3903
|
+
...(runnerSelfAid ? { workbench: { selfAid: runnerSelfAid, session, task: {
|
|
3904
|
+
taskId, startedAt: Date.now(), state: 'starting',
|
|
3905
|
+
channel: message.channelType || session.channelType || message.channel,
|
|
3906
|
+
chatType: chatType === 'group' ? 'group' : 'private',
|
|
3907
|
+
...(chatType !== 'group' ? { peerId: message.peerId || message.channelId } : {}),
|
|
3908
|
+
...(sessionTopicThreadId(session) ? { threadId: sessionTopicThreadId(session) } : {}),
|
|
3909
|
+
...(taskActivityTitle(session.name) ? { title: taskActivityTitle(session.name) } : {}),
|
|
3910
|
+
} } } : {}),
|
|
3717
3911
|
});
|
|
3912
|
+
if (runnerSelfAid)
|
|
3913
|
+
notifyWorkbenchRuntimeChanged(runnerSelfAid);
|
|
3718
3914
|
for (const item of message.items ?? []) {
|
|
3719
3915
|
const linked = normalizeCausation(item.causation);
|
|
3720
3916
|
if (!linked || linked.spanId === inputCausation.spanId)
|
|
@@ -3765,7 +3961,7 @@ export class ResponseEngine {
|
|
|
3765
3961
|
&& message.handoffDelivery.originAuthorization.chatType === 'private') {
|
|
3766
3962
|
await prepareSameOwnerProof(selfAid, message.handoffDelivery.originAuthorization.actorId);
|
|
3767
3963
|
}
|
|
3768
|
-
const triggerExecutionIdentity = this.resolveTriggerExecutionIdentity(message, selfAid);
|
|
3964
|
+
const triggerExecutionIdentity = await this.resolveTriggerExecutionIdentity(message, selfAid);
|
|
3769
3965
|
const authorizationIdentity = triggerExecutionIdentity
|
|
3770
3966
|
?? this.resolveHandoffOriginExecutionIdentity(message, selfAid);
|
|
3771
3967
|
const approvalInteractionPolicy = this.resolveTaskApprovalInteractionPolicy(message);
|
|
@@ -3788,6 +3984,20 @@ export class ResponseEngine {
|
|
|
3788
3984
|
? formatPeerKey(configChannelType, peerKeyId)
|
|
3789
3985
|
: undefined);
|
|
3790
3986
|
const peerType = message.peerType ?? session.metadata?.peerType;
|
|
3987
|
+
// 「当前话题的对端」由**会话**决定,与「本轮是谁唤醒的」正交。
|
|
3988
|
+
// Trigger / bg 等伪对端的 peerId 表达唤醒来源(`[relation]` 段要用),
|
|
3989
|
+
// 不能拿来当信封上的话题对端——否则复查轮的信封会把自己写成对端。
|
|
3990
|
+
const topicPeer = (() => {
|
|
3991
|
+
const id = String(session.channelId ?? '').trim();
|
|
3992
|
+
if (!id || id.startsWith('trigger:') || id.startsWith('bg:')) {
|
|
3993
|
+
return { id: undefined, name: undefined, type: undefined };
|
|
3994
|
+
}
|
|
3995
|
+
return {
|
|
3996
|
+
id,
|
|
3997
|
+
name: String(session.metadata?.peerName ?? '').trim() || undefined,
|
|
3998
|
+
type: String(session.metadata?.peerType ?? '').trim() || undefined,
|
|
3999
|
+
};
|
|
4000
|
+
})();
|
|
3791
4001
|
if (configChannelType === 'aun' && configChatType === 'private') {
|
|
3792
4002
|
await prepareSameOwnerProof(selfAid, configActorId);
|
|
3793
4003
|
}
|
|
@@ -3825,7 +4035,7 @@ export class ResponseEngine {
|
|
|
3825
4035
|
?? (peerRoleDetail
|
|
3826
4036
|
? (peerRoleDetail.effectiveRole ?? 'none')
|
|
3827
4037
|
: (session.identity?.role ?? 'none'));
|
|
3828
|
-
//
|
|
4038
|
+
// 「关系角色」:群聊只认发言人本人的关系(relation-actor / agent-owner),
|
|
3829
4039
|
// 没有就降级 visitor;私聊里发言人就是对端,与 peerRole 一致。
|
|
3830
4040
|
const speakerRelation = (configChatType === 'group' && configChannelType === 'aun')
|
|
3831
4041
|
? (peerRoleDetail && (peerRoleDetail.source === 'relation-actor'
|
|
@@ -3834,6 +4044,12 @@ export class ResponseEngine {
|
|
|
3834
4044
|
? (peerRoleDetail.effectiveRole ?? 'visitor')
|
|
3835
4045
|
: (isOwnerDirectoryContact(selfAid || '', configActorId || '') ? 'member' : 'visitor'))
|
|
3836
4046
|
: peerRole;
|
|
4047
|
+
const sameOwnerQualificationResult = configChannelType === 'aun'
|
|
4048
|
+
&& configChatType === 'private'
|
|
4049
|
+
&& !!selfAid
|
|
4050
|
+
&& !!configActorId
|
|
4051
|
+
? sameOwnerQualification(selfAid, configActorId)
|
|
4052
|
+
: 'not_applicable';
|
|
3837
4053
|
let effectiveAgentConfigError;
|
|
3838
4054
|
const effectiveAgentConfig = (() => {
|
|
3839
4055
|
try {
|
|
@@ -4195,6 +4411,7 @@ export class ResponseEngine {
|
|
|
4195
4411
|
});
|
|
4196
4412
|
this.eventBus.publish({
|
|
4197
4413
|
type: 'message:received',
|
|
4414
|
+
causation: taskCausation,
|
|
4198
4415
|
sessionId: session.id,
|
|
4199
4416
|
channel: message.channel,
|
|
4200
4417
|
channelId: message.channelId,
|
|
@@ -4217,15 +4434,20 @@ export class ResponseEngine {
|
|
|
4217
4434
|
this.publishTriggerExecutionFailure(message, 'budget_exceeded');
|
|
4218
4435
|
return;
|
|
4219
4436
|
}
|
|
4220
|
-
const
|
|
4437
|
+
const roleBudgetRequest = {
|
|
4221
4438
|
selfAid: budgetAgentAid,
|
|
4222
4439
|
role: peerRole,
|
|
4223
4440
|
channelType: configChannelType,
|
|
4224
4441
|
chatType: configChatType,
|
|
4225
4442
|
channelId: configActorId || message.channelId,
|
|
4226
4443
|
peerId: configActorId || undefined,
|
|
4227
|
-
}
|
|
4444
|
+
};
|
|
4445
|
+
const roleBudgetStatus = getRoleBudgetStatus(resolveRoot(), roleBudgetRequest);
|
|
4228
4446
|
if (roleBudgetStatus.hard_blocked) {
|
|
4447
|
+
const requested = await this.roleQuotaNotifier?.(roleBudgetRequest).catch(error => {
|
|
4448
|
+
logger.warn(`[ResponseEngine] Role quota request failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
4449
|
+
return false;
|
|
4450
|
+
});
|
|
4229
4451
|
const digits = roleBudgetStatus.currency === 'USD' ? 4 : 2;
|
|
4230
4452
|
const usageText = roleBudgetStatus.limit_amount >= 0
|
|
4231
4453
|
? `${roleBudgetStatus.currency} ${roleBudgetStatus.used_amount.toFixed(digits)}/${roleBudgetStatus.limit_amount.toFixed(digits)}`
|
|
@@ -4255,7 +4477,9 @@ export class ResponseEngine {
|
|
|
4255
4477
|
this.touchAgentActivity(channelKey);
|
|
4256
4478
|
adapter.send(envelope, {
|
|
4257
4479
|
kind: 'system.error',
|
|
4258
|
-
text: budgetText
|
|
4480
|
+
text: budgetText + (requested ? budgetZh
|
|
4481
|
+
? '\n已向主机 Owner 申请额度调整,调整后请重试。'
|
|
4482
|
+
: '\nA quota adjustment has been requested from the host Owner. Retry after approval.' : ''),
|
|
4259
4483
|
subtype: 'role_budget_exceeded',
|
|
4260
4484
|
recoverable: false,
|
|
4261
4485
|
metadata: { roleBudget: roleBudgetStatus },
|
|
@@ -4284,6 +4508,13 @@ export class ResponseEngine {
|
|
|
4284
4508
|
const modelBaseagent = normalizeBaseagent(agent.name).canonical;
|
|
4285
4509
|
const configuredBaseagent = modelBaseagent === 'unknown'
|
|
4286
4510
|
? undefined : effectiveAgentConfig?.baseagents?.[modelBaseagent];
|
|
4511
|
+
// Preserve actionable connection failures before default-model discovery
|
|
4512
|
+
// intentionally folds transport diagnostics into MODEL_UNAVAILABLE.
|
|
4513
|
+
if (configuredBaseagent?.provider) {
|
|
4514
|
+
const provider = resolveProviderServiceForBaseagent(configuredBaseagent.provider, modelBaseagent);
|
|
4515
|
+
if (!provider.apiKey?.trim())
|
|
4516
|
+
throw new Error(`Provider ${provider.providerId} has no API key`);
|
|
4517
|
+
}
|
|
4287
4518
|
const triggerModel = message.triggerMeta?.modelOverride;
|
|
4288
4519
|
let agentModel;
|
|
4289
4520
|
let modelFailure;
|
|
@@ -4294,6 +4525,7 @@ export class ResponseEngine {
|
|
|
4294
4525
|
}
|
|
4295
4526
|
catch (error) {
|
|
4296
4527
|
const code = error?.code;
|
|
4528
|
+
await this.askForConnection(error, message, session);
|
|
4297
4529
|
modelFailure = isHostChinese()
|
|
4298
4530
|
? error instanceof Error ? error.message : '模型目录不可用'
|
|
4299
4531
|
: code === 'CODEX_MODEL_UNAVAILABLE'
|
|
@@ -4380,6 +4612,7 @@ export class ResponseEngine {
|
|
|
4380
4612
|
chatmode,
|
|
4381
4613
|
causation: taskCausation,
|
|
4382
4614
|
});
|
|
4615
|
+
this.notifyWorkbenchSession(session.id);
|
|
4383
4616
|
this.touchAgentActivity(channelKey);
|
|
4384
4617
|
// Upgrade the channel acknowledgement at task start, before compaction and
|
|
4385
4618
|
// runner setup, so processing feedback remains visible for the whole run.
|
|
@@ -4410,7 +4643,7 @@ export class ResponseEngine {
|
|
|
4410
4643
|
suppressActivityItems: middleOutputMode !== 'all',
|
|
4411
4644
|
suppressIntermediateText: middleOutputMode === 'none',
|
|
4412
4645
|
deferTextUntilBoundary: (message.channelType ?? session.channelType) === 'aun' && session.chatType === 'private',
|
|
4413
|
-
noopSentinel: message
|
|
4646
|
+
noopSentinel: messageNoopSentinel(message),
|
|
4414
4647
|
operationalNoticesEnabled: !isProactive && middleOutputMode !== 'none',
|
|
4415
4648
|
fileMarkerPattern: options?.fileMarkerPattern,
|
|
4416
4649
|
recordActivity: async (item, activityId) => {
|
|
@@ -4440,17 +4673,39 @@ export class ResponseEngine {
|
|
|
4440
4673
|
send: async (payload) => {
|
|
4441
4674
|
if (turnLease && !this.turnCoordinator.canPublish(turnLease)) {
|
|
4442
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
|
+
})}`);
|
|
4443
4683
|
return;
|
|
4444
4684
|
}
|
|
4445
4685
|
// proactive 模式:activity.batch 是 thought 协议内容,只发给支持 thought 的 channel
|
|
4446
4686
|
// (不支持 thought 的 channel 静默丢弃,避免降级为普通消息)
|
|
4447
4687
|
if (isProactive && payload.kind === 'activity.batch' && !adapter.capabilities?.thought) {
|
|
4448
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
|
+
})}`);
|
|
4449
4697
|
return;
|
|
4450
4698
|
}
|
|
4451
4699
|
const isCurrentlyBackground = this.isBackgroundSession(session, message.channel, message.channelId);
|
|
4452
4700
|
if (isCurrentlyBackground) {
|
|
4453
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
|
+
})}`);
|
|
4454
4709
|
return;
|
|
4455
4710
|
}
|
|
4456
4711
|
const opts = {};
|
|
@@ -4492,7 +4747,46 @@ export class ResponseEngine {
|
|
|
4492
4747
|
}
|
|
4493
4748
|
const enrichedEnvelope = withEnvelopeReplyContext(envelope, opts);
|
|
4494
4749
|
snapshot.pushOutbound(session.id, taskId, { kind: payload.kind, decision: 'sent' });
|
|
4495
|
-
|
|
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
|
+
}
|
|
4496
4790
|
},
|
|
4497
4791
|
});
|
|
4498
4792
|
this.activeRenderers.set(session.id, {
|
|
@@ -4756,6 +5050,15 @@ export class ResponseEngine {
|
|
|
4756
5050
|
chatmode: effectiveChatMode,
|
|
4757
5051
|
// 系统会话没有角色
|
|
4758
5052
|
role: systemSessionMarker ? undefined : peerRole,
|
|
5053
|
+
...(triggerExecutionIdentity ? { revalidateExecutionIdentity: async () => {
|
|
5054
|
+
const current = selfAid ? await currentTriggerExecutionIdentity(message, selfAid) : undefined;
|
|
5055
|
+
if (!current || current.role !== triggerExecutionIdentity.role
|
|
5056
|
+
|| current.rolePolicy !== triggerExecutionIdentity.rolePolicy
|
|
5057
|
+
|| current.actor.principalId !== triggerExecutionIdentity.actor.principalId) {
|
|
5058
|
+
throw new Error('Trigger execution authorization changed');
|
|
5059
|
+
}
|
|
5060
|
+
} } : {}),
|
|
5061
|
+
...(authorizationIdentity?.control ? { trustedProcessRole: 'daemon-service' } : {}),
|
|
4759
5062
|
internalContactAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
|
|
4760
5063
|
&& !!selfAid && !!configActorId && (sameOwnerQualification(selfAid, configActorId) === 'matched'
|
|
4761
5064
|
|| requiresSameOwnerProof(selfAid, configActorId)),
|
|
@@ -4822,9 +5125,11 @@ export class ResponseEngine {
|
|
|
4822
5125
|
generation: turnLease.generation,
|
|
4823
5126
|
createdAt: Date.now(),
|
|
4824
5127
|
});
|
|
5128
|
+
this.notifyWorkbenchSession(session.id);
|
|
4825
5129
|
},
|
|
4826
5130
|
onInteractionSettled: async (interactionId, settlement) => {
|
|
4827
5131
|
await this.turnCoordinator.settleInteraction(session, turnLease, interactionId, settlement);
|
|
5132
|
+
this.notifyWorkbenchSession(session.id);
|
|
4828
5133
|
},
|
|
4829
5134
|
},
|
|
4830
5135
|
permissionStateChanged: async (permissionEvent) => {
|
|
@@ -4950,11 +5255,10 @@ export class ResponseEngine {
|
|
|
4950
5255
|
const prevInterruptReason = this.interruptedSessions.get(session.id);
|
|
4951
5256
|
this.interruptedSessions.delete(session.id);
|
|
4952
5257
|
const wasInterrupted = prevInterruptReason === 'new_message' && !!session.agentSessionId;
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
: body;
|
|
5258
|
+
// 「新消息插入」提示改由消息模板渲染(kits/templates/message-fragments/interrupt-insert.md),
|
|
5259
|
+
// 只挂在被插入的那一条上,不再整段包裹 prompt。
|
|
4956
5260
|
// 先用裸文本兜底;vars 构造完成后用消息渲染层重算(见下方 effectivePrompt 重赋值)。
|
|
4957
|
-
let effectivePrompt =
|
|
5261
|
+
let effectivePrompt = message.content;
|
|
4958
5262
|
let fullAccessMessagePromptContext;
|
|
4959
5263
|
const markFullAccessPromptShown = async () => {
|
|
4960
5264
|
if (!fullAccessMessagePromptContext || fullAccessAuthorization?.source !== 'session-policy')
|
|
@@ -5078,6 +5382,9 @@ export class ResponseEngine {
|
|
|
5078
5382
|
await this.assertCurrentFullAccessExecutionAuthorization(fullAccessAuthorization, agent);
|
|
5079
5383
|
effectivePermissionMode = 'fullaccess';
|
|
5080
5384
|
}
|
|
5385
|
+
else if (authorizationIdentity?.control) {
|
|
5386
|
+
effectivePermissionMode = triggerPermissionModeOverride ?? 'bypass';
|
|
5387
|
+
}
|
|
5081
5388
|
else {
|
|
5082
5389
|
try {
|
|
5083
5390
|
effectivePermissionMode = constrainRuntimePermissionMode({
|
|
@@ -5096,6 +5403,25 @@ export class ResponseEngine {
|
|
|
5096
5403
|
// records all observe the same normalized value.
|
|
5097
5404
|
permissionContext.permissionMode = effectivePermissionMode;
|
|
5098
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
|
+
})}`);
|
|
5099
5425
|
const showFullAccessPrompt = fullAccessAuthorization?.source === 'fullaccess-command'
|
|
5100
5426
|
|| (fullAccessAuthorization?.source === 'session-policy'
|
|
5101
5427
|
&& readSessionFullAccessOverride(session)?.promptedSessionId !== session.id);
|
|
@@ -5455,21 +5781,7 @@ export class ResponseEngine {
|
|
|
5455
5781
|
// isOwner 与 ownerAid 同源(归属协议),避免名录快照滞后时把自封 Owner 的角色注入进去。
|
|
5456
5782
|
isPersonalAssistant: !!personalAssistantAid && personalAssistantAid === selfAid,
|
|
5457
5783
|
isOwner: !!protocolOwnerAid && protocolOwnerAid === selfAid,
|
|
5458
|
-
|
|
5459
|
-
// 只说"能",不说"谁关的"——默认关与显式关在结果上没区别。
|
|
5460
|
-
...(() => {
|
|
5461
|
-
if (!selfAid)
|
|
5462
|
-
return {};
|
|
5463
|
-
const state = resolveContactsState(selfAid, personalAssistantAid);
|
|
5464
|
-
const open = ['Owner', '个人助理'];
|
|
5465
|
-
if (state.internalContacts)
|
|
5466
|
-
open.push('内部联系人');
|
|
5467
|
-
if (state.externalContacts)
|
|
5468
|
-
open.push('外部联系人');
|
|
5469
|
-
if (state.strangerContacts)
|
|
5470
|
-
open.push('名录外的人');
|
|
5471
|
-
return { contactsState: `现在可联系:${open.join('、')}` };
|
|
5472
|
-
})(),
|
|
5784
|
+
contactsState: '普通出站消息可直接按 AID 发送;入站按联系人范围与许可准入',
|
|
5473
5785
|
// 记忆系统开关变量(来自 effectiveAgentConfig.memory,默认全部启用)。
|
|
5474
5786
|
// enableRelation 是总开关:relation 是所有记忆的唯一出生地。
|
|
5475
5787
|
// memory.enableRelation 在 relation-config schema 里声明了 x-merge-logic: AND,
|
|
@@ -5486,7 +5798,7 @@ export class ResponseEngine {
|
|
|
5486
5798
|
selfExttype: selfIdentity?.exttype || undefined,
|
|
5487
5799
|
// 群聊:本端在当前群的成员角色(供 [relation] 段注入「我的群角色」)。
|
|
5488
5800
|
myGroupRole: message.myGroupRole || undefined,
|
|
5489
|
-
// 本轮主发言人与本端的关系角色(供 [relation]
|
|
5801
|
+
// 本轮主发言人与本端的关系角色(供 [relation] 段与信封注入「关系角色」)。
|
|
5490
5802
|
speakerRelation,
|
|
5491
5803
|
agentMdPath: selfAid ? agentMdPath(selfAid) : undefined,
|
|
5492
5804
|
lifecycle,
|
|
@@ -5504,6 +5816,11 @@ export class ResponseEngine {
|
|
|
5504
5816
|
}
|
|
5505
5817
|
})(),
|
|
5506
5818
|
peerId: peerIdRaw || undefined,
|
|
5819
|
+
// 信封模板专用:当前话题的对端。伪对端(trigger:/bg:)时全部留空,
|
|
5820
|
+
// 模板退回 peerId 表达,不改变既有行为。
|
|
5821
|
+
...(topicPeer.id ? { topicPeerId: topicPeer.id } : {}),
|
|
5822
|
+
...(topicPeer.name ? { topicPeerName: topicPeer.name } : {}),
|
|
5823
|
+
...(topicPeer.type ? { topicPeerType: topicPeer.type } : {}),
|
|
5507
5824
|
// 与任务上下文同源:系统会话取目标关系,否则 peer-profile / relation 索引会按 bg: 伪对端注入
|
|
5508
5825
|
peerKey: systemSessionContext?.peerKey ?? peerKey,
|
|
5509
5826
|
peerName: peerName || undefined,
|
|
@@ -5547,6 +5864,9 @@ export class ResponseEngine {
|
|
|
5547
5864
|
weekday: currentWeekday(),
|
|
5548
5865
|
osInfo: OS_INFO,
|
|
5549
5866
|
threadId: sessionTopicThreadId(session),
|
|
5867
|
+
// 当前会话的**规范**话题 id:话题会话是 `thread-…`,主会话是 `main:<aidA>:<aidB>`。
|
|
5868
|
+
// `threadId` 在主会话恒为空,信封要表达「当前话题」时必须用这个。
|
|
5869
|
+
localTopicId: sessionLocalTopicId(session),
|
|
5550
5870
|
// Stage 3: sessionKey 持久化字段
|
|
5551
5871
|
sessionKey: session.sessionKey,
|
|
5552
5872
|
chatMode: effectiveChatMode,
|
|
@@ -5558,6 +5878,11 @@ export class ResponseEngine {
|
|
|
5558
5878
|
baseAgentName: normalizedBaseagent.displayName,
|
|
5559
5879
|
baseAgentModel: agentModel || undefined,
|
|
5560
5880
|
effectiveModel: effectiveModel || agentModel || undefined,
|
|
5881
|
+
// 当前实际生效的 Provider:降级候选自带 provider 时以它为准,否则用主配置值。
|
|
5882
|
+
// 与 effectiveModel 同源,避免上下文里模型与 Provider 对不上。
|
|
5883
|
+
activeProvider: (usedFallback?.provider ?? primaryProvider) || undefined,
|
|
5884
|
+
// 当前实际生效的推理强度(auto/未设置时留空,由 runner 默认值决定)。
|
|
5885
|
+
activeEffort: effectiveEffort || undefined,
|
|
5561
5886
|
modelFallbackActive: usedFallback ? true : undefined,
|
|
5562
5887
|
modelFallbackModel: usedFallback?.model,
|
|
5563
5888
|
agentSessionId: session.agentSessionId || undefined,
|
|
@@ -5604,7 +5929,7 @@ export class ResponseEngine {
|
|
|
5604
5929
|
const estTokens = (s) => s ? Math.ceil(s.length / 4) : 0;
|
|
5605
5930
|
const cbModel = effectiveModel || agentModel || 'unknown';
|
|
5606
5931
|
// 从统一模型参数表获取模型的真实 context_window
|
|
5607
|
-
const { resolveModelSpec } = await import('../../stats/
|
|
5932
|
+
const { resolveModelSpec } = await import('../../stats/model-resolver.js');
|
|
5608
5933
|
const modelSpec = resolveModelSpec(resolveRoot(), cbModel);
|
|
5609
5934
|
const cbMaxTokens = modelSpec.context_window;
|
|
5610
5935
|
const systemPromptTokens = estTokens(options?.systemPromptAppend);
|
|
@@ -5687,6 +6012,8 @@ export class ResponseEngine {
|
|
|
5687
6012
|
messageId: entry.messageId,
|
|
5688
6013
|
originThreadId: entry.originThreadId,
|
|
5689
6014
|
originPeer: entry.originPeer,
|
|
6015
|
+
...(entry.originPeerName ? { originPeerName: entry.originPeerName } : {}),
|
|
6016
|
+
...(entry.originPeerType ? { originPeerType: entry.originPeerType } : {}),
|
|
5690
6017
|
originSessionId: entry.originSessionId,
|
|
5691
6018
|
...(entry.triggerId ? { triggerId: entry.triggerId } : {}),
|
|
5692
6019
|
gapDetection: entry.gapDetection,
|
|
@@ -5731,6 +6058,8 @@ export class ResponseEngine {
|
|
|
5731
6058
|
return;
|
|
5732
6059
|
}
|
|
5733
6060
|
const renderItems = hintItems.length > 0 ? [...hintItems, ...peerItems] : peerItems;
|
|
6061
|
+
// 落点规则见 markInterruptInsert():优先按队列给出的打断者 ID,缺失时退回第一条可标记条目。
|
|
6062
|
+
const markInserted = (items, reason) => markInterruptInsert(items, reason, message.interruptedByMessageId);
|
|
5734
6063
|
const fallbackContent = (() => {
|
|
5735
6064
|
if (!message.restartResume?.submitted || peerItems.length === 0)
|
|
5736
6065
|
return message.content;
|
|
@@ -5738,6 +6067,7 @@ export class ResponseEngine {
|
|
|
5738
6067
|
if (message.restartResume.pendingInterrupted && resumeIdx >= 0 && resumeIdx < peerItems.length - 1) {
|
|
5739
6068
|
const resumeText = peerItems.slice(0, resumeIdx + 1).map(item => item.content).join('\n');
|
|
5740
6069
|
const pendingText = peerItems.slice(resumeIdx + 1).map(item => item.content).join('\n');
|
|
6070
|
+
// 裸文本兜底(模板渲染不可用)没有信封可挂,只能沿用旧的整段形态。
|
|
5741
6071
|
return `${resumeText}\n\n【新消息插入】\n\n${pendingText}\n\n【请根据前后消息酌情处理】`;
|
|
5742
6072
|
}
|
|
5743
6073
|
return peerItems.map(item => item.content).join('\n');
|
|
@@ -5747,11 +6077,12 @@ export class ResponseEngine {
|
|
|
5747
6077
|
const resumeIdx = renderItems.findIndex(item => item.kind === 'restart-resume');
|
|
5748
6078
|
if (resumeIdx >= 0 && resumeIdx < renderItems.length - 1) {
|
|
5749
6079
|
const resumeRender = renderMessageBody(renderItems.slice(0, resumeIdx + 1), messageVars, session.id);
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
5754
|
-
|
|
6080
|
+
// 断点恢复 + 新消息:标记打在恢复提示之后的那条上。
|
|
6081
|
+
// 这条路径是 daemon 重启后恢复出来的 pending 消息,原因固定为 daemon_restart
|
|
6082
|
+
// (pendingInterrupted 结构不携带原始中断原因,见 types.ts restartResume)。
|
|
6083
|
+
const pendingRender = renderMessageBody(markInserted(renderItems.slice(resumeIdx + 1), 'daemon_restart'), messageVars, session.id);
|
|
6084
|
+
const body = [resumeRender.body.trim(), pendingRender.body.trim()]
|
|
6085
|
+
.filter(Boolean).join('\n\n');
|
|
5755
6086
|
renderResult = {
|
|
5756
6087
|
body,
|
|
5757
6088
|
images: [...resumeRender.images, ...pendingRender.images],
|
|
@@ -5761,13 +6092,16 @@ export class ResponseEngine {
|
|
|
5761
6092
|
renderResult = renderMessageBody(renderItems, messageVars, session.id);
|
|
5762
6093
|
}
|
|
5763
6094
|
}
|
|
6095
|
+
else if (wasInterrupted) {
|
|
6096
|
+
renderResult = renderMessageBody(markInserted(renderItems, prevInterruptReason), messageVars, session.id);
|
|
6097
|
+
}
|
|
5764
6098
|
else {
|
|
5765
6099
|
renderResult = renderMessageBody(renderItems, messageVars, session.id);
|
|
5766
6100
|
}
|
|
5767
6101
|
if (renderResult.body.trim())
|
|
5768
|
-
effectivePrompt =
|
|
6102
|
+
effectivePrompt = renderResult.body;
|
|
5769
6103
|
else
|
|
5770
|
-
effectivePrompt =
|
|
6104
|
+
effectivePrompt = composeHintFallback(hintItems, fallbackContent);
|
|
5771
6105
|
}
|
|
5772
6106
|
catch (e) {
|
|
5773
6107
|
logger.warn(`[ResponseEngine] renderMessageBody failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
@@ -5779,7 +6113,7 @@ export class ResponseEngine {
|
|
|
5779
6113
|
}
|
|
5780
6114
|
if (message.source === 'owner-inject')
|
|
5781
6115
|
throw e;
|
|
5782
|
-
effectivePrompt =
|
|
6116
|
+
effectivePrompt = fallbackContent;
|
|
5783
6117
|
}
|
|
5784
6118
|
if (v2HandoffIds.length > 0 && renderResult?.body.trim())
|
|
5785
6119
|
handoffPromptRendered = true;
|
|
@@ -5900,6 +6234,7 @@ export class ResponseEngine {
|
|
|
5900
6234
|
// 系统会话与角色体系无关:带标记、不签角色
|
|
5901
6235
|
...(systemSessionMarker ? { systemSession: systemSessionMarker } : { issuedRole: peerRole }),
|
|
5902
6236
|
executionSource: fullAccessAuthorization?.source ?? (message.source === 'trigger' ? 'trigger' : 'user'),
|
|
6237
|
+
...(authorizationIdentity?.control ? { trustedProcessRole: 'daemon-service' } : {}),
|
|
5903
6238
|
permissionMode: effectivePermissionMode,
|
|
5904
6239
|
approvalInteractionPolicy,
|
|
5905
6240
|
...(sessionRuntimeDir ? { sessionRuntimeDir } : {}),
|
|
@@ -5931,6 +6266,7 @@ export class ResponseEngine {
|
|
|
5931
6266
|
const shouldTimeoutRetryAttempt = retryScheduler.shouldTimeoutAttempt() && apiRetryTimeoutMs !== undefined;
|
|
5932
6267
|
let attemptTimeout;
|
|
5933
6268
|
try {
|
|
6269
|
+
this.captureConnectionAttempt(message, normalizedBaseagent.canonical, modelOverride?.provider ?? primaryProvider, session.projectPath, modelOverride?.model || agentModel);
|
|
5934
6270
|
logger.debug(`[ResponseEngine] agent.runQuery start: agent=${agent.name} session=${session.id} task=${taskId} attempt=${runAttempt} apiRetries=${retryScheduler.apiRetryAttemptsMade} agentSessionId=${runAgentSessionId ?? 'none'} topicBinding=${isTopicSession(session) ? 'authoritative' : 'legacy'}`);
|
|
5935
6271
|
import('../../utils/msg-diag.js').then(m => m.diagLog('task_start', { aid: session.selfAID ?? '', msgId: message.messageId ?? '', taskId, sessionId: runAgentSessionId ?? undefined, text: message.content ?? '' })).catch(() => { });
|
|
5936
6272
|
await this.assertCurrentExecutionAuthorization(permissionContext, agent);
|
|
@@ -6076,6 +6412,7 @@ export class ResponseEngine {
|
|
|
6076
6412
|
attemptTimeout = createRetryAttemptTimeout(apiRetryTimeoutMs);
|
|
6077
6413
|
resetTimer('retry_attempt');
|
|
6078
6414
|
}
|
|
6415
|
+
const attemptTurnLease = turnLease;
|
|
6079
6416
|
const processAttempt = this.processEventStream(stream, session, agent, renderer, (eventType, toolName) => {
|
|
6080
6417
|
resetTimer(eventType, toolName);
|
|
6081
6418
|
attemptTimeout?.reset();
|
|
@@ -6086,7 +6423,7 @@ export class ResponseEngine {
|
|
|
6086
6423
|
} : undefined, taskCausation, turnLease, effectivePermissionMode, selfAid, async (request) => {
|
|
6087
6424
|
if (!this.asyncQuestions)
|
|
6088
6425
|
throw new Error('Async question service is unavailable');
|
|
6089
|
-
const blocking = request.questions.some(question => question.blocking
|
|
6426
|
+
const blocking = request.questions.some(question => question.blocking !== false);
|
|
6090
6427
|
if (permissionContext.approvalInteractionPolicy === 'deny') {
|
|
6091
6428
|
logger.info(`[AsyncQuestions] no interactive recipient for unattended task: session=${session.id}`);
|
|
6092
6429
|
if (blocking)
|
|
@@ -6098,13 +6435,20 @@ export class ResponseEngine {
|
|
|
6098
6435
|
timeoutControl?.pauseForInteraction?.();
|
|
6099
6436
|
}
|
|
6100
6437
|
try {
|
|
6101
|
-
if (blocking)
|
|
6102
|
-
await
|
|
6103
|
-
|
|
6104
|
-
|
|
6105
|
-
|
|
6438
|
+
if (blocking) {
|
|
6439
|
+
if (!(await this.turnCoordinator.markStatus(session, attemptTurnLease, 'waiting_interaction'))) {
|
|
6440
|
+
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6441
|
+
}
|
|
6442
|
+
await agent.interrupt(session.id, {
|
|
6443
|
+
taskId: attemptTurnLease.taskId,
|
|
6444
|
+
generation: attemptTurnLease.generation,
|
|
6445
|
+
});
|
|
6446
|
+
if (!this.turnCoordinator.isCurrent(attemptTurnLease))
|
|
6447
|
+
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6448
|
+
}
|
|
6106
6449
|
await renderer.flush(false);
|
|
6107
6450
|
await this.asyncQuestions.present(session, request, message, adapter, envelope);
|
|
6451
|
+
return blocking;
|
|
6108
6452
|
}
|
|
6109
6453
|
catch (error) {
|
|
6110
6454
|
if (blocking)
|
|
@@ -6121,8 +6465,7 @@ export class ResponseEngine {
|
|
|
6121
6465
|
}, async () => {
|
|
6122
6466
|
if (proactiveCircuitBreakRequested)
|
|
6123
6467
|
await interruptProactiveCircuitBreak();
|
|
6124
|
-
},
|
|
6125
|
-
? message.triggerMeta?.noopSentinel : undefined);
|
|
6468
|
+
}, !this.isTrustedDaemonTrigger(message) ? messageNoopSentinel(message) : undefined);
|
|
6126
6469
|
streamResult = attemptTimeout
|
|
6127
6470
|
? await Promise.race([processAttempt, attemptTimeout.promise])
|
|
6128
6471
|
: await processAttempt;
|
|
@@ -6189,6 +6532,10 @@ export class ResponseEngine {
|
|
|
6189
6532
|
permissionError._errorAlreadySent = true;
|
|
6190
6533
|
throw permissionError;
|
|
6191
6534
|
}
|
|
6535
|
+
// The dictionary action owns recovery even when its diagnostic type
|
|
6536
|
+
// is model_unavailable. Asking must not silently switch Providers.
|
|
6537
|
+
if (errorQuestionRule(retryError))
|
|
6538
|
+
throw retryError;
|
|
6192
6539
|
const retryWouldReplaySubmittedInput = retryAttemptTimedOut
|
|
6193
6540
|
|| isRetryableError(retryError)
|
|
6194
6541
|
|| classifyError(retryError) === ErrorType.MODEL_UNAVAILABLE;
|
|
@@ -6340,8 +6687,7 @@ export class ResponseEngine {
|
|
|
6340
6687
|
runtimeEnv,
|
|
6341
6688
|
resetTimer,
|
|
6342
6689
|
shouldSuppress,
|
|
6343
|
-
noopSentinel:
|
|
6344
|
-
? message.triggerMeta?.noopSentinel : undefined,
|
|
6690
|
+
noopSentinel: !this.isTrustedDaemonTrigger(message) ? messageNoopSentinel(message) : undefined,
|
|
6345
6691
|
proactive,
|
|
6346
6692
|
proactiveSelfAid: selfAid,
|
|
6347
6693
|
permissionMode: effectivePermissionMode,
|
|
@@ -6418,10 +6764,10 @@ export class ResponseEngine {
|
|
|
6418
6764
|
// 由响应模式插件统一处理(InteractiveMode.afterProcess / ProactiveMode.afterProcess)
|
|
6419
6765
|
const finalReplyText = streamResult.lastReplyText || streamResult.fullText;
|
|
6420
6766
|
const visibleFinalReplyText = stripContextLimitErrorLines(finalReplyText);
|
|
6421
|
-
const
|
|
6422
|
-
const isNoopReply = !!
|
|
6767
|
+
const replyNoopSentinel = messageNoopSentinel(message);
|
|
6768
|
+
const isNoopReply = !!replyNoopSentinel && !streamResult.isError
|
|
6423
6769
|
&& !isExpectedTerminalInterrupt(streamResult.terminalReason)
|
|
6424
|
-
&& isNoopText(visibleFinalReplyText,
|
|
6770
|
+
&& isNoopText(visibleFinalReplyText, replyNoopSentinel);
|
|
6425
6771
|
if (resolvedMode?.mode.afterProcess && !isNoopReply) {
|
|
6426
6772
|
const flusherText = renderer.getFinalText();
|
|
6427
6773
|
const fullText = flusherText.length >= (streamResult.fullText?.length || 0) ? flusherText : streamResult.fullText;
|
|
@@ -6559,6 +6905,9 @@ export class ResponseEngine {
|
|
|
6559
6905
|
return;
|
|
6560
6906
|
}
|
|
6561
6907
|
const terminalInterrupt = isExpectedStreamInterrupt(streamResult.terminalReason, this.interruptedSessions.get(session.id));
|
|
6908
|
+
if (streamResult.isError && !terminalInterrupt) {
|
|
6909
|
+
await this.askForConnection(new Error(streamRawErrorText || getStreamErrorText(streamResult)), message, session);
|
|
6910
|
+
}
|
|
6562
6911
|
const streamRecoverable = !permissionTerminalFailure
|
|
6563
6912
|
&& !isExpectedTerminalInterrupt(streamResult.terminalReason)
|
|
6564
6913
|
&& (isRecoverableProtocolFailure(streamResult.subtype, streamResult.protocolIncompleteReason)
|
|
@@ -6641,6 +6990,20 @@ export class ResponseEngine {
|
|
|
6641
6990
|
throw tagged;
|
|
6642
6991
|
}
|
|
6643
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
|
+
})}`);
|
|
6644
7007
|
if (!streamResult.isError && !terminalInterrupt) {
|
|
6645
7008
|
const commitDecision = await this.turnCoordinator.commit(session, turnLease, this.buildTurnCommitEvidence(session, streamResult));
|
|
6646
7009
|
if (!commitDecision.ok) {
|
|
@@ -6671,8 +7034,9 @@ export class ResponseEngine {
|
|
|
6671
7034
|
}
|
|
6672
7035
|
}
|
|
6673
7036
|
else {
|
|
6674
|
-
await this.turnCoordinator.finish(session, turnLease, terminalInterrupt ? 'cancelled' : 'failed',
|
|
6675
|
-
:
|
|
7037
|
+
await this.turnCoordinator.finish(session, turnLease, streamResult.subtype === 'awaiting_user_input' ? 'interrupted' : terminalInterrupt ? 'cancelled' : 'failed', streamResult.subtype === 'awaiting_user_input' ? 'awaiting_user_input'
|
|
7038
|
+
: permissionTerminalFailure ? 'permission_denied'
|
|
7039
|
+
: streamResult.protocolIncompleteReason || streamResult.terminalReason || streamResult.subtype, streamRecoverable);
|
|
6676
7040
|
}
|
|
6677
7041
|
// 注意:不在此处清除 interruptedSessions,由下一条消息的 prompt 包装逻辑消费
|
|
6678
7042
|
const interruptReason = this.interruptedSessions.get(session.id);
|
|
@@ -6745,8 +7109,19 @@ export class ResponseEngine {
|
|
|
6745
7109
|
if (interactionCancelled) {
|
|
6746
7110
|
await adapter.send(envelope, {
|
|
6747
7111
|
kind: 'status.interrupted',
|
|
6748
|
-
metadata: { reason: '
|
|
7112
|
+
metadata: { reason: streamResult.subtype === 'awaiting_user_input'
|
|
7113
|
+
? 'awaiting_user_input' : 'interaction_cancelled' },
|
|
6749
7114
|
}).catch(() => { });
|
|
7115
|
+
if (streamResult.subtype === 'awaiting_user_input' || streamResult.subtype === 'interaction_cancelled') {
|
|
7116
|
+
// This interruption originated here, rather than in the queue.
|
|
7117
|
+
// Publish only after durable settlement; the scoped event cannot
|
|
7118
|
+
// invalidate a newer turn or close another task's accounting.
|
|
7119
|
+
this.eventBus.publish({
|
|
7120
|
+
type: 'task:interrupted', sessionId: session.id, taskId,
|
|
7121
|
+
generation: turnLease.generation, agentAid: runnerSelfAid,
|
|
7122
|
+
reason: streamResult.subtype, causation: taskCausation,
|
|
7123
|
+
});
|
|
7124
|
+
}
|
|
6750
7125
|
}
|
|
6751
7126
|
logger.info(`[${message.channel}] Stream result error suppressed (${interactionCancelled ? 'interaction cancellation' : `user interrupt: ${interruptReason}`}): ${errorSummary}`);
|
|
6752
7127
|
logger.message({
|
|
@@ -6826,6 +7201,9 @@ export class ResponseEngine {
|
|
|
6826
7201
|
? formatPeerKey(configChannelType, configActorId)
|
|
6827
7202
|
: formatPeerKey(configChannelType, message.channelId));
|
|
6828
7203
|
const ctxPct = streamResult.contextUsage?.percentage;
|
|
7204
|
+
// 网关价格缓存(/v1/models 的 pricing/effective_pricing,1h TTL)由当前 runner 提供,
|
|
7205
|
+
// 同时携带实际连接来源,供 usage_events 记录 Provider 维度。
|
|
7206
|
+
const gwPricing = agent.getGatewayPricing?.();
|
|
6829
7207
|
const event = normalizeUsage(streamResult.tokenUsage, {
|
|
6830
7208
|
ts: Date.now(),
|
|
6831
7209
|
agent_aid: statsAgentAid,
|
|
@@ -6835,13 +7213,12 @@ export class ResponseEngine {
|
|
|
6835
7213
|
peer_type: session.chatType || undefined,
|
|
6836
7214
|
session_id: session.id,
|
|
6837
7215
|
model: statsModel,
|
|
7216
|
+
provider_id: gwPricing?.source?.providerId,
|
|
7217
|
+
base_url: gwPricing?.source?.baseUrl,
|
|
6838
7218
|
turns: streamResult.numTurns,
|
|
6839
7219
|
duration_ms: durationMs,
|
|
6840
7220
|
context_window_pct: ctxPct,
|
|
6841
7221
|
});
|
|
6842
|
-
// 写库即得价格对(原价 + 网关价),无需再调 calcCost 重复计算。
|
|
6843
|
-
// 网关价格缓存(/v1/models 的 pricing/effective_pricing,1h TTL)由当前 runner 提供。
|
|
6844
|
-
const gwPricing = agent.getGatewayPricing?.();
|
|
6845
7222
|
const prices = insertUsageEvent(resolveRoot(), event, gwPricing, streamResult.modelCalls);
|
|
6846
7223
|
turnCost = { official: prices.official, gateway: prices.gateway };
|
|
6847
7224
|
// 逐次大模型调用明细落库(model_calls 表)
|
|
@@ -6855,6 +7232,8 @@ export class ResponseEngine {
|
|
|
6855
7232
|
peer_key: statsPeerKey,
|
|
6856
7233
|
call_index: mc.call_index,
|
|
6857
7234
|
model: mc.model || statsModel,
|
|
7235
|
+
provider_id: gwPricing?.source?.providerId,
|
|
7236
|
+
base_url: gwPricing?.source?.baseUrl,
|
|
6858
7237
|
source: mc.source,
|
|
6859
7238
|
provider_thread_id: mc.providerThreadId,
|
|
6860
7239
|
request_id: mc.request_id,
|
|
@@ -6882,7 +7261,7 @@ export class ResponseEngine {
|
|
|
6882
7261
|
let sessionStats;
|
|
6883
7262
|
let modelSpec;
|
|
6884
7263
|
try {
|
|
6885
|
-
const { resolveModelSpec } = await import('../../stats/
|
|
7264
|
+
const { resolveModelSpec } = await import('../../stats/model-resolver.js');
|
|
6886
7265
|
const { querySessionSummary } = await import('../../stats/query.js');
|
|
6887
7266
|
modelSpec = resolveModelSpec(resolveRoot(), statsModel);
|
|
6888
7267
|
const sum = querySessionSummary(resolveRoot(), session.id);
|
|
@@ -7098,6 +7477,8 @@ export class ResponseEngine {
|
|
|
7098
7477
|
&& !isTotalExecutionTimeout;
|
|
7099
7478
|
const isUserInterrupt = isNonErrorInterruptReason(interruptReason) || staleSupersededTurn;
|
|
7100
7479
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
7480
|
+
if (!isUserInterrupt && ownsTimeoutTerminal)
|
|
7481
|
+
await this.askForConnection(error, message, session);
|
|
7101
7482
|
const recoverable = !isUserInterrupt && !error?._replyDeliveryFailed
|
|
7102
7483
|
&& (error === timeoutControl?.error ? timeoutControl?.recoverable === true : isRetryableError(error));
|
|
7103
7484
|
if (isUserInterrupt) {
|
|
@@ -7353,6 +7734,11 @@ export class ResponseEngine {
|
|
|
7353
7734
|
finally {
|
|
7354
7735
|
if (proactiveCircuitBreakTimer)
|
|
7355
7736
|
clearTimeout(proactiveCircuitBreakTimer);
|
|
7737
|
+
if (this.activeTaskSpans.get(session.id)?.taskId === taskId) {
|
|
7738
|
+
this.activeTaskSpans.delete(session.id);
|
|
7739
|
+
if (runnerSelfAid)
|
|
7740
|
+
notifyWorkbenchRuntimeChanged(runnerSelfAid);
|
|
7741
|
+
}
|
|
7356
7742
|
if (taskActivityStore) {
|
|
7357
7743
|
try {
|
|
7358
7744
|
taskActivityStore.updateStatus(taskId, taskActivityStatus);
|
|
@@ -7448,11 +7834,27 @@ export class ResponseEngine {
|
|
|
7448
7834
|
return;
|
|
7449
7835
|
}
|
|
7450
7836
|
const ctx = await this.readLastModelCallContextUsage(session.id, session.agentSessionId);
|
|
7451
|
-
if (!ctx
|
|
7452
|
-
|
|
7837
|
+
if (!ctx)
|
|
7838
|
+
return;
|
|
7839
|
+
const model = modelOverride?.model || agent.getModel?.();
|
|
7840
|
+
if (!model)
|
|
7841
|
+
return;
|
|
7842
|
+
let policy;
|
|
7843
|
+
try {
|
|
7844
|
+
const catalog = modelOverride?.provider
|
|
7845
|
+
? await getRunnerCatalog(agent.name, undefined, { providerId: modelOverride.provider })
|
|
7846
|
+
: await agent.getModelCatalog?.();
|
|
7847
|
+
policy = resolveCatalogAutoCompactPolicy(catalog, model);
|
|
7848
|
+
}
|
|
7849
|
+
catch (error) {
|
|
7850
|
+
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} model catalog unavailable`, error);
|
|
7453
7851
|
return;
|
|
7454
7852
|
}
|
|
7455
|
-
|
|
7853
|
+
if (!policy || ctx.totalTokens < policy.autoCompactTokens) {
|
|
7854
|
+
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} ctx=${ctx.totalTokens}/${policy?.autoCompactTokens ?? 'unknown'}`);
|
|
7855
|
+
return;
|
|
7856
|
+
}
|
|
7857
|
+
logger.info(`[ResponseEngine] Auto compact at task.start: session=${session.id} model=${model} contextWindow=${policy.contextWindow} totalTokens=${ctx.totalTokens} autoCompactTokens=${policy.autoCompactTokens}`);
|
|
7456
7858
|
await this.emitOperationalNotice(renderer, '上下文接近上限,正在压缩会话...', 'info', 'auto-compact-start');
|
|
7457
7859
|
await renderer.flush();
|
|
7458
7860
|
this.announcedCompactStarts.add(session.id);
|
|
@@ -7465,7 +7867,7 @@ export class ResponseEngine {
|
|
|
7465
7867
|
const compacted = await agent.compact(session.id, session.agentSessionId, absoluteProjectPath, modelOverride);
|
|
7466
7868
|
const compactResult = compacted;
|
|
7467
7869
|
if (compactResult === true || compactResult?.ok === true) {
|
|
7468
|
-
await this.emitOperationalNotice(renderer, '
|
|
7870
|
+
await this.emitOperationalNotice(renderer, '上下文压缩完成,继续处理...', 'info', 'auto-compact-complete');
|
|
7469
7871
|
await renderer.flush();
|
|
7470
7872
|
}
|
|
7471
7873
|
else {
|
|
@@ -7521,12 +7923,7 @@ export class ResponseEngine {
|
|
|
7521
7923
|
logger.warn(`[ResponseEngine] Ignoring implausible context_tokens: session=${sessionId} totalTokens=${totalTokens} maxTokens=${maxTokens}`);
|
|
7522
7924
|
return undefined;
|
|
7523
7925
|
}
|
|
7524
|
-
|
|
7525
|
-
// 大窗口模型(1M)到 650k 由 EvolCore 压缩;小窗口模型(200k/128k)
|
|
7526
|
-
// 到不了该阈值,交给 base agent 自身的压缩机制处理。
|
|
7527
|
-
// 历史行里可能存着旧的 350k 阈值,这里一律忽略,只认当前常量。
|
|
7528
|
-
const autoCompactTokens = autoCompactWindowForModel(model);
|
|
7529
|
-
return { totalTokens, autoCompactTokens };
|
|
7926
|
+
return { totalTokens };
|
|
7530
7927
|
}
|
|
7531
7928
|
finally {
|
|
7532
7929
|
if (shouldClose)
|
|
@@ -7633,7 +8030,7 @@ export class ResponseEngine {
|
|
|
7633
8030
|
logger.warn(`[ResponseEngine] Bound session ${boundSessionId} not found, falling back to latest`);
|
|
7634
8031
|
}
|
|
7635
8032
|
}
|
|
7636
|
-
const session = await this.sessionManager.getOrCreateSession(message.channel, message.channelId, projectPath, message.threadId, metadata, message.topicName, message.peerId, message.chatType, resolvedBaseagent, message.selfAID, message.channelType, message.peerType, resolvedIdentity, message.
|
|
8033
|
+
const session = await this.sessionManager.getOrCreateSession(message.channel, message.channelId, projectPath, message.threadId, metadata, message.topicName, message.peerId, message.chatType, resolvedBaseagent, message.selfAID, message.channelType, message.peerType, resolvedIdentity, message.topicStatus);
|
|
7637
8034
|
this.ensureSessionBaseagent(session, resolvedBaseagent);
|
|
7638
8035
|
// 群名解析:群会话首次取群显示名(group.get),缓存到 metadata,供信封渲染。
|
|
7639
8036
|
// 渠道私有方法 getGroupName 自带进程缓存 + 容错;取不到不阻塞(groupName 保持空,模板回退 groupId)。
|
|
@@ -7847,10 +8244,24 @@ export class ResponseEngine {
|
|
|
7847
8244
|
if (event.type === 'user_question') {
|
|
7848
8245
|
if (!onAsyncQuestion)
|
|
7849
8246
|
throw new Error('Async question has no delivery context');
|
|
7850
|
-
await onAsyncQuestion(
|
|
8247
|
+
const interrupted = await onAsyncQuestion({
|
|
8248
|
+
...event.request,
|
|
8249
|
+
interruptedTools: [...openToolUseIds].map(callId => ({
|
|
8250
|
+
callId,
|
|
8251
|
+
name: toolInputByCallId.get(callId)?.name ?? '工具',
|
|
8252
|
+
})),
|
|
8253
|
+
});
|
|
7851
8254
|
madeProgress = true;
|
|
7852
8255
|
// A structured question is user-visible progress without being a text reply.
|
|
7853
8256
|
textCount++;
|
|
8257
|
+
if (interrupted) {
|
|
8258
|
+
// The blocking question deliberately interrupted its provider turn.
|
|
8259
|
+
// Preserve unresolved calls for diagnosis/recovery, never commit this
|
|
8260
|
+
// partial turn or synthesize successful tool results for it.
|
|
8261
|
+
completeResult = { ...completeResult, isError: false,
|
|
8262
|
+
terminalReason: 'interrupted', subtype: 'awaiting_user_input' };
|
|
8263
|
+
return finalizeResult();
|
|
8264
|
+
}
|
|
7854
8265
|
continue;
|
|
7855
8266
|
}
|
|
7856
8267
|
if (event.type === 'input_accepted') {
|
|
@@ -7973,7 +8384,12 @@ export class ResponseEngine {
|
|
|
7973
8384
|
?? (decision === 'deny' ? 'blocked' : event.isError ? 'failed' : 'completed');
|
|
7974
8385
|
eventDetail = ` tool=${event.name} ok=${decision === 'allow' && executed}`
|
|
7975
8386
|
+ ` decision=${decision} executed=${executed} executionState=${executionState}`
|
|
7976
|
-
+ (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)}"` : '');
|
|
7977
8393
|
}
|
|
7978
8394
|
const frameworkEvents = new Set(['session_id', 'state_changed', 'status']);
|
|
7979
8395
|
if (frameworkEvents.has(event.type)) {
|
|
@@ -8220,7 +8636,7 @@ export class ResponseEngine {
|
|
|
8220
8636
|
madeProgress = true;
|
|
8221
8637
|
this.eventBus.publish({ type: 'runner:compact-complete', sessionId: session.id, preTokens: event.preTokens });
|
|
8222
8638
|
if (!shouldSuppress()) {
|
|
8223
|
-
await this.emitOperationalNotice(renderer, '
|
|
8639
|
+
await this.emitOperationalNotice(renderer, '会话压缩完成,继续执行...', 'info', 'compact');
|
|
8224
8640
|
}
|
|
8225
8641
|
}
|
|
8226
8642
|
// 子任务进度
|
|
@@ -8410,6 +8826,31 @@ export class ResponseEngine {
|
|
|
8410
8826
|
}
|
|
8411
8827
|
if (original)
|
|
8412
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
|
+
}
|
|
8413
8854
|
if (original && modeHooks?.mode?.onToolResult) {
|
|
8414
8855
|
const proactiveState = modeHooks.state.get('proactive');
|
|
8415
8856
|
await modeHooks.mode.onToolResult({
|
|
@@ -8549,6 +8990,11 @@ export class ResponseEngine {
|
|
|
8549
8990
|
}
|
|
8550
8991
|
}
|
|
8551
8992
|
catch (error) {
|
|
8993
|
+
if (error instanceof AsyncQuestionCancelledError) {
|
|
8994
|
+
completeResult = { ...completeResult, isError: false,
|
|
8995
|
+
terminalReason: 'interrupted', subtype: 'interaction_cancelled' };
|
|
8996
|
+
return finalizeResult();
|
|
8997
|
+
}
|
|
8552
8998
|
// User interrupt (AbortError) is expected, log at info level
|
|
8553
8999
|
const catchInterruptReason = this.interruptedSessions.get(session.id);
|
|
8554
9000
|
const catchIsUserInterrupt = isNonErrorInterruptReason(catchInterruptReason);
|