evolcore 0.0.1 → 0.0.2
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 +813 -0
- package/LICENSE +21 -0
- package/MIGRATION-0.5.0.md +378 -0
- package/README.md +318 -14
- package/ROLE_ACCESS_CONTROL.md +174 -0
- package/assets/.env.template +4 -0
- package/assets/brand/evolcore/README.md +19 -0
- package/assets/brand/evolcore/evolcore-app-icon.png +0 -0
- package/assets/brand/evolcore/evolcore-app-icon.svg +13 -0
- package/assets/brand/evolcore/evolcore-brand-board.png +0 -0
- package/assets/brand/evolcore/evolcore-brand-board.svg +126 -0
- package/assets/brand/evolcore/evolcore-logo-kit.zip +0 -0
- package/assets/brand/evolcore/evolcore-logo-reverse.png +0 -0
- package/assets/brand/evolcore/evolcore-logo-reverse.svg +14 -0
- package/assets/brand/evolcore/evolcore-logo.png +0 -0
- package/assets/brand/evolcore/evolcore-logo.svg +14 -0
- package/assets/brand/evolcore/evolcore-mark.png +0 -0
- package/assets/brand/evolcore/evolcore-mark.svg +10 -0
- package/bin/ec-safe-output.js +161 -0
- package/bin/ec.js +29 -0
- package/dist/agents/baseagent.js +163 -0
- package/dist/agents/claude-runner.js +2385 -0
- package/dist/agents/codex-app-server-client.js +448 -0
- package/dist/agents/codex-runner.js +2639 -0
- package/dist/agents/gemini-runner.js +666 -0
- package/dist/agents/runner-types.js +75 -0
- package/dist/aun/aid/agentmd.js +216 -0
- package/dist/aun/aid/client.js +132 -0
- package/dist/aun/aid/control-aid.js +91 -0
- package/dist/aun/aid/identity.js +518 -0
- package/dist/aun/aid/index.js +4 -0
- package/dist/aun/aid/store.js +74 -0
- package/dist/aun/aid/types.js +1 -0
- package/dist/aun/aid/validation.js +21 -0
- package/dist/aun/group-identity.js +10 -0
- package/dist/aun/msg/group-index.js +6 -0
- package/dist/aun/msg/group.js +1231 -0
- package/dist/aun/msg/history.js +123 -0
- package/dist/aun/msg/index.js +5 -0
- package/dist/aun/msg/p2p.js +393 -0
- package/dist/aun/msg/payload-type.js +27 -0
- package/dist/aun/msg/upload.js +137 -0
- package/dist/aun/outbox.js +160 -0
- package/dist/aun/rpc/caller.js +42 -0
- package/dist/aun/rpc/connection.js +25 -0
- package/dist/aun/rpc/index.js +2 -0
- package/dist/aun/service-proxy.js +225 -0
- package/dist/aun/storage/download.js +29 -0
- package/dist/aun/storage/index.js +3 -0
- package/dist/aun/storage/manage.js +10 -0
- package/dist/aun/storage/upload.js +68 -0
- package/dist/channels/aun.js +4147 -0
- package/dist/channels/daemon.js +422 -0
- package/dist/channels/dingtalk.js +649 -0
- package/dist/channels/feishu.js +1789 -0
- package/dist/channels/qqbot.js +409 -0
- package/dist/channels/wechat.js +817 -0
- package/dist/channels/wecom.js +565 -0
- package/dist/cli/agent-command.js +641 -0
- package/dist/cli/agent.js +1059 -0
- package/dist/cli/aun-commands.js +1948 -0
- package/dist/cli/bench.js +1228 -0
- package/dist/cli/cli-argv.js +66 -0
- package/dist/cli/code-stats.js +329 -0
- package/dist/cli/command-log.js +82 -0
- package/dist/cli/config-selector.js +69 -0
- package/dist/cli/config.js +261 -0
- package/dist/cli/ctl-command.js +62 -0
- package/dist/cli/daemon-commands.js +2887 -0
- package/dist/cli/fs-command.js +1447 -0
- package/dist/cli/handoff-command.js +302 -0
- package/dist/cli/help.js +31 -0
- package/dist/cli/index.js +358 -0
- package/dist/cli/init-channel.js +1377 -0
- package/dist/cli/init.js +553 -0
- package/dist/cli/link-rules.js +240 -0
- package/dist/cli/model.js +590 -0
- package/dist/cli/net-check.js +723 -0
- package/dist/cli/queue-command.js +126 -0
- package/dist/cli/response.js +345 -0
- package/dist/cli/restart-monitor.js +456 -0
- package/dist/cli/stats.js +607 -0
- package/dist/cli/task-context.js +80 -0
- package/dist/cli/trigger-command.js +505 -0
- package/dist/cli/version.js +88 -0
- package/dist/cli/watch-logs.js +33 -0
- package/dist/cli/watch-msg.js +673 -0
- package/dist/config/boot-log.js +266 -0
- package/dist/config/builtin-role-templates.js +30 -0
- package/dist/config/builtin-roles.js +85 -0
- package/dist/config/config-batch-get.js +11 -0
- package/dist/config/config-field-policy.js +261 -0
- package/dist/config/config-manager.js +916 -0
- package/dist/config/config-operation-service.js +384 -0
- package/dist/config/contact-book.js +371 -0
- package/dist/config/gateway-config.js +858 -0
- package/dist/config/lifecycle.js +17 -0
- package/dist/config/mention-mode.js +27 -0
- package/dist/config/merge.js +161 -0
- package/dist/config/owner-policy.js +4 -0
- package/dist/config/peer-role-resolver.js +139 -0
- package/dist/config/resolved-config-op.js +483 -0
- package/dist/config/role-config-v4-startup.js +32 -0
- package/dist/config/role-config-v5-startup.js +27 -0
- package/dist/config/role-schema.js +105 -0
- package/dist/config/role-service.js +159 -0
- package/dist/config/role-store.js +204 -0
- package/dist/config/roles.js +55 -0
- package/dist/config/schema-registry.js +154 -0
- package/dist/config/snapshot.js +598 -0
- package/dist/config-store.js +503 -0
- package/dist/core/auth/agent-delegation.js +111 -0
- package/dist/core/auth/auth-gateway.js +166 -0
- package/dist/core/auth/authenticated-actor.js +6 -0
- package/dist/core/auth/authorization-audit.js +110 -0
- package/dist/core/auth/operation-authorizer.js +718 -0
- package/dist/core/auth/operation-catalog.js +675 -0
- package/dist/core/baseagent-loader.js +54 -0
- package/dist/core/bootstrap-service.js +175 -0
- package/dist/core/capability/capability-manager.js +316 -0
- package/dist/core/capability/providers/claude-capability-provider.js +176 -0
- package/dist/core/capability/providers/codex-capability-provider.js +148 -0
- package/dist/core/capability/providers/gemini-capability-provider.js +10 -0
- package/dist/core/capability/types.js +27 -0
- package/dist/core/causation/audit.js +103 -0
- package/dist/core/causation/aun-association.js +111 -0
- package/dist/core/causation/context.js +93 -0
- package/dist/core/causation/index.js +4 -0
- package/dist/core/causation/types.js +2 -0
- package/dist/core/channel-loader.js +277 -0
- package/dist/core/command/agent-control.js +616 -0
- package/dist/core/command/cli-intent-parser.js +225 -0
- package/dist/core/command/command-handler.js +1638 -0
- package/dist/core/command/menu-handler.js +3354 -0
- package/dist/core/command/menu-protocol.js +247 -0
- package/dist/core/command/role-menu.js +1524 -0
- package/dist/core/command/slash-gate.js +148 -0
- package/dist/core/command/slash-handler.js +3056 -0
- package/dist/core/daemon-file-cache.js +216 -0
- package/dist/core/event-bus.js +32 -0
- package/dist/core/event-catalog.js +740 -0
- package/dist/core/evolagent-registry.js +546 -0
- package/dist/core/evolagent.js +331 -0
- package/dist/core/handoff/dispatcher.js +229 -0
- package/dist/core/handoff/mutex.js +46 -0
- package/dist/core/handoff/runtime.js +324 -0
- package/dist/core/handoff/store.js +537 -0
- package/dist/core/handoff/types.js +12 -0
- package/dist/core/inference/text-inference.js +173 -0
- package/dist/core/interaction-registration.js +10 -0
- package/dist/core/interaction-router.js +278 -0
- package/dist/core/message/create-status.js +67 -0
- package/dist/core/message/im-renderer.js +657 -0
- package/dist/core/message/items-formatter.js +76 -0
- package/dist/core/message/logical-queue-bridge.js +123 -0
- package/dist/core/message/message-bridge.js +803 -0
- package/dist/core/message/message-cache.js +56 -0
- package/dist/core/message/message-log.js +339 -0
- package/dist/core/message/message-processor.js +4 -0
- package/dist/core/message/message-queue.js +1436 -0
- package/dist/core/message/message-utils.js +70 -0
- package/dist/core/message/peer-mode.js +105 -0
- package/dist/core/message/pending-hints.js +232 -0
- package/dist/core/message/response-depth.js +33 -0
- package/dist/core/message/response-engine.js +3776 -0
- package/dist/core/message/response-snapshot.js +83 -0
- package/dist/core/message/stream-debouncer.js +130 -0
- package/dist/core/message/stream-idle-monitor.js +124 -0
- package/dist/core/model/config-scope.js +162 -0
- package/dist/core/model/field-scope.js +78 -0
- package/dist/core/model/model-catalog.js +227 -0
- package/dist/core/model/model-diagnostics.js +182 -0
- package/dist/core/model/model-permission.js +90 -0
- package/dist/core/permission/approval-gateway.js +1017 -0
- package/dist/core/permission/ec-command-parser.js +347 -0
- package/dist/core/permission/execution-sandbox.js +16 -0
- package/dist/core/permission/index.js +6 -0
- package/dist/core/permission/mode.js +24 -0
- package/dist/core/permission/sandbox-runtime.js +265 -0
- package/dist/core/permission/tool-policy.js +987 -0
- package/dist/core/permission/unix-socket-policy.js +99 -0
- package/dist/core/protected-paths.js +330 -0
- package/dist/core/relation/peer-identity.js +222 -0
- package/dist/core/relation/peer-key.js +1 -0
- package/dist/core/role/runtime-policy.js +141 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +218 -0
- package/dist/core/session/adapters/codex-session-file-adapter.js +333 -0
- package/dist/core/session/adapters/gemini-session-file-adapter.js +181 -0
- package/dist/core/session/session-file-adapter.js +7 -0
- package/dist/core/session/session-file-health.js +45 -0
- package/dist/core/session/session-fs-store.js +232 -0
- package/dist/core/session/session-key.js +24 -0
- package/dist/core/session/session-manager.js +1587 -0
- package/dist/core/session/session-mapper.js +100 -0
- package/dist/core/session/session-renew.js +314 -0
- package/dist/core/session/session-title.js +128 -0
- package/dist/core/session/session-turn-coordinator.js +205 -0
- package/dist/core/session/session-turns.js +67 -0
- package/dist/core/system-channels.js +29 -0
- package/dist/eck/baseagent-caps.js +18 -0
- package/dist/eck/detect.js +47 -0
- package/dist/eck/group-rules-sync.js +345 -0
- package/dist/eck/init.js +77 -0
- package/dist/eck/kit-renderer.js +359 -0
- package/dist/eck/manifest-engine.js +446 -0
- package/dist/eck/message-renderer.js +199 -0
- package/dist/eck/rules-loader.js +28 -0
- package/dist/index.js +2870 -4
- package/dist/ipc.js +748 -0
- package/dist/paths.js +262 -0
- package/dist/product.js +18 -0
- package/dist/response-system/context-builder.js +71 -0
- package/dist/response-system/coordinator.js +117 -0
- package/dist/response-system/decision-executor.js +86 -0
- package/dist/response-system/engines/v1/index.js +21 -0
- package/dist/response-system/engines/v1/interactive-flow.js +27 -0
- package/dist/response-system/engines/v1/proactive-flow.js +137 -0
- package/dist/response-system/engines/v1/types.js +1 -0
- package/dist/response-system/extensions.js +41 -0
- package/dist/response-system/index.js +6 -0
- package/dist/response-system/modes/index.js +7 -0
- package/dist/response-system/modes/single-session/index.js +72 -0
- package/dist/response-system/queues/fifo-queue.js +44 -0
- package/dist/response-system/queues/index.js +6 -0
- package/dist/response-system/queues/lifo-queue.js +42 -0
- package/dist/response-system/queues/priority-queue.js +63 -0
- package/dist/response-system/registry.js +97 -0
- package/dist/response-system/resolver.js +37 -0
- package/dist/response-system/selector.js +23 -0
- package/dist/response-system/types.js +7 -0
- package/dist/stats/billing.js +151 -0
- package/dist/stats/budget.js +93 -0
- package/dist/stats/db.js +403 -0
- package/dist/stats/eck-vars.js +89 -0
- package/dist/stats/index.js +11 -0
- package/dist/stats/normalizer.js +80 -0
- package/dist/stats/price-resolver.js +138 -0
- package/dist/stats/query.js +763 -0
- package/dist/stats/role-budget.js +168 -0
- package/dist/stats/writer.js +151 -0
- package/dist/trigger/anomaly-store.js +258 -0
- package/dist/trigger/audit.js +152 -0
- package/dist/trigger/event-source.js +119 -0
- package/dist/trigger/feedback.js +685 -0
- package/dist/trigger/history.js +290 -0
- package/dist/trigger/manager.js +291 -0
- package/dist/trigger/parser.js +520 -0
- package/dist/trigger/patch.js +148 -0
- package/dist/trigger/scheduler.js +1600 -0
- package/dist/trigger/script-executor.js +155 -0
- package/dist/trigger/state.js +145 -0
- package/dist/trigger/types.js +1 -0
- package/dist/trigger/validation.js +621 -0
- package/dist/types.js +12 -0
- package/dist/utils/aid-bind.js +299 -0
- package/dist/utils/atomic-write.js +95 -0
- package/dist/utils/avatar-upload.js +123 -0
- package/dist/utils/cross-platform.js +297 -0
- package/dist/utils/ecweb-utils.js +73 -0
- package/dist/utils/error-dict.json +153 -0
- package/dist/utils/error-utils.js +349 -0
- package/dist/utils/instance-registry.js +437 -0
- package/dist/utils/locale.js +21 -0
- package/dist/utils/log-writer.js +224 -0
- package/dist/utils/logger.js +89 -0
- package/dist/utils/markdown-to-plain-text.js +20 -0
- package/dist/utils/media-cache.js +271 -0
- package/dist/utils/model-prices.jsonl +17 -0
- package/dist/utils/npm-ops.js +210 -0
- package/dist/utils/process-introspect.js +133 -0
- package/dist/utils/process-tree-stats.js +271 -0
- package/dist/utils/project-path.js +74 -0
- package/dist/utils/stats.js +410 -0
- package/dist/utils/tool-summary.js +284 -0
- package/dist/utils/welcome.js +268 -0
- package/kits/docs/GUIDE.md +20 -0
- package/kits/docs/INDEX.md +65 -0
- package/kits/docs/aun/CHEATSHEET.md +19 -0
- package/kits/docs/aun/SYNC_PROTOCOL.md +15 -0
- package/kits/docs/channels/aun.md +65 -0
- package/kits/docs/channels/feishu.md +56 -0
- package/kits/docs/context-assembly.md +366 -0
- package/kits/docs/eck_templates/GUIDE.template.md +22 -0
- package/kits/docs/eck_templates/INDEX.template.md +28 -0
- package/kits/docs/eck_templates/path-registry.template.md +33 -0
- package/kits/docs/eck_templates/runtime.template.md +19 -0
- package/kits/docs/evolcore/INDEX.md +66 -0
- package/kits/docs/evolcore/agent.md +69 -0
- package/kits/docs/evolcore/aid.md +49 -0
- package/kits/docs/evolcore/config.md +149 -0
- package/kits/docs/evolcore/ctl.md +46 -0
- package/kits/docs/evolcore/event.md +216 -0
- package/kits/docs/evolcore/fs-architecture.md +1215 -0
- package/kits/docs/evolcore/fs.md +101 -0
- package/kits/docs/evolcore/group-fs.md +17 -0
- package/kits/docs/evolcore/group-rules.md +226 -0
- package/kits/docs/evolcore/group.md +141 -0
- package/kits/docs/evolcore/model.md +47 -0
- package/kits/docs/evolcore/msg.md +130 -0
- package/kits/docs/evolcore/response.md +80 -0
- package/kits/docs/evolcore/rpc.md +35 -0
- package/kits/docs/evolcore/self-summary.md +29 -0
- package/kits/docs/evolcore/stats.md +70 -0
- package/kits/docs/evolcore/storage.md +49 -0
- package/kits/docs/evolcore/trigger.md +524 -0
- package/kits/docs/identity/AID_PROFILE_SPEC.md +26 -0
- package/kits/docs/identity/PATH_OPS.md +16 -0
- package/kits/docs/identity/ROLE_DETAIL.md +23 -0
- package/kits/docs/identity/identity-tools.md +26 -0
- package/kits/docs/path-registry.md +43 -0
- package/kits/docs/prompt-loading-architecture.md +266 -0
- package/kits/docs/venues/aun-group.md +45 -0
- package/kits/docs/venues/aun-private.md +10 -0
- package/kits/docs/venues/client-desktop.md +10 -0
- package/kits/docs/venues/client-mobile.md +10 -0
- package/kits/docs/venues/feishu-group.md +13 -0
- package/kits/docs/venues/feishu-private.md +9 -0
- package/kits/docs/venues/group.md +25 -0
- package/kits/docs/venues/private.md +10 -0
- package/kits/eck_manifest.auxiliary.json +43 -0
- package/kits/eck_manifest.json +191 -0
- package/kits/eck_message_manifest.json +63 -0
- package/kits/migrations/README-role-config-v4.md +32 -0
- package/kits/migrations/migrate-role-config-v4.mjs +623 -0
- package/kits/migrations/migrate-role-config-v5.mjs +346 -0
- package/kits/migrations/rename-config-file.mjs +99 -0
- package/kits/rules/01-overview.md +142 -0
- package/kits/rules/02-navigation.md +76 -0
- package/kits/rules/03-identity.md +34 -0
- package/kits/rules/04-relation.md +59 -0
- package/kits/rules/05-venue.md +44 -0
- package/kits/rules/06-channel.md +59 -0
- package/kits/schemas/_meta.json +29 -0
- package/kits/schemas/agent-config.schema.1.json +177 -0
- package/kits/schemas/agent-config.schema.2.json +239 -0
- package/kits/schemas/agent-config.schema.3.json +119 -0
- package/kits/schemas/agent-config.schema.4.json +208 -0
- package/kits/schemas/agent-config.schema.5.json +326 -0
- package/kits/schemas/contact-book.schema.1.json +36 -0
- package/kits/schemas/daemon.schema.1.json +90 -0
- package/kits/schemas/defaults.schema.1.json +81 -0
- package/kits/schemas/menu-exec-schema-commands.md +208 -0
- package/kits/schemas/migrations/README.md +28 -0
- package/kits/schemas/relation-config.schema.1.json +158 -0
- package/kits/schemas/relation-config.schema.2.json +73 -0
- package/kits/schemas/relation-config.schema.3.json +50 -0
- package/kits/schemas/relation-config.schema.4.json +47 -0
- package/kits/schemas/role-config.schema.1.json +200 -0
- package/kits/schemas/role-registry.schema.1.json +35 -0
- package/kits/schemas/single-session.schema.1.json +31 -0
- package/kits/templates/bootstrap-welcome.md +15 -0
- package/kits/templates/message-fragments/handoff-request-to-target.md +13 -0
- package/kits/templates/message-fragments/handoff-response-to-origin.md +10 -0
- package/kits/templates/message-fragments/inject-default.md +2 -0
- package/kits/templates/message-fragments/item.md +2 -0
- package/kits/templates/roles/admin.json +8 -0
- package/kits/templates/roles/member.json +40 -0
- package/kits/templates/roles/owner.json +8 -0
- package/kits/templates/roles/visitor.json +39 -0
- package/kits/templates/system-fragments/baseagent.md +14 -0
- package/kits/templates/system-fragments/bootstrap.md +16 -0
- package/kits/templates/system-fragments/channel.md +48 -0
- package/kits/templates/system-fragments/commands.md +26 -0
- package/kits/templates/system-fragments/identity.md +11 -0
- package/kits/templates/system-fragments/relation.md +19 -0
- package/kits/templates/system-fragments/session.md +53 -0
- package/kits/templates/system-fragments/venue.md +31 -0
- package/package.json +50 -15
- package/dist/index.d.ts +0 -7
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
import { logger } from '../../utils/logger.js';
|
|
2
|
+
import { summarizeToolInput } from '../../utils/tool-summary.js';
|
|
3
|
+
import { CONTEXT_TOO_LONG_PATTERN, getErrorMessage, isContextTooLongText } from '../../utils/error-utils.js';
|
|
4
|
+
import fs from 'fs';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import { resolvePaths } from '../../paths.js';
|
|
7
|
+
import { DEFAULT_FLUSH_DELAY_MS } from '../../types.js';
|
|
8
|
+
let diagStream = null;
|
|
9
|
+
function getDiagStream() {
|
|
10
|
+
if (!diagStream) {
|
|
11
|
+
const logDir = resolvePaths().logs;
|
|
12
|
+
diagStream = fs.createWriteStream(path.join(logDir, 'im-renderer-diag.log'), { flags: 'a' });
|
|
13
|
+
}
|
|
14
|
+
return diagStream;
|
|
15
|
+
}
|
|
16
|
+
function diag(instanceId, action, meta = {}) {
|
|
17
|
+
const line = JSON.stringify({ ts: new Date().toISOString(), id: instanceId, action, ...meta });
|
|
18
|
+
getDiagStream().write(line + '\n');
|
|
19
|
+
}
|
|
20
|
+
let instanceCounter = 0;
|
|
21
|
+
export class IMRenderer {
|
|
22
|
+
opts;
|
|
23
|
+
itemsQueue = [];
|
|
24
|
+
textBuffer = '';
|
|
25
|
+
timer;
|
|
26
|
+
lastFlush = Date.now();
|
|
27
|
+
allText = '';
|
|
28
|
+
sentContent = false;
|
|
29
|
+
flushCount = 0;
|
|
30
|
+
messageTimestamps = [];
|
|
31
|
+
instanceId;
|
|
32
|
+
diagEnabled;
|
|
33
|
+
/** 串行发送队列:保证消息按序到达 */
|
|
34
|
+
sendChain = Promise.resolve();
|
|
35
|
+
/** proactive:是否已发过 text 文本(用于去重 complete.result) */
|
|
36
|
+
hasEmittedText = false;
|
|
37
|
+
/** 自增 callId 兜底(runner 没提供时用) */
|
|
38
|
+
syntheticCallSeq = 0;
|
|
39
|
+
constructor(opts) {
|
|
40
|
+
this.opts = opts;
|
|
41
|
+
this.diagEnabled = opts.diagEnabled ?? false;
|
|
42
|
+
this.instanceId = `R${++instanceCounter}`;
|
|
43
|
+
if (this.diagEnabled) {
|
|
44
|
+
diag(this.instanceId, 'created', {
|
|
45
|
+
chatmode: opts.envelope.chatmode,
|
|
46
|
+
flushDelay: opts.flushDelay,
|
|
47
|
+
suppressActivityItems: this.suppressActivityItems(),
|
|
48
|
+
suppressIntermediateText: this.suppressIntermediateText(),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
suppressActivityItems() {
|
|
53
|
+
return this.opts.suppressActivityItems ?? this.opts.suppressActivities ?? false;
|
|
54
|
+
}
|
|
55
|
+
suppressIntermediateText() {
|
|
56
|
+
return this.opts.suppressIntermediateText ?? this.opts.suppressActivities ?? false;
|
|
57
|
+
}
|
|
58
|
+
// ── 公开接口 ──
|
|
59
|
+
/** 推入 AgentEvent,按 chatmode 投影 */
|
|
60
|
+
emit(event) {
|
|
61
|
+
try {
|
|
62
|
+
logger.event({ source: 'runner', taskId: this.opts.envelope.taskId, channelId: this.opts.envelope.channelId, event });
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// logger.event 失败不影响业务
|
|
66
|
+
}
|
|
67
|
+
if (this.opts.envelope.chatmode === 'proactive') {
|
|
68
|
+
this.emitProactive(event);
|
|
69
|
+
}
|
|
70
|
+
// interactive 模式由 MessageProcessor 显式调 addText/addToolCall/... 推入 items
|
|
71
|
+
}
|
|
72
|
+
/** 强制刷新所有 pending 事件 */
|
|
73
|
+
async flush(isFinal) {
|
|
74
|
+
if (this.opts.envelope.chatmode === 'proactive') {
|
|
75
|
+
// proactive 是 fire-and-forget,无 pending buffer
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
return this.flushInternal(isFinal);
|
|
79
|
+
}
|
|
80
|
+
/** 仅 flush activities,保留 textBuffer(用于中间 complete 事件) */
|
|
81
|
+
async flushActivitiesOnly() {
|
|
82
|
+
if (this.opts.envelope.chatmode === 'proactive')
|
|
83
|
+
return;
|
|
84
|
+
return this.flushActivitiesInternal();
|
|
85
|
+
}
|
|
86
|
+
/** 是否有 pending 内容 */
|
|
87
|
+
hasContent() {
|
|
88
|
+
return this.textBuffer.length > 0 || this.itemsQueue.some(it => it.kind !== 'text');
|
|
89
|
+
}
|
|
90
|
+
/** 是否有会抑制兜底错误消息的正文/过程内容;lifecycle 边界不算。 */
|
|
91
|
+
hasNonLifecycleContent() {
|
|
92
|
+
return this.textBuffer.length > 0 || this.itemsQueue.some(it => {
|
|
93
|
+
if (it.kind === 'text')
|
|
94
|
+
return it.text.length > 0;
|
|
95
|
+
return it.kind !== 'started' && it.kind !== 'completed';
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/** 是否有待发送的文本 */
|
|
99
|
+
hasTextPending() {
|
|
100
|
+
return this.textBuffer.length > 0;
|
|
101
|
+
}
|
|
102
|
+
/** flush 当前 textBuffer 作为独立的 result.text(非 final),然后清空 buffer */
|
|
103
|
+
async flushText() {
|
|
104
|
+
if (this.opts.envelope.chatmode === 'proactive')
|
|
105
|
+
return;
|
|
106
|
+
if (this.textBuffer.length === 0)
|
|
107
|
+
return;
|
|
108
|
+
if (this.suppressIntermediateText()) {
|
|
109
|
+
this.itemsQueue = this.itemsQueue.filter(it => it.kind !== 'text');
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (this.timer) {
|
|
113
|
+
clearTimeout(this.timer);
|
|
114
|
+
this.timer = undefined;
|
|
115
|
+
}
|
|
116
|
+
// 文件标记过滤:tool_use 前的文本块也不能把 marker 暴露给用户
|
|
117
|
+
const rawText = this.opts.fileMarkerPattern
|
|
118
|
+
? this.textBuffer.replace(this.opts.fileMarkerPattern, '')
|
|
119
|
+
: this.textBuffer;
|
|
120
|
+
this.textBuffer = '';
|
|
121
|
+
if (!rawText)
|
|
122
|
+
return;
|
|
123
|
+
// 清掉 itemsQueue 中的 text items(已发出)
|
|
124
|
+
this.itemsQueue = this.itemsQueue.filter(it => it.kind !== 'text');
|
|
125
|
+
const payload = { kind: 'result.text', text: rawText, isFinal: false };
|
|
126
|
+
this.sentContent = true;
|
|
127
|
+
this.sendChain = this.sendChain
|
|
128
|
+
.then(() => this.opts.send(payload))
|
|
129
|
+
.catch(e => logger.warn('[IMRenderer] flushText send failed:', e));
|
|
130
|
+
await this.sendChain;
|
|
131
|
+
this.lastFlush = Date.now();
|
|
132
|
+
this.flushCount++;
|
|
133
|
+
}
|
|
134
|
+
/** 是否已发送过内容(用于决定最终 flush 是否带 isFinal 标题) */
|
|
135
|
+
hasSentContent() {
|
|
136
|
+
return this.sentContent;
|
|
137
|
+
}
|
|
138
|
+
/** 累积的全部文本(流式 + 最终) */
|
|
139
|
+
getFinalText() {
|
|
140
|
+
return this.allText;
|
|
141
|
+
}
|
|
142
|
+
/** 丢弃当前 attempt 的未发送内容;用于命中可重试错误后避免把瞬时错误文本发给用户。 */
|
|
143
|
+
discardPending() {
|
|
144
|
+
if (this.timer) {
|
|
145
|
+
clearTimeout(this.timer);
|
|
146
|
+
this.timer = undefined;
|
|
147
|
+
}
|
|
148
|
+
this.itemsQueue = [];
|
|
149
|
+
this.textBuffer = '';
|
|
150
|
+
this.allText = '';
|
|
151
|
+
}
|
|
152
|
+
/** 仅丢弃尚未发送的正文,保留 notice/tool 等活动项。 */
|
|
153
|
+
discardPendingText() {
|
|
154
|
+
if (this.timer) {
|
|
155
|
+
clearTimeout(this.timer);
|
|
156
|
+
this.timer = undefined;
|
|
157
|
+
}
|
|
158
|
+
this.itemsQueue = this.itemsQueue.filter(it => it.kind !== 'text');
|
|
159
|
+
this.textBuffer = '';
|
|
160
|
+
}
|
|
161
|
+
/** 当前 buffer 中尚未 flush 的文本 */
|
|
162
|
+
getRemainingText() {
|
|
163
|
+
return this.textBuffer;
|
|
164
|
+
}
|
|
165
|
+
// ── 文本/活动注入(替代 StreamFlusher.addText/addActivity)──
|
|
166
|
+
/** 添加文本片段(流式 text) */
|
|
167
|
+
addText(text, outputTokens, turn) {
|
|
168
|
+
if (this.opts.envelope.chatmode === 'proactive')
|
|
169
|
+
return;
|
|
170
|
+
this.emitProgress('text', outputTokens, turn);
|
|
171
|
+
if (!text)
|
|
172
|
+
return;
|
|
173
|
+
// 同一窗口内连续 text delta 合并到最后一个 text item
|
|
174
|
+
const last = this.itemsQueue[this.itemsQueue.length - 1];
|
|
175
|
+
if (last && last.kind === 'text') {
|
|
176
|
+
last.text += text;
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
this.itemsQueue.push({ kind: 'text', text });
|
|
180
|
+
}
|
|
181
|
+
this.textBuffer += text;
|
|
182
|
+
this.allText += text;
|
|
183
|
+
this.messageTimestamps.push(Date.now());
|
|
184
|
+
if (this.diagEnabled) {
|
|
185
|
+
diag(this.instanceId, 'addText', {
|
|
186
|
+
len: text.length,
|
|
187
|
+
preview: text.substring(0, 60),
|
|
188
|
+
bufLen: this.textBuffer.length,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
this.scheduleFlush();
|
|
192
|
+
}
|
|
193
|
+
/** 添加工具调用 */
|
|
194
|
+
addToolCall(name, input, callId, descText, turn, outputTokens) {
|
|
195
|
+
if (this.opts.envelope.chatmode === 'proactive')
|
|
196
|
+
return;
|
|
197
|
+
this.emitProgress('tool_call', outputTokens, turn, { toolName: name, callId });
|
|
198
|
+
if (this.suppressActivityItems())
|
|
199
|
+
return;
|
|
200
|
+
this.itemsQueue.push({
|
|
201
|
+
kind: 'tool_call',
|
|
202
|
+
call_id: callId || this.synthCallId(),
|
|
203
|
+
name,
|
|
204
|
+
arguments: input,
|
|
205
|
+
text: descText,
|
|
206
|
+
});
|
|
207
|
+
this.messageTimestamps.push(Date.now());
|
|
208
|
+
if (this.diagEnabled)
|
|
209
|
+
diag(this.instanceId, 'addToolCall', { name, callId });
|
|
210
|
+
this.scheduleFlush();
|
|
211
|
+
}
|
|
212
|
+
/** 添加工具结果 */
|
|
213
|
+
addToolResult(name, ok, result, error, callId, durationMs, descText) {
|
|
214
|
+
if (this.opts.envelope.chatmode === 'proactive')
|
|
215
|
+
return;
|
|
216
|
+
this.emitProgress('tool_result', undefined, undefined, { toolName: name, callId, ok, durationMs });
|
|
217
|
+
if (this.suppressActivityItems())
|
|
218
|
+
return;
|
|
219
|
+
this.itemsQueue.push({
|
|
220
|
+
kind: 'tool_result',
|
|
221
|
+
call_id: callId || this.synthCallId(),
|
|
222
|
+
name,
|
|
223
|
+
ok,
|
|
224
|
+
...(result !== undefined && { result }),
|
|
225
|
+
...(error !== undefined && { error }),
|
|
226
|
+
...(durationMs !== undefined && { duration_ms: durationMs }),
|
|
227
|
+
...(descText !== undefined && { text: descText }),
|
|
228
|
+
});
|
|
229
|
+
this.messageTimestamps.push(Date.now());
|
|
230
|
+
if (this.diagEnabled)
|
|
231
|
+
diag(this.instanceId, 'addToolResult', { name, ok, callId });
|
|
232
|
+
this.scheduleFlush();
|
|
233
|
+
}
|
|
234
|
+
/** 添加进度提示 */
|
|
235
|
+
addProgress(text, opts = {}) {
|
|
236
|
+
if (this.opts.envelope.chatmode === 'proactive')
|
|
237
|
+
return;
|
|
238
|
+
if (this.suppressActivityItems())
|
|
239
|
+
return;
|
|
240
|
+
this.emitProgress('progress', undefined, undefined, {
|
|
241
|
+
text,
|
|
242
|
+
state: opts.state,
|
|
243
|
+
toolUses: opts.toolUses,
|
|
244
|
+
durationMs: opts.durationMs,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
/** 添加任务生命周期边界事件,复用 activity.batch 投影路径。 */
|
|
248
|
+
addLifecycle(phase, metadata, text) {
|
|
249
|
+
const item = {
|
|
250
|
+
kind: phase,
|
|
251
|
+
...(text !== undefined && { text }),
|
|
252
|
+
...(metadata !== undefined && { metadata }),
|
|
253
|
+
};
|
|
254
|
+
if (this.opts.envelope.chatmode === 'proactive') {
|
|
255
|
+
this.emitProactiveItem(item);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (this.suppressActivityItems())
|
|
259
|
+
return;
|
|
260
|
+
this.itemsQueue.push(item);
|
|
261
|
+
this.messageTimestamps.push(Date.now());
|
|
262
|
+
this.scheduleFlush();
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* proactive 下放行为 thought 的 notice subtype 白名单——仅"真·终态错误":
|
|
266
|
+
* - context-too-long:上下文超限且无法 auto-compact,任务到此终止
|
|
267
|
+
* - process-exit:Agent 子进程异常崩溃(无 complete 事件,emit 完全覆盖不到)
|
|
268
|
+
* 二者都是用户必须知道、否则会困惑"任务为什么停了"的终态信号。
|
|
269
|
+
*
|
|
270
|
+
* 其余 subtype 一律不发:
|
|
271
|
+
* - compact / runtime-error / task-error:emit() 路径(mapEventToItem)已投影,重复
|
|
272
|
+
* - compact-start / compact-trigger / compact-retry / retry:内部机务噪音(压缩中/
|
|
273
|
+
* 重试中/压缩完成),proactive 下用户要的是工作产出而非流水账,压缩后 thought 会
|
|
274
|
+
* 继续输出,过程本身无需播报。
|
|
275
|
+
*/
|
|
276
|
+
static PROACTIVE_NOTICE_ALLOW = new Set(['context-too-long', 'process-exit']);
|
|
277
|
+
/** 添加系统提示 / 通知。force=true 仅跳过入队门禁;最终 flush 仍遵守 activity 抑制。 */
|
|
278
|
+
addNotice(text, severity, subtype, force = false) {
|
|
279
|
+
// proactive 模式:只放行真·终态错误,机务噪音(压缩/重试)和 emit 已覆盖的 subtype 均不发。
|
|
280
|
+
if (this.opts.envelope.chatmode === 'proactive') {
|
|
281
|
+
if (subtype == null || !IMRenderer.PROACTIVE_NOTICE_ALLOW.has(subtype))
|
|
282
|
+
return;
|
|
283
|
+
this.emitProactiveItem({ kind: 'notice', text, severity, subtype });
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (this.suppressActivityItems() && !force)
|
|
287
|
+
return;
|
|
288
|
+
this.itemsQueue.push({ kind: 'notice', text, severity, subtype });
|
|
289
|
+
this.messageTimestamps.push(Date.now());
|
|
290
|
+
this.scheduleFlush();
|
|
291
|
+
}
|
|
292
|
+
// ── 内部:interactive 模式聚合窗口 ──
|
|
293
|
+
synthCallId() {
|
|
294
|
+
return `synth-${this.opts.envelope.taskId}-${++this.syntheticCallSeq}`;
|
|
295
|
+
}
|
|
296
|
+
scheduleFlush() {
|
|
297
|
+
if (this.timer) {
|
|
298
|
+
if (this.diagEnabled)
|
|
299
|
+
diag(this.instanceId, 'scheduleFlush:skip', { reason: 'timer_exists' });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const interval = this.opts.flushDelay ?? DEFAULT_FLUSH_DELAY_MS;
|
|
303
|
+
let targetDelay;
|
|
304
|
+
if (this.flushCount === 0) {
|
|
305
|
+
targetDelay = 500;
|
|
306
|
+
}
|
|
307
|
+
else if (this.flushCount <= 3) {
|
|
308
|
+
targetDelay = Math.ceil(interval / 2);
|
|
309
|
+
}
|
|
310
|
+
else if (this.messageTimestamps.length >= 5) {
|
|
311
|
+
targetDelay = this.calculateDynamicDelay(interval);
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
targetDelay = interval;
|
|
315
|
+
}
|
|
316
|
+
const elapsed = Date.now() - this.lastFlush;
|
|
317
|
+
const delay = Math.max(0, targetDelay - elapsed);
|
|
318
|
+
if (this.diagEnabled) {
|
|
319
|
+
diag(this.instanceId, 'scheduleFlush:set', {
|
|
320
|
+
flushCount: this.flushCount,
|
|
321
|
+
targetDelay,
|
|
322
|
+
elapsed,
|
|
323
|
+
actualDelay: delay,
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
this.timer = setTimeout(() => this.flushInternal(), delay);
|
|
327
|
+
}
|
|
328
|
+
calculateDynamicDelay(interval) {
|
|
329
|
+
const recent = this.messageTimestamps.slice(-10);
|
|
330
|
+
const intervals = [];
|
|
331
|
+
for (let i = 1; i < recent.length; i++) {
|
|
332
|
+
intervals.push(recent[i] - recent[i - 1]);
|
|
333
|
+
}
|
|
334
|
+
if (intervals.length === 0)
|
|
335
|
+
return interval;
|
|
336
|
+
const avgInterval = intervals.reduce((a, b) => a + b) / intervals.length;
|
|
337
|
+
const dynamicDelay = avgInterval * 3;
|
|
338
|
+
const minDelay = interval;
|
|
339
|
+
const maxDelay = interval * 2.5;
|
|
340
|
+
return Math.max(minDelay, Math.min(maxDelay, dynamicDelay));
|
|
341
|
+
}
|
|
342
|
+
/** 仅 flush 非 text items(text items 和 textBuffer 保留,等待下次完整 flush) */
|
|
343
|
+
async flushActivitiesInternal() {
|
|
344
|
+
const nonThinking = this.itemsQueue.filter(it => it.kind !== 'text');
|
|
345
|
+
if (nonThinking.length === 0)
|
|
346
|
+
return;
|
|
347
|
+
if (this.timer) {
|
|
348
|
+
clearTimeout(this.timer);
|
|
349
|
+
this.timer = undefined;
|
|
350
|
+
}
|
|
351
|
+
// 移除已 flush 的 non-text items,保留 text items
|
|
352
|
+
this.itemsQueue = this.itemsQueue.filter(it => it.kind === 'text');
|
|
353
|
+
if (this.suppressActivityItems())
|
|
354
|
+
return;
|
|
355
|
+
const payload = { kind: 'activity.batch', items: nonThinking };
|
|
356
|
+
if (this.diagEnabled)
|
|
357
|
+
diag(this.instanceId, 'flushActivitiesOnly', { itemCount: nonThinking.length });
|
|
358
|
+
this.sentContent = true;
|
|
359
|
+
this.sendChain = this.sendChain
|
|
360
|
+
.then(() => this.opts.send(payload))
|
|
361
|
+
.catch(e => logger.warn('[IMRenderer] activity.batch send failed:', e));
|
|
362
|
+
await this.sendChain;
|
|
363
|
+
this.lastFlush = Date.now();
|
|
364
|
+
this.flushCount++;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* 完整 flush:把 itemsQueue 里所有 items 打包成 activity.batch 发送。
|
|
368
|
+
* 如果 isFinal=true,还会在 batch 之后单独发一条 result.text 作为最终回复。
|
|
369
|
+
*/
|
|
370
|
+
async flushInternal(isFinal) {
|
|
371
|
+
if (this.timer) {
|
|
372
|
+
clearTimeout(this.timer);
|
|
373
|
+
this.timer = undefined;
|
|
374
|
+
}
|
|
375
|
+
// 文件标记过滤:marker 任何时候都不该出现在用户文本里,必须在 *每次* flush
|
|
376
|
+
// (含非最终的定时 flush)执行。否则文本块若滞留 buffer 后被定时器触发,会走
|
|
377
|
+
// 下方非-final 的 result.text 路径,把 [SEND_FILE:...] 原样发给用户。
|
|
378
|
+
// 非最终 flush 不做 trim,避免 trim 掉 Markdown 块级换行。
|
|
379
|
+
if (this.opts.fileMarkerPattern) {
|
|
380
|
+
const strip = (s) => {
|
|
381
|
+
const replaced = s.replace(this.opts.fileMarkerPattern, '');
|
|
382
|
+
return isFinal ? replaced.trim() : replaced;
|
|
383
|
+
};
|
|
384
|
+
this.textBuffer = strip(this.textBuffer);
|
|
385
|
+
for (const item of this.itemsQueue) {
|
|
386
|
+
if (item.kind === 'text')
|
|
387
|
+
item.text = item.text.replace(this.opts.fileMarkerPattern, '');
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (isFinal) {
|
|
391
|
+
// 上下文错误短语过滤:剔除错误关键词本身,保留前后内容。
|
|
392
|
+
// 只在最终 flush 清理,避免中间定时 flush trim 掉 Markdown 块级换行。
|
|
393
|
+
const ctxErrPattern = new RegExp(CONTEXT_TOO_LONG_PATTERN.source, 'gi');
|
|
394
|
+
const stripCtxErr = (s) => s.replace(ctxErrPattern, '').trim();
|
|
395
|
+
this.textBuffer = stripCtxErr(this.textBuffer);
|
|
396
|
+
this.allText = stripCtxErr(this.allText);
|
|
397
|
+
for (const item of this.itemsQueue) {
|
|
398
|
+
if (item.kind === 'text')
|
|
399
|
+
item.text = stripCtxErr(item.text);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
// 清掉空 text items
|
|
403
|
+
const items = this.itemsQueue.filter(it => {
|
|
404
|
+
if (it.kind === 'text')
|
|
405
|
+
return it.text.length > 0;
|
|
406
|
+
return true;
|
|
407
|
+
});
|
|
408
|
+
this.itemsQueue = [];
|
|
409
|
+
const finalText = isFinal ? this.textBuffer : '';
|
|
410
|
+
if (isFinal)
|
|
411
|
+
this.textBuffer = '';
|
|
412
|
+
if (this.diagEnabled) {
|
|
413
|
+
diag(this.instanceId, 'flush', {
|
|
414
|
+
isFinal,
|
|
415
|
+
itemCount: items.length,
|
|
416
|
+
finalTextLen: finalText.length,
|
|
417
|
+
flushCount: this.flushCount,
|
|
418
|
+
sinceLastFlush: Date.now() - this.lastFlush,
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
// 1. interactive 模式下:不发 text items(由 result.text 统一发送最终文本)
|
|
422
|
+
let itemsForBatch = this.suppressActivityItems() ? [] : items.filter(it => it.kind !== 'text');
|
|
423
|
+
if (itemsForBatch.length > 0) {
|
|
424
|
+
const payload = { kind: 'activity.batch', items: itemsForBatch };
|
|
425
|
+
this.sentContent = true;
|
|
426
|
+
this.sendChain = this.sendChain
|
|
427
|
+
.then(() => this.opts.send(payload))
|
|
428
|
+
.catch(e => logger.warn('[IMRenderer] activity.batch send failed:', e));
|
|
429
|
+
await this.sendChain;
|
|
430
|
+
this.lastFlush = Date.now();
|
|
431
|
+
this.flushCount++;
|
|
432
|
+
}
|
|
433
|
+
// 1.5 非最终定时 flush:把已累积的文本块作为独立 result.text 发出。
|
|
434
|
+
// 每个 text 事件本身是完整语义块(runner 已合并流式 delta),工具调用前的
|
|
435
|
+
// 文本一向作为独立气泡发送(见 message-processor 的 flushText 调用)。
|
|
436
|
+
// 这里补上「文本块后面没有紧跟 tool_use」的情况——例如 readonly 拒绝写文件时
|
|
437
|
+
// SDK 直接拒绝、不产生 tool_use 事件,文本会一直滞留 buffer,直到下一个
|
|
438
|
+
// tool_use 才被 flushText 带出,并与其后的文本合并成一条(用户侧表现为:
|
|
439
|
+
// 第一条文本等待一分多钟后才和第二条凑成一条发出)。定时器到期即发,根除滞留。
|
|
440
|
+
if (!isFinal && this.textBuffer.length > 0) {
|
|
441
|
+
if (this.suppressIntermediateText())
|
|
442
|
+
return;
|
|
443
|
+
const text = this.textBuffer;
|
|
444
|
+
this.textBuffer = '';
|
|
445
|
+
const payload = { kind: 'result.text', text, isFinal: false };
|
|
446
|
+
this.sentContent = true;
|
|
447
|
+
this.sendChain = this.sendChain
|
|
448
|
+
.then(() => this.opts.send(payload))
|
|
449
|
+
.catch(e => logger.warn('[IMRenderer] timed result.text send failed:', e));
|
|
450
|
+
await this.sendChain;
|
|
451
|
+
this.lastFlush = Date.now();
|
|
452
|
+
this.flushCount++;
|
|
453
|
+
}
|
|
454
|
+
// 2. isFinal=true 时单独发最终回复文本
|
|
455
|
+
if (isFinal && finalText.length > 0) {
|
|
456
|
+
const payload = { kind: 'result.text', text: finalText, isFinal: true };
|
|
457
|
+
this.sentContent = true;
|
|
458
|
+
this.sendChain = this.sendChain
|
|
459
|
+
.then(() => this.opts.send(payload))
|
|
460
|
+
.catch(e => logger.warn('[IMRenderer] result.text send failed:', e));
|
|
461
|
+
await this.sendChain;
|
|
462
|
+
this.lastFlush = Date.now();
|
|
463
|
+
this.flushCount++;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
// ── 内部:status.progress 发送 ──
|
|
467
|
+
emitProgress(activityType, outputTokens, turn, extra) {
|
|
468
|
+
if (this.suppressActivityItems())
|
|
469
|
+
return;
|
|
470
|
+
const payload = {
|
|
471
|
+
kind: 'status.progress',
|
|
472
|
+
metadata: {
|
|
473
|
+
activityType,
|
|
474
|
+
...(turn != null && { turn }),
|
|
475
|
+
...(outputTokens != null && { outputTokens }),
|
|
476
|
+
...(extra?.toolName != null && { toolName: extra.toolName }),
|
|
477
|
+
...(extra?.callId != null && { callId: extra.callId }),
|
|
478
|
+
...(extra?.ok != null && { ok: extra.ok }),
|
|
479
|
+
...(extra?.durationMs != null && { durationMs: extra.durationMs }),
|
|
480
|
+
...(extra?.text != null && { text: extra.text }),
|
|
481
|
+
...(extra?.state != null && { state: extra.state }),
|
|
482
|
+
...(extra?.toolUses != null && { toolUses: extra.toolUses }),
|
|
483
|
+
},
|
|
484
|
+
};
|
|
485
|
+
this.opts.send(payload).catch(() => { });
|
|
486
|
+
}
|
|
487
|
+
// ── 内部:proactive 模式(逐事件 activity.batch[1 item]) ──
|
|
488
|
+
emitProactive(event) {
|
|
489
|
+
// 对齐 interactive 的 dedup:流式 text 已推过时,complete.result 不再重复发 summary
|
|
490
|
+
if (event.type === 'complete' &&
|
|
491
|
+
!event.isError &&
|
|
492
|
+
event.result &&
|
|
493
|
+
this.hasEmittedText) {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
const item = this.mapEventToItem(event);
|
|
497
|
+
if (!item)
|
|
498
|
+
return;
|
|
499
|
+
if (item.kind === 'text') {
|
|
500
|
+
this.hasEmittedText = true;
|
|
501
|
+
this.allText += item.text;
|
|
502
|
+
}
|
|
503
|
+
// proactive 模式:status.progress 是 interactive 的处理状态指示器,proactive 下
|
|
504
|
+
// 过程由 thought(activity.batch)表达,不再发 status.progress(与 addProgress 在
|
|
505
|
+
// proactive 下的拦截保持一致)。progress-kind item 若进 activity.batch 会被 aun 侧
|
|
506
|
+
// 回转成 status.progress(见 aun.ts 'activity.batch' 分支),故直接丢弃。
|
|
507
|
+
// 终态 status(started/completed/interrupted/error)由 message-processor 发送,不受影响。
|
|
508
|
+
if (item.kind === 'progress') {
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
this.emitProactiveItem(item);
|
|
512
|
+
}
|
|
513
|
+
/** proactive 模式逐条投影:单个 ThoughtItem 包成 activity.batch[1] 发出(fire-and-forget)。 */
|
|
514
|
+
emitProactiveItem(item) {
|
|
515
|
+
const payload = { kind: 'activity.batch', items: [item] };
|
|
516
|
+
this.opts.send(payload).catch(err => {
|
|
517
|
+
logger.debug(`[IMRenderer] proactive send failed: ${err.message}`);
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
mapEventToItem(event) {
|
|
521
|
+
switch (event.type) {
|
|
522
|
+
case 'text':
|
|
523
|
+
if (!event.text)
|
|
524
|
+
return null;
|
|
525
|
+
return { kind: 'text', text: event.text };
|
|
526
|
+
case 'tool_use': {
|
|
527
|
+
const desc = summarizeToolInput(event.name, event.input || {});
|
|
528
|
+
const item = {
|
|
529
|
+
kind: 'tool_call',
|
|
530
|
+
call_id: event.callId || this.synthCallId(),
|
|
531
|
+
name: event.name,
|
|
532
|
+
text: desc,
|
|
533
|
+
};
|
|
534
|
+
if (event.input !== undefined)
|
|
535
|
+
item.arguments = event.input;
|
|
536
|
+
return item;
|
|
537
|
+
}
|
|
538
|
+
case 'tool_result':
|
|
539
|
+
if (event.isError) {
|
|
540
|
+
return {
|
|
541
|
+
kind: 'tool_result',
|
|
542
|
+
call_id: event.callId || this.synthCallId(),
|
|
543
|
+
name: event.name,
|
|
544
|
+
ok: false,
|
|
545
|
+
error: event.error || (typeof event.result === 'string' ? event.result : '执行失败'),
|
|
546
|
+
...(event.durationMs !== undefined && { duration_ms: event.durationMs }),
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
else {
|
|
550
|
+
const resultText = this.truncate(this.stringifyResult(event.result), 200);
|
|
551
|
+
return {
|
|
552
|
+
kind: 'tool_result',
|
|
553
|
+
call_id: event.callId || this.synthCallId(),
|
|
554
|
+
name: event.name,
|
|
555
|
+
ok: true,
|
|
556
|
+
result: event.result,
|
|
557
|
+
text: resultText,
|
|
558
|
+
...(event.durationMs !== undefined && { duration_ms: event.durationMs }),
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
case 'compact':
|
|
562
|
+
return {
|
|
563
|
+
kind: 'notice',
|
|
564
|
+
text: `💡 会话压缩完成 (压缩前 tokens: ${event.preTokens})`,
|
|
565
|
+
severity: 'info',
|
|
566
|
+
subtype: 'compact',
|
|
567
|
+
};
|
|
568
|
+
case 'task_progress': {
|
|
569
|
+
const stats = this.formatTaskStats(event);
|
|
570
|
+
const text = event.summary
|
|
571
|
+
? `子任务: ${event.summary}${stats ? ` (${stats})` : ''}`
|
|
572
|
+
: `子任务进行中${stats ? `: ${stats}` : ''}`;
|
|
573
|
+
const item = {
|
|
574
|
+
kind: 'progress',
|
|
575
|
+
text,
|
|
576
|
+
state: 'processing',
|
|
577
|
+
};
|
|
578
|
+
if (event.toolUses !== undefined)
|
|
579
|
+
item.tool_uses = event.toolUses;
|
|
580
|
+
if (event.durationMs !== undefined)
|
|
581
|
+
item.duration_ms = event.durationMs;
|
|
582
|
+
return item;
|
|
583
|
+
}
|
|
584
|
+
case 'error': {
|
|
585
|
+
// 上下文过长错误不输出(留给外层 auto-compact 处理)
|
|
586
|
+
if (isContextTooLongText(event.error || ''))
|
|
587
|
+
return null;
|
|
588
|
+
const text = getErrorMessage(new Error(event.error || '任务执行失败'), undefined, false);
|
|
589
|
+
return { kind: 'notice', text, severity: 'warn' };
|
|
590
|
+
}
|
|
591
|
+
case 'complete': {
|
|
592
|
+
// 上下文过长错误不输出(留给外层 auto-compact 处理)
|
|
593
|
+
const hasContextError = event.terminalReason === 'prompt_too_long'
|
|
594
|
+
|| isContextTooLongText(event.errors?.join(' ') || '')
|
|
595
|
+
|| isContextTooLongText(event.result || '');
|
|
596
|
+
if (event.isError && hasContextError) {
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
if (event.isError) {
|
|
600
|
+
const errText = event.errors?.join('; ') || event.result || '任务失败';
|
|
601
|
+
const text = getErrorMessage(new Error(errText), event.terminalReason, false);
|
|
602
|
+
const item = {
|
|
603
|
+
kind: 'summary',
|
|
604
|
+
text,
|
|
605
|
+
is_error: true,
|
|
606
|
+
};
|
|
607
|
+
if (event.subtype !== undefined)
|
|
608
|
+
item.subtype = event.subtype;
|
|
609
|
+
if (event.durationMs !== undefined)
|
|
610
|
+
item.duration_ms = event.durationMs;
|
|
611
|
+
return item;
|
|
612
|
+
}
|
|
613
|
+
if (event.result) {
|
|
614
|
+
const item = {
|
|
615
|
+
kind: 'summary',
|
|
616
|
+
text: event.result,
|
|
617
|
+
};
|
|
618
|
+
if (event.subtype !== undefined)
|
|
619
|
+
item.subtype = event.subtype;
|
|
620
|
+
if (event.durationMs !== undefined)
|
|
621
|
+
item.duration_ms = event.durationMs;
|
|
622
|
+
return item;
|
|
623
|
+
}
|
|
624
|
+
return null;
|
|
625
|
+
}
|
|
626
|
+
case 'session_id':
|
|
627
|
+
case 'state_changed':
|
|
628
|
+
case 'status':
|
|
629
|
+
return null;
|
|
630
|
+
default:
|
|
631
|
+
return null;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
stringifyResult(result) {
|
|
635
|
+
if (result === null || result === undefined)
|
|
636
|
+
return '';
|
|
637
|
+
if (typeof result === 'string')
|
|
638
|
+
return result;
|
|
639
|
+
try {
|
|
640
|
+
return JSON.stringify(result);
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
return String(result);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
truncate(text, maxLen) {
|
|
647
|
+
return text.length > maxLen ? text.substring(0, maxLen) + '...' : text;
|
|
648
|
+
}
|
|
649
|
+
formatTaskStats(event) {
|
|
650
|
+
const parts = [];
|
|
651
|
+
if (event.toolUses)
|
|
652
|
+
parts.push(`${event.toolUses} tools`);
|
|
653
|
+
if (event.durationMs)
|
|
654
|
+
parts.push(`${Math.round(event.durationMs / 1000)}s`);
|
|
655
|
+
return parts.join(', ');
|
|
656
|
+
}
|
|
657
|
+
}
|