evolcore 0.0.47 → 0.0.48
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 +56 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +139 -39
- 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 +31 -16
- 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/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +81 -24
- 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 +7 -1
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +2 -8
- 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/provider-command.js +74 -13
- package/dist/cli/role.js +61 -17
- package/dist/cli/stats.js +3 -3
- 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-manager.js +2 -6
- 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 +59 -8
- package/dist/config/providers-management.js +467 -49
- 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 +3 -0
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +28 -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/command-handler.js +81 -85
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +61 -149
- package/dist/core/command/menu-protocol.js +7 -1
- package/dist/core/command/provider-menu.js +13 -3
- 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 +7 -7
- package/dist/core/evolagent-registry.js +14 -1
- 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 +2 -1
- package/dist/core/message/aun-ipc-sender.js +165 -55
- package/dist/core/message/im-renderer.js +1 -1
- package/dist/core/message/message-bridge.js +51 -334
- package/dist/core/message/message-log.js +5 -0
- package/dist/core/message/message-queue.js +22 -0
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +429 -116
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/ownership/owner-resolver.js +328 -50
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/relation/peer-identity.js +23 -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 +12 -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/directory/owner-directory-admission.js +1 -1
- package/dist/directory/owner-directory-cache.js +45 -28
- package/dist/directory/owner-directory-markdown.js +13 -1
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/eck/message-renderer.js +84 -24
- 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 +4 -2
- package/dist/event-center/registry.js +13 -2
- package/dist/event-center/runtime.js +103 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +92 -59
- package/dist/ipc.js +13 -2
- package/dist/outputs/events.js +62 -0
- package/dist/outputs/protocol.js +102 -0
- package/dist/outputs/service.js +279 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +89 -4
- package/dist/services/ipc-operation.js +4 -15
- package/dist/services/pack-manager.js +12 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- 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 +9 -3
- package/dist/trigger/validation.js +22 -0
- 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/msg-diag.js +1 -0
- 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 +2 -2
- package/kits/docs/evolcore/config.md +12 -0
- package/kits/docs/evolcore/directory.md +22 -3
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +123 -3
- package/kits/docs/evolcore/role.md +80 -0
- package/kits/docs/evolcore/services.md +6 -6
- 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 +10 -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/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/references/calling.md +1 -1
- 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 +221 -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/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +3 -3
- 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 +6 -5
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +4 -1
- package/scripts/agent-template/shared/common.mjs +2 -3
- package/scripts/agent-template/shared/template-contract.mjs +2 -1
- package/scripts/agent-template/shared/template-package.mjs +9 -2
- package/scripts/agent-template/shared/template-runtime.mjs +20 -5
- package/scripts/agent-template/team-pack.mjs +6 -3
- 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,7 +18,8 @@ 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';
|
|
@@ -44,7 +46,7 @@ import { recordCausationLink, recordCausationSpan } from '../causation/audit.js'
|
|
|
44
46
|
import { normalizeBaseagent, resolveBaseagentModelSelection, resolveRuntimeBaseagentModelSelection } from '../../agents/baseagent.js';
|
|
45
47
|
import { renderActionAsText } from '../interaction-router.js';
|
|
46
48
|
import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
|
|
47
|
-
import { buildEnvelope, isInteractionSendAccepted, isNoopText, replyContextFromSession, sendInteractionPayload, withEnvelopeReplyContext } from './message-utils.js';
|
|
49
|
+
import { buildEnvelope, isInteractionSendAccepted, isNoopText, messageNoopSentinel, replyContextFromSession, sendInteractionPayload, withEnvelopeReplyContext } from './message-utils.js';
|
|
48
50
|
import { chatModeForScene, isSystemOrServicePeer, resolveChatMode } from './peer-mode.js';
|
|
49
51
|
import { AGENT_DELEGATION_TOKEN_ENV } from '../auth/agent-delegation.js';
|
|
50
52
|
import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
|
|
@@ -59,12 +61,20 @@ import { constrainResolvedModelForRole, isModelAllowedForRoleBaseagent } from '.
|
|
|
59
61
|
import { eligibleFallbackModels } from '../model/model-fallback.js';
|
|
60
62
|
import { isRecoverableProtocolFailure, RetryScheduler } from './retry-scheduler.js';
|
|
61
63
|
import { assertSessionFullAccessAuthorization, constrainRuntimePermissionMode, readSessionFullAccessOverride, resolveRuntimeStringField, updateRelationSessionFullAccess } from '../role/runtime-policy.js';
|
|
62
|
-
import { resolveEffective, resolveEffectiveFieldWithSource } from '../../config/config-manager.js';
|
|
64
|
+
import { ConfigTarget, mutateConfig, resolveEffective, resolveEffectiveFieldWithSource } from '../../config/config-manager.js';
|
|
65
|
+
import { ProviderConnectionQuestions, providerConnectionContext } from '../../config/providers-management.js';
|
|
66
|
+
import { errorQuestionRule } from '../../utils/error-utils.js';
|
|
67
|
+
import { catalogHash, clearModelCatalogCache, getRunnerCatalog } from '../model/model-catalog.js';
|
|
68
|
+
import { probeTextModel } from '../invoke/executors/text.js';
|
|
69
|
+
import { assertProviderModelAllowed } from '../../config/providers-config.js';
|
|
70
|
+
import { resolveCatalogAutoCompactPolicy } from '../model/model-capabilities.js';
|
|
71
|
+
import { resolveNativeConnectionForRepair } from '../../agents/baseagent.js';
|
|
72
|
+
import { resolveProviderService, resolveProviderServiceForBaseagent } from '../../config/providers.js';
|
|
63
73
|
import { resolveAgentLifecycle } from '../../config/lifecycle.js';
|
|
64
74
|
import { authorizationConfigRevision, checkRoleAccess, getFirstStaticAgentOwner, listStaticAgentAdmins, listStaticAgentOwners, resolvePeerRoleDetail, roleToSessionIdentity, } from '../../config/peer-role-resolver.js';
|
|
65
75
|
import { insertUsageEvent, insertContextBreakdown, insertModelCalls } from '../../stats/writer.js';
|
|
66
76
|
import { normalizeUsage } from '../../stats/normalizer.js';
|
|
67
|
-
import { resolvePrices, roundCostForOutput } from '../../stats/
|
|
77
|
+
import { resolvePrices, roundCostForOutput } from '../../stats/model-resolver.js';
|
|
68
78
|
import { getBudgetStatus } from '../../stats/budget.js';
|
|
69
79
|
import { formatUsageSubjectKey, getRoleBudgetStatus } from '../../stats/role-budget.js';
|
|
70
80
|
import { snapshot } from './response-snapshot.js';
|
|
@@ -92,6 +102,8 @@ const QUESTION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
|
92
102
|
function isThreadRoutedSendForSelf(toolName, toolInput, selfAid) {
|
|
93
103
|
return isThreadRoutedEvolcoreSendCommand(toolName, toolInput, selfAid, (scope, threadId, target) => !!selfAid && !!resolveThreadRouteTarget(selfAid, threadId, scope, target));
|
|
94
104
|
}
|
|
105
|
+
class AsyncQuestionCancelledError extends Error {
|
|
106
|
+
}
|
|
95
107
|
export class AsyncQuestionService {
|
|
96
108
|
deps;
|
|
97
109
|
registered = new Map();
|
|
@@ -157,7 +169,9 @@ export class AsyncQuestionService {
|
|
|
157
169
|
if (!waiter)
|
|
158
170
|
return;
|
|
159
171
|
this.blockingWaiters.delete(id);
|
|
160
|
-
|
|
172
|
+
const message = `用户交互已结束(${reason})`;
|
|
173
|
+
waiter.reject(['user_cancelled', 'stop', 'explicit_cancel', 'new_message', 'recalled'].includes(reason)
|
|
174
|
+
? new AsyncQuestionCancelledError(message) : new Error(message));
|
|
161
175
|
}
|
|
162
176
|
async present(session, request, message, adapter, envelope) {
|
|
163
177
|
if (!session.selfAID || !message.peerId)
|
|
@@ -195,6 +209,8 @@ export class AsyncQuestionService {
|
|
|
195
209
|
createdAt: Date.now(),
|
|
196
210
|
...(question.blocking === true ? {} : { expiresAt: Date.now() + QUESTION_TTL_MS }),
|
|
197
211
|
blocking: question.blocking !== false,
|
|
212
|
+
...(question.blocking !== false && request.interruptedTools?.length
|
|
213
|
+
? { interruptedTools: request.interruptedTools } : {}),
|
|
198
214
|
status: 'pending',
|
|
199
215
|
};
|
|
200
216
|
if (!existing)
|
|
@@ -279,6 +295,7 @@ export class AsyncQuestionService {
|
|
|
279
295
|
&& ['submitting', 'answered', 'uncertain'].includes(record.status)
|
|
280
296
|
&& record.providerThreadId === answer.providerThreadId
|
|
281
297
|
&& record.itemId === answer.questionItemId && record.question.title === answer.question
|
|
298
|
+
&& JSON.stringify(record.interruptedTools ?? []) === JSON.stringify(answer.interruptedTools ?? [])
|
|
282
299
|
&& record.answer === answer.answer && !!(await this.validSession(record));
|
|
283
300
|
}
|
|
284
301
|
async deliver(record, adapter) {
|
|
@@ -361,6 +378,7 @@ export class AsyncQuestionService {
|
|
|
361
378
|
await this.deps.submit(current, session, {
|
|
362
379
|
requestId: current.id, providerThreadId: current.providerThreadId,
|
|
363
380
|
questionItemId: current.itemId, question: current.question.title, answer,
|
|
381
|
+
...(current.interruptedTools?.length ? { interruptedTools: current.interruptedTools } : {}),
|
|
364
382
|
});
|
|
365
383
|
current.status = 'answered';
|
|
366
384
|
this.save(current);
|
|
@@ -1117,6 +1135,35 @@ function isExpectedTerminalInterrupt(reason) {
|
|
|
1117
1135
|
export function isExpectedStreamInterrupt(terminalReason, interruptReason) {
|
|
1118
1136
|
return isExpectedTerminalInterrupt(terminalReason) || isNonErrorInterruptReason(interruptReason);
|
|
1119
1137
|
}
|
|
1138
|
+
/**
|
|
1139
|
+
* 给「打断上一轮的那一条」打中断插入标记:模板段 msg-interrupt-insert 据此只渲染一行提示,
|
|
1140
|
+
* 其余条目照常出信封。已有专属 kind(trigger / thread-context…)的条目不覆盖 kind,
|
|
1141
|
+
* 改用 interruptInsert 布尔位,两者在渲染层等价。原因随条目带下去:渲染层拿不到
|
|
1142
|
+
* interruptedSessions,模板据 interruptReason 选文案。
|
|
1143
|
+
*/
|
|
1144
|
+
export function markInterruptInsertItem(item, reason) {
|
|
1145
|
+
return item.kind
|
|
1146
|
+
? { ...item, interruptInsert: true, interruptReason: reason }
|
|
1147
|
+
: { ...item, kind: 'interrupt-insert', interruptReason: reason };
|
|
1148
|
+
}
|
|
1149
|
+
/**
|
|
1150
|
+
* 把标记打在「打断上一轮的那一条」上。
|
|
1151
|
+
*
|
|
1152
|
+
* 只接受真正的对端消息:渲染列表前面可能排着 thread-context 注入、handoff 上下文、
|
|
1153
|
+
* owner 插话提示或断点恢复提示,它们不是「被插入的那条」,标记落到它们身上会指向错误的消息。
|
|
1154
|
+
* 用白名单而非排除名单,新增 kind 默认不命中。
|
|
1155
|
+
*
|
|
1156
|
+
* `interruptedByMessageId` 给出时优先按 ID 精确落点:未提交的旧输入回队后与打断者同批
|
|
1157
|
+
* (见 message-queue 的 disposeInterruptedBatch),此时第一条可标记条目是被中断的那条旧消息。
|
|
1158
|
+
*/
|
|
1159
|
+
export function markInterruptInsert(items, reason, interruptedByMessageId) {
|
|
1160
|
+
const isMarkable = (item) => (!item.kind || item.kind === 'trigger') && item.interruptInsert !== true;
|
|
1161
|
+
const byId = interruptedByMessageId
|
|
1162
|
+
? items.findIndex(item => isMarkable(item) && item.messageId === interruptedByMessageId)
|
|
1163
|
+
: -1;
|
|
1164
|
+
const idx = byId >= 0 ? byId : items.findIndex(isMarkable);
|
|
1165
|
+
return idx < 0 ? items : items.map((item, i) => (i === idx ? markInterruptInsertItem(item, reason) : item));
|
|
1166
|
+
}
|
|
1120
1167
|
export async function projectTerminalReply(projection) {
|
|
1121
1168
|
if (!projection.isCurrent() || projection.isInterrupted())
|
|
1122
1169
|
return false;
|
|
@@ -1420,6 +1467,8 @@ export class ResponseEngine {
|
|
|
1420
1467
|
/** sessionId → interruptible task-level API retry delays. */
|
|
1421
1468
|
retryDelayWaiters = new Map();
|
|
1422
1469
|
interactionRouter;
|
|
1470
|
+
connectionQuestions;
|
|
1471
|
+
connectionAttempts = new WeakMap();
|
|
1423
1472
|
asyncQuestions;
|
|
1424
1473
|
messageQueue;
|
|
1425
1474
|
taskRecoveryService;
|
|
@@ -1655,16 +1704,22 @@ export class ResponseEngine {
|
|
|
1655
1704
|
if ('sessionId' in event && event.sessionId) {
|
|
1656
1705
|
const taskId = event.taskId;
|
|
1657
1706
|
const active = this.activeTaskSpans.get(event.sessionId);
|
|
1658
|
-
if (!taskId || active?.taskId === taskId)
|
|
1707
|
+
if (!taskId || active?.taskId === taskId) {
|
|
1659
1708
|
this.activeTaskSpans.delete(event.sessionId);
|
|
1709
|
+
if (active?.workbench)
|
|
1710
|
+
notifyWorkbenchRuntimeChanged(active.workbench.selfAid);
|
|
1711
|
+
}
|
|
1660
1712
|
}
|
|
1661
1713
|
});
|
|
1662
1714
|
this.eventBus.subscribe('task:error', event => {
|
|
1663
1715
|
if ('sessionId' in event && event.sessionId) {
|
|
1664
1716
|
const taskId = event.taskId;
|
|
1665
1717
|
const active = this.activeTaskSpans.get(event.sessionId);
|
|
1666
|
-
if (!taskId || active?.taskId === taskId)
|
|
1718
|
+
if (!taskId || active?.taskId === taskId) {
|
|
1667
1719
|
this.activeTaskSpans.delete(event.sessionId);
|
|
1720
|
+
if (active?.workbench)
|
|
1721
|
+
notifyWorkbenchRuntimeChanged(active.workbench.selfAid);
|
|
1722
|
+
}
|
|
1668
1723
|
}
|
|
1669
1724
|
});
|
|
1670
1725
|
this.eventBus.subscribe('session:backend-recovery', event => {
|
|
@@ -1696,8 +1751,41 @@ export class ResponseEngine {
|
|
|
1696
1751
|
}
|
|
1697
1752
|
return controller;
|
|
1698
1753
|
}
|
|
1699
|
-
|
|
1700
|
-
|
|
1754
|
+
notifyWorkbenchSession(sessionId) {
|
|
1755
|
+
const workbench = this.activeTaskSpans.get(sessionId)?.workbench;
|
|
1756
|
+
if (workbench)
|
|
1757
|
+
notifyWorkbenchRuntimeChanged(workbench.selfAid);
|
|
1758
|
+
}
|
|
1759
|
+
/** Authoritative process-local tasks; persisted running markers are never adopted. */
|
|
1760
|
+
getWorkbenchTasks(selfAid) {
|
|
1761
|
+
return [...this.activeTaskSpans.values()].flatMap(span => {
|
|
1762
|
+
const workbench = span.workbench;
|
|
1763
|
+
if (!workbench || workbench.selfAid !== selfAid)
|
|
1764
|
+
return [];
|
|
1765
|
+
const turn = this.turnCoordinator.current(workbench.session);
|
|
1766
|
+
const active = turn.active;
|
|
1767
|
+
if (active && active.taskId !== span.taskId)
|
|
1768
|
+
return [];
|
|
1769
|
+
if (!active && turn.lastTerminal?.taskId === span.taskId)
|
|
1770
|
+
return [];
|
|
1771
|
+
return [{ ...workbench.task, state: this.isPauseRequested(workbench.session.id) ? 'paused'
|
|
1772
|
+
: active?.status === 'interrupting' ? 'interrupting'
|
|
1773
|
+
: active?.status === 'waiting_interaction' || active?.interactions.some(item => !item.settlement) ? 'waiting'
|
|
1774
|
+
: active ? 'running' : 'starting' }];
|
|
1775
|
+
});
|
|
1776
|
+
}
|
|
1777
|
+
pauseSession(sessionId) {
|
|
1778
|
+
const changed = this.getPauseController(sessionId).requestPause();
|
|
1779
|
+
if (changed)
|
|
1780
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1781
|
+
return changed;
|
|
1782
|
+
}
|
|
1783
|
+
resumeSession(sessionId) {
|
|
1784
|
+
const changed = this.pauseControllers.get(sessionId)?.resume() ?? false;
|
|
1785
|
+
if (changed)
|
|
1786
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1787
|
+
return changed;
|
|
1788
|
+
}
|
|
1701
1789
|
isPauseRequested(sessionId) {
|
|
1702
1790
|
const controller = this.pauseControllers.get(sessionId);
|
|
1703
1791
|
return !!controller && (controller.isPauseRequested() || controller.isPaused());
|
|
@@ -1711,6 +1799,7 @@ export class ResponseEngine {
|
|
|
1711
1799
|
}
|
|
1712
1800
|
setInteractionRouter(router) {
|
|
1713
1801
|
this.interactionRouter = router;
|
|
1802
|
+
this.connectionQuestions = new ProviderConnectionQuestions(router);
|
|
1714
1803
|
this.asyncQuestions = new AsyncQuestionService({
|
|
1715
1804
|
router,
|
|
1716
1805
|
getSession: id => this.sessionManager.getSessionById(id),
|
|
@@ -1722,14 +1811,20 @@ export class ResponseEngine {
|
|
|
1722
1811
|
router.setWaitHooks({
|
|
1723
1812
|
onWaitStart: (sessionId) => {
|
|
1724
1813
|
this.activeMonitors.get(sessionId)?.pause();
|
|
1814
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1725
1815
|
},
|
|
1726
1816
|
onWaitEnd: (sessionId) => {
|
|
1727
1817
|
this.activeMonitors.get(sessionId)?.resume();
|
|
1818
|
+
this.notifyWorkbenchSession(sessionId);
|
|
1728
1819
|
},
|
|
1729
1820
|
});
|
|
1730
1821
|
for (const { adapter } of this.channels.values())
|
|
1731
1822
|
this.restoreAsyncQuestions(adapter);
|
|
1732
1823
|
}
|
|
1824
|
+
roleQuotaNotifier;
|
|
1825
|
+
setRoleQuotaNotifier(notify) {
|
|
1826
|
+
this.roleQuotaNotifier = notify;
|
|
1827
|
+
}
|
|
1733
1828
|
/**
|
|
1734
1829
|
* 注入能力清单查询(ECK 的 hasServicePacks / hasEventPacks)。
|
|
1735
1830
|
*
|
|
@@ -2155,6 +2250,8 @@ export class ResponseEngine {
|
|
|
2155
2250
|
});
|
|
2156
2251
|
}
|
|
2157
2252
|
this.activeTaskSpans.delete(sessionId);
|
|
2253
|
+
if (taskSpan?.workbench)
|
|
2254
|
+
notifyWorkbenchRuntimeChanged(taskSpan.workbench.selfAid);
|
|
2158
2255
|
this.sessionManager.clearProcessingIfTask(sessionId, taskId);
|
|
2159
2256
|
if (this.activeTaskRuntimeContexts.get(sessionId)?.taskId === taskId) {
|
|
2160
2257
|
this.activeTaskRuntimeContexts.delete(sessionId);
|
|
@@ -2512,7 +2609,7 @@ export class ResponseEngine {
|
|
|
2512
2609
|
const active = this.activeRenderers.get(sessionId);
|
|
2513
2610
|
if (!active || active.suppressActivities)
|
|
2514
2611
|
return;
|
|
2515
|
-
void this.emitOperationalNotice(active.renderer, '
|
|
2612
|
+
void this.emitOperationalNotice(active.renderer, '会话压缩中...', 'info', 'compact-start')
|
|
2516
2613
|
.catch(error => logger.warn(`[ResponseEngine] compact-start notice send failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
2517
2614
|
}
|
|
2518
2615
|
async emitOperationalNotice(renderer, text, severity, subtype) {
|
|
@@ -2580,7 +2677,7 @@ export class ResponseEngine {
|
|
|
2580
2677
|
}
|
|
2581
2678
|
const compactResult = compacted;
|
|
2582
2679
|
if (compactResult === true || compactResult?.ok === true) {
|
|
2583
|
-
await this.emitOperationalNotice(renderer, '
|
|
2680
|
+
await this.emitOperationalNotice(renderer, '压缩完成,继续处理...', 'info', 'compact-retry');
|
|
2584
2681
|
await renderer.flush();
|
|
2585
2682
|
await beforeRunQuery?.();
|
|
2586
2683
|
const rawRetryStream = await agent.runQuery(session.id, insertMessagePromptContext(prompt, messagePromptContext), absoluteProjectPath, session.agentSessionId, undefined, effectiveSystemPrompt, this.sessionManager, recoveryModelOverride, runtimeEnv);
|
|
@@ -2788,51 +2885,15 @@ export class ResponseEngine {
|
|
|
2788
2885
|
throw new Error(`baseagent ${agent.name} does not provide a complete fullaccess execution profile`);
|
|
2789
2886
|
}
|
|
2790
2887
|
}
|
|
2791
|
-
resolveTriggerExecutionIdentity(message, selfAid) {
|
|
2888
|
+
async resolveTriggerExecutionIdentity(message, selfAid) {
|
|
2792
2889
|
if (message.source !== 'trigger' || !message.triggerMeta?.triggerId)
|
|
2793
2890
|
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
|
-
};
|
|
2891
|
+
if (selfAid) {
|
|
2892
|
+
const bound = await currentTriggerExecutionIdentity(message, selfAid);
|
|
2893
|
+
if (bound)
|
|
2894
|
+
return bound;
|
|
2825
2895
|
}
|
|
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
|
-
};
|
|
2896
|
+
return undefined;
|
|
2836
2897
|
}
|
|
2837
2898
|
resolveTaskApprovalInteractionPolicy(message) {
|
|
2838
2899
|
if (message.taskRecovery) {
|
|
@@ -3008,9 +3069,113 @@ export class ResponseEngine {
|
|
|
3008
3069
|
return content === '/s' || content === '/pair' ||
|
|
3009
3070
|
ResponseEngine.COMMAND_PREFIXES.some(cmd => content.startsWith(cmd));
|
|
3010
3071
|
}
|
|
3011
|
-
/**
|
|
3012
|
-
|
|
3013
|
-
|
|
3072
|
+
/** Keep connection facts beside the exact attempt that can fail. */
|
|
3073
|
+
captureConnectionAttempt(message, baseagent, providerId, projectPath, model) {
|
|
3074
|
+
try {
|
|
3075
|
+
const self = message.selfAID || this.agentRegistry?.resolveByChannel(message.channel)?.aid;
|
|
3076
|
+
const selected = resolveEffective({ self }, { cache: true })?.baseagents?.[baseagent];
|
|
3077
|
+
const native = !(providerId ?? selected?.provider)
|
|
3078
|
+
? resolveNativeConnectionForRepair(baseagent, selected, { agentAid: self,
|
|
3079
|
+
projectPath: projectPath ?? this.agentRegistry?.resolveByChannel(message.channel)?.projectPath }) : undefined;
|
|
3080
|
+
const context = providerConnectionContext(baseagent, providerId ?? selected?.provider, native?.baseUrl, native?.apiKey, native);
|
|
3081
|
+
if (context)
|
|
3082
|
+
this.connectionAttempts.set(message, { ...context, model: model ?? selected?.model, selectedProvider: selected?.provider,
|
|
3083
|
+
nativeRevision: native ? catalogHash([native.baseUrl, native.apiKey, native.headers, native.queryParams]) : undefined });
|
|
3084
|
+
else
|
|
3085
|
+
this.connectionAttempts.delete(message);
|
|
3086
|
+
}
|
|
3087
|
+
catch {
|
|
3088
|
+
this.connectionAttempts.delete(message);
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
async askForConnection(error, message, session) {
|
|
3092
|
+
const rule = errorQuestionRule(error);
|
|
3093
|
+
const context = this.connectionAttempts.get(message);
|
|
3094
|
+
if (!rule || !context || !this.connectionQuestions
|
|
3095
|
+
|| (message.source !== undefined && !['user', 'card-trigger'].includes(message.source))
|
|
3096
|
+
|| message.chatType === 'group' || message.peerType !== 'human')
|
|
3097
|
+
return false;
|
|
3098
|
+
const info = this.resolveChannelInfo(message.channel);
|
|
3099
|
+
if (!info)
|
|
3100
|
+
return false;
|
|
3101
|
+
const currentSession = session ?? (message.boundSessionId
|
|
3102
|
+
? await this.sessionManager.getSessionById(message.boundSessionId) : undefined);
|
|
3103
|
+
if (!currentSession)
|
|
3104
|
+
return false;
|
|
3105
|
+
const self = currentSession.selfAID ?? message.selfAID;
|
|
3106
|
+
const sessionBinding = { ...currentSession, metadata: { ...currentSession.metadata } };
|
|
3107
|
+
const generation = this.turnCoordinator.current(currentSession).generation;
|
|
3108
|
+
let selectedProvider = context.selectedProvider;
|
|
3109
|
+
const binding = async () => {
|
|
3110
|
+
const live = await this.sessionManager.getSessionById(currentSession.id);
|
|
3111
|
+
const selected = resolveEffective({ self }, { cache: false })?.baseagents?.[context.baseagent];
|
|
3112
|
+
const native = context.nativeRevision && selected?.provider === undefined
|
|
3113
|
+
? resolveNativeConnectionForRepair(context.baseagent, selected, { agentAid: self,
|
|
3114
|
+
projectPath: sessionBinding.projectPath }) : undefined;
|
|
3115
|
+
return !!live && !live.deletedAt && live.selfAID === sessionBinding.selfAID
|
|
3116
|
+
&& live.baseagent === sessionBinding.baseagent && live.agentSessionId === sessionBinding.agentSessionId
|
|
3117
|
+
&& live.channel === sessionBinding.channel && live.channelId === sessionBinding.channelId
|
|
3118
|
+
&& live.projectPath === sessionBinding.projectPath && live.channelType === sessionBinding.channelType
|
|
3119
|
+
&& this.turnCoordinator.current(live).generation === generation
|
|
3120
|
+
&& sessionTopicThreadId(live) === sessionTopicThreadId(sessionBinding)
|
|
3121
|
+
&& selected?.provider === selectedProvider
|
|
3122
|
+
&& (!context.nativeRevision || selectedProvider !== undefined
|
|
3123
|
+
|| !!native && catalogHash([native.baseUrl, native.apiKey, native.headers, native.queryParams]) === context.nativeRevision);
|
|
3124
|
+
};
|
|
3125
|
+
const authorize = async () => {
|
|
3126
|
+
const subject = buildAuthSubject({ selfAid: self, actorId: message.peerId, channel: message.channel,
|
|
3127
|
+
channelType: message.channelType ?? 'aun', channelId: message.channelId, chatType: 'private',
|
|
3128
|
+
peerType: 'human', sessionId: currentSession.id });
|
|
3129
|
+
const decision = await authorizeFreshOperation({ source: 'menu', subject,
|
|
3130
|
+
intent: { operation: 'provider.connection.repair', source: 'menu', scope: 'process',
|
|
3131
|
+
args: context.providerId ? { providerId: context.providerId } : {} } });
|
|
3132
|
+
return decision.allow;
|
|
3133
|
+
};
|
|
3134
|
+
try {
|
|
3135
|
+
if (!(await binding()))
|
|
3136
|
+
return false;
|
|
3137
|
+
return await this.connectionQuestions.present({ rule, context, message, session: currentSession,
|
|
3138
|
+
adapter: info.adapter, authorize, isCurrent: binding,
|
|
3139
|
+
envelope: buildEnvelope({ channel: message.channel, channelId: message.channelId,
|
|
3140
|
+
sessionId: currentSession.id, agentName: self, delivery: { chatType: 'private' },
|
|
3141
|
+
replyContext: this.getReplyContext(message) }),
|
|
3142
|
+
verify: async (providerId, serviceType) => {
|
|
3143
|
+
clearModelCatalogCache();
|
|
3144
|
+
const connection = resolveProviderService(providerId, serviceType);
|
|
3145
|
+
// Test the exact failed model. Directory membership or a manual list proves no inference capability.
|
|
3146
|
+
if (!context.model)
|
|
3147
|
+
return false;
|
|
3148
|
+
assertProviderModelAllowed(context.model, connection);
|
|
3149
|
+
return (await probeTextModel(connection, context.model)).ok;
|
|
3150
|
+
},
|
|
3151
|
+
bindCreated: async (providerId) => {
|
|
3152
|
+
if (!self || !(await binding()))
|
|
3153
|
+
throw new Error('Connection binding changed');
|
|
3154
|
+
mutateConfig(ConfigTarget.Agent, { self }, config => {
|
|
3155
|
+
const effective = resolveEffective({ self }, { cache: false });
|
|
3156
|
+
if (effective?.baseagents?.[context.baseagent]?.provider !== selectedProvider) {
|
|
3157
|
+
throw new Error('Connection binding changed');
|
|
3158
|
+
}
|
|
3159
|
+
config.baseagents ??= {};
|
|
3160
|
+
config.baseagents[context.baseagent] = { ...config.baseagents[context.baseagent], provider: providerId };
|
|
3161
|
+
});
|
|
3162
|
+
selectedProvider = providerId;
|
|
3163
|
+
},
|
|
3164
|
+
...(this.messageQueue ? { retry: async () => {
|
|
3165
|
+
if (!(await binding()))
|
|
3166
|
+
throw new Error('Session binding changed');
|
|
3167
|
+
const { executionPermissionOverride: _permission, triggerMeta: _trigger, asyncQuestionAnswer: _answer, ...original } = message;
|
|
3168
|
+
await this.messageQueue.enqueuePersisted(currentSession.id, { ...original,
|
|
3169
|
+
source: 'card-trigger', boundSessionId: currentSession.id, messageId: `connection-retry-${crypto.randomUUID()}`,
|
|
3170
|
+
timestamp: Date.now(), receivedAt: Date.now() }, currentSession.projectPath, { interruptible: false, interruptSamePeer: false, selfAID: self, sessionKeyField: currentSession.sessionKey });
|
|
3171
|
+
} } : {}),
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
catch {
|
|
3175
|
+
return false;
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
/** 处理消息(主入口)。 */
|
|
3014
3179
|
async processMessage(message) {
|
|
3015
3180
|
const fallbackFullAccessAudit = await this.resolveFullAccessAuditCandidate(message);
|
|
3016
3181
|
let outerFailureReason;
|
|
@@ -3019,6 +3184,7 @@ export class ResponseEngine {
|
|
|
3019
3184
|
}
|
|
3020
3185
|
catch (error) {
|
|
3021
3186
|
outerFailureReason = error instanceof Error ? error.message : String(error);
|
|
3187
|
+
await this.askForConnection(error, message);
|
|
3022
3188
|
if (message.source === 'owner-inject') {
|
|
3023
3189
|
this.reportObserverHintFailureForMessage(message, this.observerHintFailureCodeForError(error));
|
|
3024
3190
|
}
|
|
@@ -3131,7 +3297,7 @@ export class ResponseEngine {
|
|
|
3131
3297
|
delete message.handoffDelivery;
|
|
3132
3298
|
}
|
|
3133
3299
|
}
|
|
3134
|
-
const triggerExecutionIdentity = this.resolveTriggerExecutionIdentity(message, selfAidForAccess);
|
|
3300
|
+
const triggerExecutionIdentity = await this.resolveTriggerExecutionIdentity(message, selfAidForAccess);
|
|
3135
3301
|
const handoffExecutionIdentity = this.resolveHandoffOriginExecutionIdentity(message, selfAidForAccess);
|
|
3136
3302
|
const executionIdentity = triggerExecutionIdentity ?? handoffExecutionIdentity;
|
|
3137
3303
|
if (message.source === 'trigger' && !triggerExecutionIdentity) {
|
|
@@ -3157,11 +3323,9 @@ export class ResponseEngine {
|
|
|
3157
3323
|
this.publishTriggerExecutionFailure(message, 'trigger_identity_missing');
|
|
3158
3324
|
return;
|
|
3159
3325
|
}
|
|
3160
|
-
|
|
3161
|
-
session.identity = roleToSessionIdentity(executionIdentity.role);
|
|
3162
|
-
}
|
|
3326
|
+
// Trigger authority belongs to the run, never to the recipient's persistent session object.
|
|
3163
3327
|
// ── 角色访问控制检查:读取该用户角色的 allowAccess 配置,false 则拦截并回复权限不足 ──
|
|
3164
|
-
const userRole = session.identity?.role
|
|
3328
|
+
const userRole = executionIdentity?.role ?? session.identity?.role ?? 'none';
|
|
3165
3329
|
const isInternalHandoff = message.source === 'handoff';
|
|
3166
3330
|
const fullAccessAuditCandidate = await this.resolveFullAccessAuditCandidate(message);
|
|
3167
3331
|
const isCurrentFullAccessCommand = (fullAccessAuditCandidate?.authorization.source === 'fullaccess-command'
|
|
@@ -3173,6 +3337,7 @@ export class ResponseEngine {
|
|
|
3173
3337
|
if (!isInternalHandoff
|
|
3174
3338
|
&& !isCurrentFullAccessCommand
|
|
3175
3339
|
&& !isCurrentFullAccessTrigger
|
|
3340
|
+
&& !triggerExecutionIdentity?.control
|
|
3176
3341
|
&& !checkRoleAccess(userRole, selfAidForAccess)) {
|
|
3177
3342
|
logger.warn(`[ResponseEngine] Access denied: role=${userRole} peerKey=${message.channelId} session=${session.id}`);
|
|
3178
3343
|
const channelKey = session.metadata?.channelKey || message.channel;
|
|
@@ -3240,6 +3405,7 @@ export class ResponseEngine {
|
|
|
3240
3405
|
// 按 session.baseagent 选择 agent 后端(idle-kill 路径需要 interrupt)
|
|
3241
3406
|
let agent;
|
|
3242
3407
|
try {
|
|
3408
|
+
this.captureConnectionAttempt(message, session.baseagent, undefined, session.projectPath);
|
|
3243
3409
|
const runnerSelfAid = this.agentRegistry?.resolveByChannel(channelKey)?.aid
|
|
3244
3410
|
|| session.selfAID
|
|
3245
3411
|
|| message.selfAID;
|
|
@@ -3251,6 +3417,7 @@ export class ResponseEngine {
|
|
|
3251
3417
|
agent = loaded;
|
|
3252
3418
|
}
|
|
3253
3419
|
catch (error) {
|
|
3420
|
+
await this.askForConnection(error, message, session);
|
|
3254
3421
|
if (error instanceof BaseagentRunnerUnavailableError) {
|
|
3255
3422
|
logger.error(`[ResponseEngine] baseagent mismatch blocked: session=${session.id} channel=${channelKey} requested=${session.baseagent} owner=${error.evolagentName} available=${error.availableBaseagents.join(',') || '<none>'}`);
|
|
3256
3423
|
this.reportObserverHintFailureForMessage(message, 'RUNNER_START_FAILED');
|
|
@@ -3697,6 +3864,8 @@ export class ResponseEngine {
|
|
|
3697
3864
|
...(activityChatType === 'group' ? { groupId: activityChannelId } : {}),
|
|
3698
3865
|
...(activityChatType === 'private' ? { peerId: activityChannelId } : {}),
|
|
3699
3866
|
taskStatus: taskActivityStatus,
|
|
3867
|
+
...(sessionTopicThreadId(session) ? { threadId: sessionTopicThreadId(session) } : {}),
|
|
3868
|
+
...(taskActivityTitle(session.name) ? { title: taskActivityTitle(session.name) } : {}),
|
|
3700
3869
|
});
|
|
3701
3870
|
}
|
|
3702
3871
|
catch (error) {
|
|
@@ -3714,7 +3883,17 @@ export class ResponseEngine {
|
|
|
3714
3883
|
taskId,
|
|
3715
3884
|
messageId: message.messageId,
|
|
3716
3885
|
causation: taskCausation,
|
|
3886
|
+
...(runnerSelfAid ? { workbench: { selfAid: runnerSelfAid, session, task: {
|
|
3887
|
+
taskId, startedAt: Date.now(), state: 'starting',
|
|
3888
|
+
channel: message.channelType || session.channelType || message.channel,
|
|
3889
|
+
chatType: chatType === 'group' ? 'group' : 'private',
|
|
3890
|
+
...(chatType !== 'group' ? { peerId: message.peerId || message.channelId } : {}),
|
|
3891
|
+
...(sessionTopicThreadId(session) ? { threadId: sessionTopicThreadId(session) } : {}),
|
|
3892
|
+
...(taskActivityTitle(session.name) ? { title: taskActivityTitle(session.name) } : {}),
|
|
3893
|
+
} } } : {}),
|
|
3717
3894
|
});
|
|
3895
|
+
if (runnerSelfAid)
|
|
3896
|
+
notifyWorkbenchRuntimeChanged(runnerSelfAid);
|
|
3718
3897
|
for (const item of message.items ?? []) {
|
|
3719
3898
|
const linked = normalizeCausation(item.causation);
|
|
3720
3899
|
if (!linked || linked.spanId === inputCausation.spanId)
|
|
@@ -3765,7 +3944,7 @@ export class ResponseEngine {
|
|
|
3765
3944
|
&& message.handoffDelivery.originAuthorization.chatType === 'private') {
|
|
3766
3945
|
await prepareSameOwnerProof(selfAid, message.handoffDelivery.originAuthorization.actorId);
|
|
3767
3946
|
}
|
|
3768
|
-
const triggerExecutionIdentity = this.resolveTriggerExecutionIdentity(message, selfAid);
|
|
3947
|
+
const triggerExecutionIdentity = await this.resolveTriggerExecutionIdentity(message, selfAid);
|
|
3769
3948
|
const authorizationIdentity = triggerExecutionIdentity
|
|
3770
3949
|
?? this.resolveHandoffOriginExecutionIdentity(message, selfAid);
|
|
3771
3950
|
const approvalInteractionPolicy = this.resolveTaskApprovalInteractionPolicy(message);
|
|
@@ -3788,6 +3967,20 @@ export class ResponseEngine {
|
|
|
3788
3967
|
? formatPeerKey(configChannelType, peerKeyId)
|
|
3789
3968
|
: undefined);
|
|
3790
3969
|
const peerType = message.peerType ?? session.metadata?.peerType;
|
|
3970
|
+
// 「当前话题的对端」由**会话**决定,与「本轮是谁唤醒的」正交。
|
|
3971
|
+
// Trigger / bg 等伪对端的 peerId 表达唤醒来源(`[relation]` 段要用),
|
|
3972
|
+
// 不能拿来当信封上的话题对端——否则复查轮的信封会把自己写成对端。
|
|
3973
|
+
const topicPeer = (() => {
|
|
3974
|
+
const id = String(session.channelId ?? '').trim();
|
|
3975
|
+
if (!id || id.startsWith('trigger:') || id.startsWith('bg:')) {
|
|
3976
|
+
return { id: undefined, name: undefined, type: undefined };
|
|
3977
|
+
}
|
|
3978
|
+
return {
|
|
3979
|
+
id,
|
|
3980
|
+
name: String(session.metadata?.peerName ?? '').trim() || undefined,
|
|
3981
|
+
type: String(session.metadata?.peerType ?? '').trim() || undefined,
|
|
3982
|
+
};
|
|
3983
|
+
})();
|
|
3791
3984
|
if (configChannelType === 'aun' && configChatType === 'private') {
|
|
3792
3985
|
await prepareSameOwnerProof(selfAid, configActorId);
|
|
3793
3986
|
}
|
|
@@ -3825,7 +4018,7 @@ export class ResponseEngine {
|
|
|
3825
4018
|
?? (peerRoleDetail
|
|
3826
4019
|
? (peerRoleDetail.effectiveRole ?? 'none')
|
|
3827
4020
|
: (session.identity?.role ?? 'none'));
|
|
3828
|
-
//
|
|
4021
|
+
// 「关系角色」:群聊只认发言人本人的关系(relation-actor / agent-owner),
|
|
3829
4022
|
// 没有就降级 visitor;私聊里发言人就是对端,与 peerRole 一致。
|
|
3830
4023
|
const speakerRelation = (configChatType === 'group' && configChannelType === 'aun')
|
|
3831
4024
|
? (peerRoleDetail && (peerRoleDetail.source === 'relation-actor'
|
|
@@ -4195,6 +4388,7 @@ export class ResponseEngine {
|
|
|
4195
4388
|
});
|
|
4196
4389
|
this.eventBus.publish({
|
|
4197
4390
|
type: 'message:received',
|
|
4391
|
+
causation: taskCausation,
|
|
4198
4392
|
sessionId: session.id,
|
|
4199
4393
|
channel: message.channel,
|
|
4200
4394
|
channelId: message.channelId,
|
|
@@ -4217,15 +4411,20 @@ export class ResponseEngine {
|
|
|
4217
4411
|
this.publishTriggerExecutionFailure(message, 'budget_exceeded');
|
|
4218
4412
|
return;
|
|
4219
4413
|
}
|
|
4220
|
-
const
|
|
4414
|
+
const roleBudgetRequest = {
|
|
4221
4415
|
selfAid: budgetAgentAid,
|
|
4222
4416
|
role: peerRole,
|
|
4223
4417
|
channelType: configChannelType,
|
|
4224
4418
|
chatType: configChatType,
|
|
4225
4419
|
channelId: configActorId || message.channelId,
|
|
4226
4420
|
peerId: configActorId || undefined,
|
|
4227
|
-
}
|
|
4421
|
+
};
|
|
4422
|
+
const roleBudgetStatus = getRoleBudgetStatus(resolveRoot(), roleBudgetRequest);
|
|
4228
4423
|
if (roleBudgetStatus.hard_blocked) {
|
|
4424
|
+
const requested = await this.roleQuotaNotifier?.(roleBudgetRequest).catch(error => {
|
|
4425
|
+
logger.warn(`[ResponseEngine] Role quota request failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
4426
|
+
return false;
|
|
4427
|
+
});
|
|
4229
4428
|
const digits = roleBudgetStatus.currency === 'USD' ? 4 : 2;
|
|
4230
4429
|
const usageText = roleBudgetStatus.limit_amount >= 0
|
|
4231
4430
|
? `${roleBudgetStatus.currency} ${roleBudgetStatus.used_amount.toFixed(digits)}/${roleBudgetStatus.limit_amount.toFixed(digits)}`
|
|
@@ -4255,7 +4454,9 @@ export class ResponseEngine {
|
|
|
4255
4454
|
this.touchAgentActivity(channelKey);
|
|
4256
4455
|
adapter.send(envelope, {
|
|
4257
4456
|
kind: 'system.error',
|
|
4258
|
-
text: budgetText
|
|
4457
|
+
text: budgetText + (requested ? budgetZh
|
|
4458
|
+
? '\n已向主机 Owner 申请额度调整,调整后请重试。'
|
|
4459
|
+
: '\nA quota adjustment has been requested from the host Owner. Retry after approval.' : ''),
|
|
4259
4460
|
subtype: 'role_budget_exceeded',
|
|
4260
4461
|
recoverable: false,
|
|
4261
4462
|
metadata: { roleBudget: roleBudgetStatus },
|
|
@@ -4284,6 +4485,13 @@ export class ResponseEngine {
|
|
|
4284
4485
|
const modelBaseagent = normalizeBaseagent(agent.name).canonical;
|
|
4285
4486
|
const configuredBaseagent = modelBaseagent === 'unknown'
|
|
4286
4487
|
? undefined : effectiveAgentConfig?.baseagents?.[modelBaseagent];
|
|
4488
|
+
// Preserve actionable connection failures before default-model discovery
|
|
4489
|
+
// intentionally folds transport diagnostics into MODEL_UNAVAILABLE.
|
|
4490
|
+
if (configuredBaseagent?.provider) {
|
|
4491
|
+
const provider = resolveProviderServiceForBaseagent(configuredBaseagent.provider, modelBaseagent);
|
|
4492
|
+
if (!provider.apiKey?.trim())
|
|
4493
|
+
throw new Error(`Provider ${provider.providerId} has no API key`);
|
|
4494
|
+
}
|
|
4287
4495
|
const triggerModel = message.triggerMeta?.modelOverride;
|
|
4288
4496
|
let agentModel;
|
|
4289
4497
|
let modelFailure;
|
|
@@ -4294,6 +4502,7 @@ export class ResponseEngine {
|
|
|
4294
4502
|
}
|
|
4295
4503
|
catch (error) {
|
|
4296
4504
|
const code = error?.code;
|
|
4505
|
+
await this.askForConnection(error, message, session);
|
|
4297
4506
|
modelFailure = isHostChinese()
|
|
4298
4507
|
? error instanceof Error ? error.message : '模型目录不可用'
|
|
4299
4508
|
: code === 'CODEX_MODEL_UNAVAILABLE'
|
|
@@ -4380,6 +4589,7 @@ export class ResponseEngine {
|
|
|
4380
4589
|
chatmode,
|
|
4381
4590
|
causation: taskCausation,
|
|
4382
4591
|
});
|
|
4592
|
+
this.notifyWorkbenchSession(session.id);
|
|
4383
4593
|
this.touchAgentActivity(channelKey);
|
|
4384
4594
|
// Upgrade the channel acknowledgement at task start, before compaction and
|
|
4385
4595
|
// runner setup, so processing feedback remains visible for the whole run.
|
|
@@ -4410,7 +4620,7 @@ export class ResponseEngine {
|
|
|
4410
4620
|
suppressActivityItems: middleOutputMode !== 'all',
|
|
4411
4621
|
suppressIntermediateText: middleOutputMode === 'none',
|
|
4412
4622
|
deferTextUntilBoundary: (message.channelType ?? session.channelType) === 'aun' && session.chatType === 'private',
|
|
4413
|
-
noopSentinel: message
|
|
4623
|
+
noopSentinel: messageNoopSentinel(message),
|
|
4414
4624
|
operationalNoticesEnabled: !isProactive && middleOutputMode !== 'none',
|
|
4415
4625
|
fileMarkerPattern: options?.fileMarkerPattern,
|
|
4416
4626
|
recordActivity: async (item, activityId) => {
|
|
@@ -4756,6 +4966,15 @@ export class ResponseEngine {
|
|
|
4756
4966
|
chatmode: effectiveChatMode,
|
|
4757
4967
|
// 系统会话没有角色
|
|
4758
4968
|
role: systemSessionMarker ? undefined : peerRole,
|
|
4969
|
+
...(triggerExecutionIdentity ? { revalidateExecutionIdentity: async () => {
|
|
4970
|
+
const current = selfAid ? await currentTriggerExecutionIdentity(message, selfAid) : undefined;
|
|
4971
|
+
if (!current || current.role !== triggerExecutionIdentity.role
|
|
4972
|
+
|| current.rolePolicy !== triggerExecutionIdentity.rolePolicy
|
|
4973
|
+
|| current.actor.principalId !== triggerExecutionIdentity.actor.principalId) {
|
|
4974
|
+
throw new Error('Trigger execution authorization changed');
|
|
4975
|
+
}
|
|
4976
|
+
} } : {}),
|
|
4977
|
+
...(authorizationIdentity?.control ? { trustedProcessRole: 'daemon-service' } : {}),
|
|
4759
4978
|
internalContactAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
|
|
4760
4979
|
&& !!selfAid && !!configActorId && (sameOwnerQualification(selfAid, configActorId) === 'matched'
|
|
4761
4980
|
|| requiresSameOwnerProof(selfAid, configActorId)),
|
|
@@ -4822,9 +5041,11 @@ export class ResponseEngine {
|
|
|
4822
5041
|
generation: turnLease.generation,
|
|
4823
5042
|
createdAt: Date.now(),
|
|
4824
5043
|
});
|
|
5044
|
+
this.notifyWorkbenchSession(session.id);
|
|
4825
5045
|
},
|
|
4826
5046
|
onInteractionSettled: async (interactionId, settlement) => {
|
|
4827
5047
|
await this.turnCoordinator.settleInteraction(session, turnLease, interactionId, settlement);
|
|
5048
|
+
this.notifyWorkbenchSession(session.id);
|
|
4828
5049
|
},
|
|
4829
5050
|
},
|
|
4830
5051
|
permissionStateChanged: async (permissionEvent) => {
|
|
@@ -4950,11 +5171,10 @@ export class ResponseEngine {
|
|
|
4950
5171
|
const prevInterruptReason = this.interruptedSessions.get(session.id);
|
|
4951
5172
|
this.interruptedSessions.delete(session.id);
|
|
4952
5173
|
const wasInterrupted = prevInterruptReason === 'new_message' && !!session.agentSessionId;
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
: body;
|
|
5174
|
+
// 「新消息插入」提示改由消息模板渲染(kits/templates/message-fragments/interrupt-insert.md),
|
|
5175
|
+
// 只挂在被插入的那一条上,不再整段包裹 prompt。
|
|
4956
5176
|
// 先用裸文本兜底;vars 构造完成后用消息渲染层重算(见下方 effectivePrompt 重赋值)。
|
|
4957
|
-
let effectivePrompt =
|
|
5177
|
+
let effectivePrompt = message.content;
|
|
4958
5178
|
let fullAccessMessagePromptContext;
|
|
4959
5179
|
const markFullAccessPromptShown = async () => {
|
|
4960
5180
|
if (!fullAccessMessagePromptContext || fullAccessAuthorization?.source !== 'session-policy')
|
|
@@ -5078,6 +5298,9 @@ export class ResponseEngine {
|
|
|
5078
5298
|
await this.assertCurrentFullAccessExecutionAuthorization(fullAccessAuthorization, agent);
|
|
5079
5299
|
effectivePermissionMode = 'fullaccess';
|
|
5080
5300
|
}
|
|
5301
|
+
else if (authorizationIdentity?.control) {
|
|
5302
|
+
effectivePermissionMode = triggerPermissionModeOverride ?? 'bypass';
|
|
5303
|
+
}
|
|
5081
5304
|
else {
|
|
5082
5305
|
try {
|
|
5083
5306
|
effectivePermissionMode = constrainRuntimePermissionMode({
|
|
@@ -5486,7 +5709,7 @@ export class ResponseEngine {
|
|
|
5486
5709
|
selfExttype: selfIdentity?.exttype || undefined,
|
|
5487
5710
|
// 群聊:本端在当前群的成员角色(供 [relation] 段注入「我的群角色」)。
|
|
5488
5711
|
myGroupRole: message.myGroupRole || undefined,
|
|
5489
|
-
// 本轮主发言人与本端的关系角色(供 [relation]
|
|
5712
|
+
// 本轮主发言人与本端的关系角色(供 [relation] 段与信封注入「关系角色」)。
|
|
5490
5713
|
speakerRelation,
|
|
5491
5714
|
agentMdPath: selfAid ? agentMdPath(selfAid) : undefined,
|
|
5492
5715
|
lifecycle,
|
|
@@ -5504,6 +5727,11 @@ export class ResponseEngine {
|
|
|
5504
5727
|
}
|
|
5505
5728
|
})(),
|
|
5506
5729
|
peerId: peerIdRaw || undefined,
|
|
5730
|
+
// 信封模板专用:当前话题的对端。伪对端(trigger:/bg:)时全部留空,
|
|
5731
|
+
// 模板退回 peerId 表达,不改变既有行为。
|
|
5732
|
+
...(topicPeer.id ? { topicPeerId: topicPeer.id } : {}),
|
|
5733
|
+
...(topicPeer.name ? { topicPeerName: topicPeer.name } : {}),
|
|
5734
|
+
...(topicPeer.type ? { topicPeerType: topicPeer.type } : {}),
|
|
5507
5735
|
// 与任务上下文同源:系统会话取目标关系,否则 peer-profile / relation 索引会按 bg: 伪对端注入
|
|
5508
5736
|
peerKey: systemSessionContext?.peerKey ?? peerKey,
|
|
5509
5737
|
peerName: peerName || undefined,
|
|
@@ -5547,6 +5775,9 @@ export class ResponseEngine {
|
|
|
5547
5775
|
weekday: currentWeekday(),
|
|
5548
5776
|
osInfo: OS_INFO,
|
|
5549
5777
|
threadId: sessionTopicThreadId(session),
|
|
5778
|
+
// 当前会话的**规范**话题 id:话题会话是 `thread-…`,主会话是 `main:<aidA>:<aidB>`。
|
|
5779
|
+
// `threadId` 在主会话恒为空,信封要表达「当前话题」时必须用这个。
|
|
5780
|
+
localTopicId: sessionLocalTopicId(session),
|
|
5550
5781
|
// Stage 3: sessionKey 持久化字段
|
|
5551
5782
|
sessionKey: session.sessionKey,
|
|
5552
5783
|
chatMode: effectiveChatMode,
|
|
@@ -5558,6 +5789,11 @@ export class ResponseEngine {
|
|
|
5558
5789
|
baseAgentName: normalizedBaseagent.displayName,
|
|
5559
5790
|
baseAgentModel: agentModel || undefined,
|
|
5560
5791
|
effectiveModel: effectiveModel || agentModel || undefined,
|
|
5792
|
+
// 当前实际生效的 Provider:降级候选自带 provider 时以它为准,否则用主配置值。
|
|
5793
|
+
// 与 effectiveModel 同源,避免上下文里模型与 Provider 对不上。
|
|
5794
|
+
activeProvider: (usedFallback?.provider ?? primaryProvider) || undefined,
|
|
5795
|
+
// 当前实际生效的推理强度(auto/未设置时留空,由 runner 默认值决定)。
|
|
5796
|
+
activeEffort: effectiveEffort || undefined,
|
|
5561
5797
|
modelFallbackActive: usedFallback ? true : undefined,
|
|
5562
5798
|
modelFallbackModel: usedFallback?.model,
|
|
5563
5799
|
agentSessionId: session.agentSessionId || undefined,
|
|
@@ -5604,7 +5840,7 @@ export class ResponseEngine {
|
|
|
5604
5840
|
const estTokens = (s) => s ? Math.ceil(s.length / 4) : 0;
|
|
5605
5841
|
const cbModel = effectiveModel || agentModel || 'unknown';
|
|
5606
5842
|
// 从统一模型参数表获取模型的真实 context_window
|
|
5607
|
-
const { resolveModelSpec } = await import('../../stats/
|
|
5843
|
+
const { resolveModelSpec } = await import('../../stats/model-resolver.js');
|
|
5608
5844
|
const modelSpec = resolveModelSpec(resolveRoot(), cbModel);
|
|
5609
5845
|
const cbMaxTokens = modelSpec.context_window;
|
|
5610
5846
|
const systemPromptTokens = estTokens(options?.systemPromptAppend);
|
|
@@ -5687,6 +5923,8 @@ export class ResponseEngine {
|
|
|
5687
5923
|
messageId: entry.messageId,
|
|
5688
5924
|
originThreadId: entry.originThreadId,
|
|
5689
5925
|
originPeer: entry.originPeer,
|
|
5926
|
+
...(entry.originPeerName ? { originPeerName: entry.originPeerName } : {}),
|
|
5927
|
+
...(entry.originPeerType ? { originPeerType: entry.originPeerType } : {}),
|
|
5690
5928
|
originSessionId: entry.originSessionId,
|
|
5691
5929
|
...(entry.triggerId ? { triggerId: entry.triggerId } : {}),
|
|
5692
5930
|
gapDetection: entry.gapDetection,
|
|
@@ -5731,6 +5969,8 @@ export class ResponseEngine {
|
|
|
5731
5969
|
return;
|
|
5732
5970
|
}
|
|
5733
5971
|
const renderItems = hintItems.length > 0 ? [...hintItems, ...peerItems] : peerItems;
|
|
5972
|
+
// 落点规则见 markInterruptInsert():优先按队列给出的打断者 ID,缺失时退回第一条可标记条目。
|
|
5973
|
+
const markInserted = (items, reason) => markInterruptInsert(items, reason, message.interruptedByMessageId);
|
|
5734
5974
|
const fallbackContent = (() => {
|
|
5735
5975
|
if (!message.restartResume?.submitted || peerItems.length === 0)
|
|
5736
5976
|
return message.content;
|
|
@@ -5738,6 +5978,7 @@ export class ResponseEngine {
|
|
|
5738
5978
|
if (message.restartResume.pendingInterrupted && resumeIdx >= 0 && resumeIdx < peerItems.length - 1) {
|
|
5739
5979
|
const resumeText = peerItems.slice(0, resumeIdx + 1).map(item => item.content).join('\n');
|
|
5740
5980
|
const pendingText = peerItems.slice(resumeIdx + 1).map(item => item.content).join('\n');
|
|
5981
|
+
// 裸文本兜底(模板渲染不可用)没有信封可挂,只能沿用旧的整段形态。
|
|
5741
5982
|
return `${resumeText}\n\n【新消息插入】\n\n${pendingText}\n\n【请根据前后消息酌情处理】`;
|
|
5742
5983
|
}
|
|
5743
5984
|
return peerItems.map(item => item.content).join('\n');
|
|
@@ -5747,11 +5988,12 @@ export class ResponseEngine {
|
|
|
5747
5988
|
const resumeIdx = renderItems.findIndex(item => item.kind === 'restart-resume');
|
|
5748
5989
|
if (resumeIdx >= 0 && resumeIdx < renderItems.length - 1) {
|
|
5749
5990
|
const resumeRender = renderMessageBody(renderItems.slice(0, resumeIdx + 1), messageVars, session.id);
|
|
5750
|
-
|
|
5751
|
-
|
|
5752
|
-
|
|
5753
|
-
|
|
5754
|
-
|
|
5991
|
+
// 断点恢复 + 新消息:标记打在恢复提示之后的那条上。
|
|
5992
|
+
// 这条路径是 daemon 重启后恢复出来的 pending 消息,原因固定为 daemon_restart
|
|
5993
|
+
// (pendingInterrupted 结构不携带原始中断原因,见 types.ts restartResume)。
|
|
5994
|
+
const pendingRender = renderMessageBody(markInserted(renderItems.slice(resumeIdx + 1), 'daemon_restart'), messageVars, session.id);
|
|
5995
|
+
const body = [resumeRender.body.trim(), pendingRender.body.trim()]
|
|
5996
|
+
.filter(Boolean).join('\n\n');
|
|
5755
5997
|
renderResult = {
|
|
5756
5998
|
body,
|
|
5757
5999
|
images: [...resumeRender.images, ...pendingRender.images],
|
|
@@ -5761,13 +6003,16 @@ export class ResponseEngine {
|
|
|
5761
6003
|
renderResult = renderMessageBody(renderItems, messageVars, session.id);
|
|
5762
6004
|
}
|
|
5763
6005
|
}
|
|
6006
|
+
else if (wasInterrupted) {
|
|
6007
|
+
renderResult = renderMessageBody(markInserted(renderItems, prevInterruptReason), messageVars, session.id);
|
|
6008
|
+
}
|
|
5764
6009
|
else {
|
|
5765
6010
|
renderResult = renderMessageBody(renderItems, messageVars, session.id);
|
|
5766
6011
|
}
|
|
5767
6012
|
if (renderResult.body.trim())
|
|
5768
|
-
effectivePrompt =
|
|
6013
|
+
effectivePrompt = renderResult.body;
|
|
5769
6014
|
else
|
|
5770
|
-
effectivePrompt =
|
|
6015
|
+
effectivePrompt = composeHintFallback(hintItems, fallbackContent);
|
|
5771
6016
|
}
|
|
5772
6017
|
catch (e) {
|
|
5773
6018
|
logger.warn(`[ResponseEngine] renderMessageBody failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
@@ -5779,7 +6024,7 @@ export class ResponseEngine {
|
|
|
5779
6024
|
}
|
|
5780
6025
|
if (message.source === 'owner-inject')
|
|
5781
6026
|
throw e;
|
|
5782
|
-
effectivePrompt =
|
|
6027
|
+
effectivePrompt = fallbackContent;
|
|
5783
6028
|
}
|
|
5784
6029
|
if (v2HandoffIds.length > 0 && renderResult?.body.trim())
|
|
5785
6030
|
handoffPromptRendered = true;
|
|
@@ -5900,6 +6145,7 @@ export class ResponseEngine {
|
|
|
5900
6145
|
// 系统会话与角色体系无关:带标记、不签角色
|
|
5901
6146
|
...(systemSessionMarker ? { systemSession: systemSessionMarker } : { issuedRole: peerRole }),
|
|
5902
6147
|
executionSource: fullAccessAuthorization?.source ?? (message.source === 'trigger' ? 'trigger' : 'user'),
|
|
6148
|
+
...(authorizationIdentity?.control ? { trustedProcessRole: 'daemon-service' } : {}),
|
|
5903
6149
|
permissionMode: effectivePermissionMode,
|
|
5904
6150
|
approvalInteractionPolicy,
|
|
5905
6151
|
...(sessionRuntimeDir ? { sessionRuntimeDir } : {}),
|
|
@@ -5931,6 +6177,7 @@ export class ResponseEngine {
|
|
|
5931
6177
|
const shouldTimeoutRetryAttempt = retryScheduler.shouldTimeoutAttempt() && apiRetryTimeoutMs !== undefined;
|
|
5932
6178
|
let attemptTimeout;
|
|
5933
6179
|
try {
|
|
6180
|
+
this.captureConnectionAttempt(message, normalizedBaseagent.canonical, modelOverride?.provider ?? primaryProvider, session.projectPath, modelOverride?.model || agentModel);
|
|
5934
6181
|
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
6182
|
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
6183
|
await this.assertCurrentExecutionAuthorization(permissionContext, agent);
|
|
@@ -6076,6 +6323,7 @@ export class ResponseEngine {
|
|
|
6076
6323
|
attemptTimeout = createRetryAttemptTimeout(apiRetryTimeoutMs);
|
|
6077
6324
|
resetTimer('retry_attempt');
|
|
6078
6325
|
}
|
|
6326
|
+
const attemptTurnLease = turnLease;
|
|
6079
6327
|
const processAttempt = this.processEventStream(stream, session, agent, renderer, (eventType, toolName) => {
|
|
6080
6328
|
resetTimer(eventType, toolName);
|
|
6081
6329
|
attemptTimeout?.reset();
|
|
@@ -6086,7 +6334,7 @@ export class ResponseEngine {
|
|
|
6086
6334
|
} : undefined, taskCausation, turnLease, effectivePermissionMode, selfAid, async (request) => {
|
|
6087
6335
|
if (!this.asyncQuestions)
|
|
6088
6336
|
throw new Error('Async question service is unavailable');
|
|
6089
|
-
const blocking = request.questions.some(question => question.blocking
|
|
6337
|
+
const blocking = request.questions.some(question => question.blocking !== false);
|
|
6090
6338
|
if (permissionContext.approvalInteractionPolicy === 'deny') {
|
|
6091
6339
|
logger.info(`[AsyncQuestions] no interactive recipient for unattended task: session=${session.id}`);
|
|
6092
6340
|
if (blocking)
|
|
@@ -6098,13 +6346,20 @@ export class ResponseEngine {
|
|
|
6098
6346
|
timeoutControl?.pauseForInteraction?.();
|
|
6099
6347
|
}
|
|
6100
6348
|
try {
|
|
6101
|
-
if (blocking)
|
|
6102
|
-
await
|
|
6103
|
-
|
|
6104
|
-
|
|
6105
|
-
|
|
6349
|
+
if (blocking) {
|
|
6350
|
+
if (!(await this.turnCoordinator.markStatus(session, attemptTurnLease, 'waiting_interaction'))) {
|
|
6351
|
+
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6352
|
+
}
|
|
6353
|
+
await agent.interrupt(session.id, {
|
|
6354
|
+
taskId: attemptTurnLease.taskId,
|
|
6355
|
+
generation: attemptTurnLease.generation,
|
|
6356
|
+
});
|
|
6357
|
+
if (!this.turnCoordinator.isCurrent(attemptTurnLease))
|
|
6358
|
+
throw new Error('RUNNER_START_SUPERSEDED');
|
|
6359
|
+
}
|
|
6106
6360
|
await renderer.flush(false);
|
|
6107
6361
|
await this.asyncQuestions.present(session, request, message, adapter, envelope);
|
|
6362
|
+
return blocking;
|
|
6108
6363
|
}
|
|
6109
6364
|
catch (error) {
|
|
6110
6365
|
if (blocking)
|
|
@@ -6121,8 +6376,7 @@ export class ResponseEngine {
|
|
|
6121
6376
|
}, async () => {
|
|
6122
6377
|
if (proactiveCircuitBreakRequested)
|
|
6123
6378
|
await interruptProactiveCircuitBreak();
|
|
6124
|
-
},
|
|
6125
|
-
? message.triggerMeta?.noopSentinel : undefined);
|
|
6379
|
+
}, !this.isTrustedDaemonTrigger(message) ? messageNoopSentinel(message) : undefined);
|
|
6126
6380
|
streamResult = attemptTimeout
|
|
6127
6381
|
? await Promise.race([processAttempt, attemptTimeout.promise])
|
|
6128
6382
|
: await processAttempt;
|
|
@@ -6189,6 +6443,10 @@ export class ResponseEngine {
|
|
|
6189
6443
|
permissionError._errorAlreadySent = true;
|
|
6190
6444
|
throw permissionError;
|
|
6191
6445
|
}
|
|
6446
|
+
// The dictionary action owns recovery even when its diagnostic type
|
|
6447
|
+
// is model_unavailable. Asking must not silently switch Providers.
|
|
6448
|
+
if (errorQuestionRule(retryError))
|
|
6449
|
+
throw retryError;
|
|
6192
6450
|
const retryWouldReplaySubmittedInput = retryAttemptTimedOut
|
|
6193
6451
|
|| isRetryableError(retryError)
|
|
6194
6452
|
|| classifyError(retryError) === ErrorType.MODEL_UNAVAILABLE;
|
|
@@ -6340,8 +6598,7 @@ export class ResponseEngine {
|
|
|
6340
6598
|
runtimeEnv,
|
|
6341
6599
|
resetTimer,
|
|
6342
6600
|
shouldSuppress,
|
|
6343
|
-
noopSentinel:
|
|
6344
|
-
? message.triggerMeta?.noopSentinel : undefined,
|
|
6601
|
+
noopSentinel: !this.isTrustedDaemonTrigger(message) ? messageNoopSentinel(message) : undefined,
|
|
6345
6602
|
proactive,
|
|
6346
6603
|
proactiveSelfAid: selfAid,
|
|
6347
6604
|
permissionMode: effectivePermissionMode,
|
|
@@ -6418,10 +6675,10 @@ export class ResponseEngine {
|
|
|
6418
6675
|
// 由响应模式插件统一处理(InteractiveMode.afterProcess / ProactiveMode.afterProcess)
|
|
6419
6676
|
const finalReplyText = streamResult.lastReplyText || streamResult.fullText;
|
|
6420
6677
|
const visibleFinalReplyText = stripContextLimitErrorLines(finalReplyText);
|
|
6421
|
-
const
|
|
6422
|
-
const isNoopReply = !!
|
|
6678
|
+
const replyNoopSentinel = messageNoopSentinel(message);
|
|
6679
|
+
const isNoopReply = !!replyNoopSentinel && !streamResult.isError
|
|
6423
6680
|
&& !isExpectedTerminalInterrupt(streamResult.terminalReason)
|
|
6424
|
-
&& isNoopText(visibleFinalReplyText,
|
|
6681
|
+
&& isNoopText(visibleFinalReplyText, replyNoopSentinel);
|
|
6425
6682
|
if (resolvedMode?.mode.afterProcess && !isNoopReply) {
|
|
6426
6683
|
const flusherText = renderer.getFinalText();
|
|
6427
6684
|
const fullText = flusherText.length >= (streamResult.fullText?.length || 0) ? flusherText : streamResult.fullText;
|
|
@@ -6559,6 +6816,9 @@ export class ResponseEngine {
|
|
|
6559
6816
|
return;
|
|
6560
6817
|
}
|
|
6561
6818
|
const terminalInterrupt = isExpectedStreamInterrupt(streamResult.terminalReason, this.interruptedSessions.get(session.id));
|
|
6819
|
+
if (streamResult.isError && !terminalInterrupt) {
|
|
6820
|
+
await this.askForConnection(new Error(streamRawErrorText || getStreamErrorText(streamResult)), message, session);
|
|
6821
|
+
}
|
|
6562
6822
|
const streamRecoverable = !permissionTerminalFailure
|
|
6563
6823
|
&& !isExpectedTerminalInterrupt(streamResult.terminalReason)
|
|
6564
6824
|
&& (isRecoverableProtocolFailure(streamResult.subtype, streamResult.protocolIncompleteReason)
|
|
@@ -6671,8 +6931,9 @@ export class ResponseEngine {
|
|
|
6671
6931
|
}
|
|
6672
6932
|
}
|
|
6673
6933
|
else {
|
|
6674
|
-
await this.turnCoordinator.finish(session, turnLease, terminalInterrupt ? 'cancelled' : 'failed',
|
|
6675
|
-
:
|
|
6934
|
+
await this.turnCoordinator.finish(session, turnLease, streamResult.subtype === 'awaiting_user_input' ? 'interrupted' : terminalInterrupt ? 'cancelled' : 'failed', streamResult.subtype === 'awaiting_user_input' ? 'awaiting_user_input'
|
|
6935
|
+
: permissionTerminalFailure ? 'permission_denied'
|
|
6936
|
+
: streamResult.protocolIncompleteReason || streamResult.terminalReason || streamResult.subtype, streamRecoverable);
|
|
6676
6937
|
}
|
|
6677
6938
|
// 注意:不在此处清除 interruptedSessions,由下一条消息的 prompt 包装逻辑消费
|
|
6678
6939
|
const interruptReason = this.interruptedSessions.get(session.id);
|
|
@@ -6745,8 +7006,19 @@ export class ResponseEngine {
|
|
|
6745
7006
|
if (interactionCancelled) {
|
|
6746
7007
|
await adapter.send(envelope, {
|
|
6747
7008
|
kind: 'status.interrupted',
|
|
6748
|
-
metadata: { reason: '
|
|
7009
|
+
metadata: { reason: streamResult.subtype === 'awaiting_user_input'
|
|
7010
|
+
? 'awaiting_user_input' : 'interaction_cancelled' },
|
|
6749
7011
|
}).catch(() => { });
|
|
7012
|
+
if (streamResult.subtype === 'awaiting_user_input' || streamResult.subtype === 'interaction_cancelled') {
|
|
7013
|
+
// This interruption originated here, rather than in the queue.
|
|
7014
|
+
// Publish only after durable settlement; the scoped event cannot
|
|
7015
|
+
// invalidate a newer turn or close another task's accounting.
|
|
7016
|
+
this.eventBus.publish({
|
|
7017
|
+
type: 'task:interrupted', sessionId: session.id, taskId,
|
|
7018
|
+
generation: turnLease.generation, agentAid: runnerSelfAid,
|
|
7019
|
+
reason: streamResult.subtype, causation: taskCausation,
|
|
7020
|
+
});
|
|
7021
|
+
}
|
|
6750
7022
|
}
|
|
6751
7023
|
logger.info(`[${message.channel}] Stream result error suppressed (${interactionCancelled ? 'interaction cancellation' : `user interrupt: ${interruptReason}`}): ${errorSummary}`);
|
|
6752
7024
|
logger.message({
|
|
@@ -6826,6 +7098,9 @@ export class ResponseEngine {
|
|
|
6826
7098
|
? formatPeerKey(configChannelType, configActorId)
|
|
6827
7099
|
: formatPeerKey(configChannelType, message.channelId));
|
|
6828
7100
|
const ctxPct = streamResult.contextUsage?.percentage;
|
|
7101
|
+
// 网关价格缓存(/v1/models 的 pricing/effective_pricing,1h TTL)由当前 runner 提供,
|
|
7102
|
+
// 同时携带实际连接来源,供 usage_events 记录 Provider 维度。
|
|
7103
|
+
const gwPricing = agent.getGatewayPricing?.();
|
|
6829
7104
|
const event = normalizeUsage(streamResult.tokenUsage, {
|
|
6830
7105
|
ts: Date.now(),
|
|
6831
7106
|
agent_aid: statsAgentAid,
|
|
@@ -6835,13 +7110,12 @@ export class ResponseEngine {
|
|
|
6835
7110
|
peer_type: session.chatType || undefined,
|
|
6836
7111
|
session_id: session.id,
|
|
6837
7112
|
model: statsModel,
|
|
7113
|
+
provider_id: gwPricing?.source?.providerId,
|
|
7114
|
+
base_url: gwPricing?.source?.baseUrl,
|
|
6838
7115
|
turns: streamResult.numTurns,
|
|
6839
7116
|
duration_ms: durationMs,
|
|
6840
7117
|
context_window_pct: ctxPct,
|
|
6841
7118
|
});
|
|
6842
|
-
// 写库即得价格对(原价 + 网关价),无需再调 calcCost 重复计算。
|
|
6843
|
-
// 网关价格缓存(/v1/models 的 pricing/effective_pricing,1h TTL)由当前 runner 提供。
|
|
6844
|
-
const gwPricing = agent.getGatewayPricing?.();
|
|
6845
7119
|
const prices = insertUsageEvent(resolveRoot(), event, gwPricing, streamResult.modelCalls);
|
|
6846
7120
|
turnCost = { official: prices.official, gateway: prices.gateway };
|
|
6847
7121
|
// 逐次大模型调用明细落库(model_calls 表)
|
|
@@ -6855,6 +7129,8 @@ export class ResponseEngine {
|
|
|
6855
7129
|
peer_key: statsPeerKey,
|
|
6856
7130
|
call_index: mc.call_index,
|
|
6857
7131
|
model: mc.model || statsModel,
|
|
7132
|
+
provider_id: gwPricing?.source?.providerId,
|
|
7133
|
+
base_url: gwPricing?.source?.baseUrl,
|
|
6858
7134
|
source: mc.source,
|
|
6859
7135
|
provider_thread_id: mc.providerThreadId,
|
|
6860
7136
|
request_id: mc.request_id,
|
|
@@ -6882,7 +7158,7 @@ export class ResponseEngine {
|
|
|
6882
7158
|
let sessionStats;
|
|
6883
7159
|
let modelSpec;
|
|
6884
7160
|
try {
|
|
6885
|
-
const { resolveModelSpec } = await import('../../stats/
|
|
7161
|
+
const { resolveModelSpec } = await import('../../stats/model-resolver.js');
|
|
6886
7162
|
const { querySessionSummary } = await import('../../stats/query.js');
|
|
6887
7163
|
modelSpec = resolveModelSpec(resolveRoot(), statsModel);
|
|
6888
7164
|
const sum = querySessionSummary(resolveRoot(), session.id);
|
|
@@ -7098,6 +7374,8 @@ export class ResponseEngine {
|
|
|
7098
7374
|
&& !isTotalExecutionTimeout;
|
|
7099
7375
|
const isUserInterrupt = isNonErrorInterruptReason(interruptReason) || staleSupersededTurn;
|
|
7100
7376
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
7377
|
+
if (!isUserInterrupt && ownsTimeoutTerminal)
|
|
7378
|
+
await this.askForConnection(error, message, session);
|
|
7101
7379
|
const recoverable = !isUserInterrupt && !error?._replyDeliveryFailed
|
|
7102
7380
|
&& (error === timeoutControl?.error ? timeoutControl?.recoverable === true : isRetryableError(error));
|
|
7103
7381
|
if (isUserInterrupt) {
|
|
@@ -7353,6 +7631,11 @@ export class ResponseEngine {
|
|
|
7353
7631
|
finally {
|
|
7354
7632
|
if (proactiveCircuitBreakTimer)
|
|
7355
7633
|
clearTimeout(proactiveCircuitBreakTimer);
|
|
7634
|
+
if (this.activeTaskSpans.get(session.id)?.taskId === taskId) {
|
|
7635
|
+
this.activeTaskSpans.delete(session.id);
|
|
7636
|
+
if (runnerSelfAid)
|
|
7637
|
+
notifyWorkbenchRuntimeChanged(runnerSelfAid);
|
|
7638
|
+
}
|
|
7356
7639
|
if (taskActivityStore) {
|
|
7357
7640
|
try {
|
|
7358
7641
|
taskActivityStore.updateStatus(taskId, taskActivityStatus);
|
|
@@ -7448,11 +7731,27 @@ export class ResponseEngine {
|
|
|
7448
7731
|
return;
|
|
7449
7732
|
}
|
|
7450
7733
|
const ctx = await this.readLastModelCallContextUsage(session.id, session.agentSessionId);
|
|
7451
|
-
if (!ctx
|
|
7452
|
-
|
|
7734
|
+
if (!ctx)
|
|
7735
|
+
return;
|
|
7736
|
+
const model = modelOverride?.model || agent.getModel?.();
|
|
7737
|
+
if (!model)
|
|
7738
|
+
return;
|
|
7739
|
+
let policy;
|
|
7740
|
+
try {
|
|
7741
|
+
const catalog = modelOverride?.provider
|
|
7742
|
+
? await getRunnerCatalog(agent.name, undefined, { providerId: modelOverride.provider })
|
|
7743
|
+
: await agent.getModelCatalog?.();
|
|
7744
|
+
policy = resolveCatalogAutoCompactPolicy(catalog, model);
|
|
7745
|
+
}
|
|
7746
|
+
catch (error) {
|
|
7747
|
+
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} model catalog unavailable`, error);
|
|
7453
7748
|
return;
|
|
7454
7749
|
}
|
|
7455
|
-
|
|
7750
|
+
if (!policy || ctx.totalTokens < policy.autoCompactTokens) {
|
|
7751
|
+
logger.debug(`[ResponseEngine] Auto compact skipped: session=${session.id} ctx=${ctx.totalTokens}/${policy?.autoCompactTokens ?? 'unknown'}`);
|
|
7752
|
+
return;
|
|
7753
|
+
}
|
|
7754
|
+
logger.info(`[ResponseEngine] Auto compact at task.start: session=${session.id} model=${model} contextWindow=${policy.contextWindow} totalTokens=${ctx.totalTokens} autoCompactTokens=${policy.autoCompactTokens}`);
|
|
7456
7755
|
await this.emitOperationalNotice(renderer, '上下文接近上限,正在压缩会话...', 'info', 'auto-compact-start');
|
|
7457
7756
|
await renderer.flush();
|
|
7458
7757
|
this.announcedCompactStarts.add(session.id);
|
|
@@ -7465,7 +7764,7 @@ export class ResponseEngine {
|
|
|
7465
7764
|
const compacted = await agent.compact(session.id, session.agentSessionId, absoluteProjectPath, modelOverride);
|
|
7466
7765
|
const compactResult = compacted;
|
|
7467
7766
|
if (compactResult === true || compactResult?.ok === true) {
|
|
7468
|
-
await this.emitOperationalNotice(renderer, '
|
|
7767
|
+
await this.emitOperationalNotice(renderer, '上下文压缩完成,继续处理...', 'info', 'auto-compact-complete');
|
|
7469
7768
|
await renderer.flush();
|
|
7470
7769
|
}
|
|
7471
7770
|
else {
|
|
@@ -7521,12 +7820,7 @@ export class ResponseEngine {
|
|
|
7521
7820
|
logger.warn(`[ResponseEngine] Ignoring implausible context_tokens: session=${sessionId} totalTokens=${totalTokens} maxTokens=${maxTokens}`);
|
|
7522
7821
|
return undefined;
|
|
7523
7822
|
}
|
|
7524
|
-
|
|
7525
|
-
// 大窗口模型(1M)到 650k 由 EvolCore 压缩;小窗口模型(200k/128k)
|
|
7526
|
-
// 到不了该阈值,交给 base agent 自身的压缩机制处理。
|
|
7527
|
-
// 历史行里可能存着旧的 350k 阈值,这里一律忽略,只认当前常量。
|
|
7528
|
-
const autoCompactTokens = autoCompactWindowForModel(model);
|
|
7529
|
-
return { totalTokens, autoCompactTokens };
|
|
7823
|
+
return { totalTokens };
|
|
7530
7824
|
}
|
|
7531
7825
|
finally {
|
|
7532
7826
|
if (shouldClose)
|
|
@@ -7633,7 +7927,7 @@ export class ResponseEngine {
|
|
|
7633
7927
|
logger.warn(`[ResponseEngine] Bound session ${boundSessionId} not found, falling back to latest`);
|
|
7634
7928
|
}
|
|
7635
7929
|
}
|
|
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.
|
|
7930
|
+
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
7931
|
this.ensureSessionBaseagent(session, resolvedBaseagent);
|
|
7638
7932
|
// 群名解析:群会话首次取群显示名(group.get),缓存到 metadata,供信封渲染。
|
|
7639
7933
|
// 渠道私有方法 getGroupName 自带进程缓存 + 容错;取不到不阻塞(groupName 保持空,模板回退 groupId)。
|
|
@@ -7847,10 +8141,24 @@ export class ResponseEngine {
|
|
|
7847
8141
|
if (event.type === 'user_question') {
|
|
7848
8142
|
if (!onAsyncQuestion)
|
|
7849
8143
|
throw new Error('Async question has no delivery context');
|
|
7850
|
-
await onAsyncQuestion(
|
|
8144
|
+
const interrupted = await onAsyncQuestion({
|
|
8145
|
+
...event.request,
|
|
8146
|
+
interruptedTools: [...openToolUseIds].map(callId => ({
|
|
8147
|
+
callId,
|
|
8148
|
+
name: toolInputByCallId.get(callId)?.name ?? '工具',
|
|
8149
|
+
})),
|
|
8150
|
+
});
|
|
7851
8151
|
madeProgress = true;
|
|
7852
8152
|
// A structured question is user-visible progress without being a text reply.
|
|
7853
8153
|
textCount++;
|
|
8154
|
+
if (interrupted) {
|
|
8155
|
+
// The blocking question deliberately interrupted its provider turn.
|
|
8156
|
+
// Preserve unresolved calls for diagnosis/recovery, never commit this
|
|
8157
|
+
// partial turn or synthesize successful tool results for it.
|
|
8158
|
+
completeResult = { ...completeResult, isError: false,
|
|
8159
|
+
terminalReason: 'interrupted', subtype: 'awaiting_user_input' };
|
|
8160
|
+
return finalizeResult();
|
|
8161
|
+
}
|
|
7854
8162
|
continue;
|
|
7855
8163
|
}
|
|
7856
8164
|
if (event.type === 'input_accepted') {
|
|
@@ -8220,7 +8528,7 @@ export class ResponseEngine {
|
|
|
8220
8528
|
madeProgress = true;
|
|
8221
8529
|
this.eventBus.publish({ type: 'runner:compact-complete', sessionId: session.id, preTokens: event.preTokens });
|
|
8222
8530
|
if (!shouldSuppress()) {
|
|
8223
|
-
await this.emitOperationalNotice(renderer, '
|
|
8531
|
+
await this.emitOperationalNotice(renderer, '会话压缩完成,继续执行...', 'info', 'compact');
|
|
8224
8532
|
}
|
|
8225
8533
|
}
|
|
8226
8534
|
// 子任务进度
|
|
@@ -8549,6 +8857,11 @@ export class ResponseEngine {
|
|
|
8549
8857
|
}
|
|
8550
8858
|
}
|
|
8551
8859
|
catch (error) {
|
|
8860
|
+
if (error instanceof AsyncQuestionCancelledError) {
|
|
8861
|
+
completeResult = { ...completeResult, isError: false,
|
|
8862
|
+
terminalReason: 'interrupted', subtype: 'interaction_cancelled' };
|
|
8863
|
+
return finalizeResult();
|
|
8864
|
+
}
|
|
8552
8865
|
// User interrupt (AbortError) is expected, log at info level
|
|
8553
8866
|
const catchInterruptReason = this.interruptedSessions.get(session.id);
|
|
8554
8867
|
const catchIsUserInterrupt = isNonErrorInterruptReason(catchInterruptReason);
|