@octopi-agent/engine 0.90.11 → 0.98.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config-admin/agent-presets.d.ts +70 -0
- package/dist/config-admin/agent-presets.js +243 -0
- package/dist/config-admin/discover.d.ts +30 -0
- package/dist/config-admin/discover.js +48 -0
- package/dist/config-admin/env.d.ts +22 -0
- package/dist/config-admin/env.js +41 -0
- package/dist/config-admin/index.d.ts +20 -0
- package/dist/config-admin/index.js +15 -0
- package/dist/config-admin/model-presets.d.ts +75 -0
- package/dist/config-admin/model-presets.js +249 -0
- package/dist/config-admin/name-guard.d.ts +14 -0
- package/dist/config-admin/name-guard.js +24 -0
- package/dist/config-admin/patch.d.ts +56 -0
- package/dist/config-admin/patch.js +201 -0
- package/dist/config-admin/port.d.ts +68 -0
- package/dist/config-admin/port.js +21 -0
- package/dist/config-admin/redact.d.ts +39 -0
- package/dist/config-admin/redact.js +42 -0
- package/dist/config-schema/agent.d.ts +45 -1
- package/dist/config-schema/context.d.ts +6 -1
- package/dist/config-schema/context.js +8 -0
- package/dist/config-schema/engine.d.ts +110 -4
- package/dist/config-schema/governance.d.ts +45 -1
- package/dist/config-schema/governance.js +187 -0
- package/dist/config-schema/models.d.ts +5 -2
- package/dist/config-schema/models.js +4 -1
- package/dist/config-schema/observability.d.ts +9 -0
- package/dist/config-schema/observability.js +29 -0
- package/dist/config-schema/run.d.ts +3 -0
- package/dist/config-schema/run.js +14 -0
- package/dist/config.d.ts +29 -4
- package/dist/config.js +15 -4
- package/dist/harness/activation/dispatcher.d.ts +8 -2
- package/dist/harness/activation/dispatcher.js +33 -5
- package/dist/harness/activation/inbox.d.ts +87 -0
- package/dist/harness/activation/inbox.js +169 -0
- package/dist/harness/activation/runtime.d.ts +9 -8
- package/dist/harness/activation/runtime.js +100 -8
- package/dist/harness/activation/types.d.ts +19 -0
- package/dist/harness/activation/types.js +2 -0
- package/dist/harness/agent/builder.d.ts +26 -1
- package/dist/harness/agent/builder.js +85 -37
- package/dist/harness/agent/config-bridge.d.ts +5 -0
- package/dist/harness/agent/config-bridge.js +3 -0
- package/dist/harness/agent/config-integrity.d.ts +138 -0
- package/dist/harness/agent/config-integrity.js +235 -0
- package/dist/harness/agent/wire-agent-builder.js +7 -1
- package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
- package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
- package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
- package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
- package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
- package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
- package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
- package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
- package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
- package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
- package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
- package/dist/harness/collaboration/delegation/child-run.js +21 -5
- package/dist/harness/collaboration/delegation/notifier.js +4 -3
- package/dist/harness/collaboration/delegation/service.js +2 -3
- package/dist/harness/collaboration/delegation/wiring.js +6 -5
- package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
- package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
- package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
- package/dist/harness/context/capabilities/compact/engine.js +198 -46
- package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
- package/dist/harness/context/capabilities/compact/handover.js +107 -0
- package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
- package/dist/harness/context/capabilities/compact/index.js +2 -1
- package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
- package/dist/harness/context/capabilities/summary/executor.js +2 -1
- package/dist/harness/context/capabilities/summary/policies.js +8 -5
- package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
- package/dist/harness/context/capabilities/summary/resolver.js +4 -4
- package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
- package/dist/harness/context/constitution/default-agents.md +11 -10
- package/dist/harness/context/default-context-engine.d.ts +34 -4
- package/dist/harness/context/default-context-engine.js +194 -49
- package/dist/harness/context/hybrid-compressor.js +6 -0
- package/dist/harness/context/layers.d.ts +2 -4
- package/dist/harness/context/layers.js +9 -11
- package/dist/harness/context/llm-summarizer.d.ts +2 -8
- package/dist/harness/context/llm-summarizer.js +69 -91
- package/dist/harness/context/message-selector.js +4 -3
- package/dist/harness/context/summarize.d.ts +3 -1
- package/dist/harness/context/summarize.js +9 -4
- package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
- package/dist/harness/context/system-prompt-assembler.js +1 -0
- package/dist/harness/context/truncate-compressor.js +7 -0
- package/dist/harness/context/turn-envelope.d.ts +3 -2
- package/dist/harness/context/turn-envelope.js +3 -2
- package/dist/harness/context/types.d.ts +33 -1
- package/dist/harness/extension/execution-environment/dangerous-commands.d.ts +28 -0
- package/dist/harness/extension/execution-environment/dangerous-commands.js +129 -0
- package/dist/harness/extension/execution-environment/effect-policy.d.ts +149 -8
- package/dist/harness/extension/execution-environment/effect-policy.js +274 -19
- package/dist/harness/extension/execution-environment/index.d.ts +4 -2
- package/dist/harness/extension/execution-environment/index.js +2 -1
- package/dist/harness/extension/execution-environment/kill-switch.d.ts +34 -0
- package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
- package/dist/harness/extension/execution-environment/ops-audit.d.ts +204 -0
- package/dist/harness/extension/execution-environment/ops-audit.js +337 -0
- package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
- package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
- package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
- package/dist/harness/extension/execution-environment/process-info.js +466 -0
- package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
- package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
- package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
- package/dist/harness/extension/execution-environment/sandbox.js +228 -21
- package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
- package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
- package/dist/harness/extension/execution-environment/types.d.ts +19 -0
- package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
- package/dist/harness/extension/execution-environment/undo-log.js +31 -10
- package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
- package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +33 -0
- package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +4 -5
- package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +5 -15
- package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +3 -0
- package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +70 -26
- package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
- package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
- package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
- package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
- package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
- package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +2 -0
- package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
- package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
- package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
- package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
- package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
- package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
- package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
- package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
- package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
- package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
- package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
- package/dist/harness/governance/security/default-risk-policy.js +1 -0
- package/dist/harness/governance/security/default-security-guard.js +9 -0
- package/dist/harness/governance/security/index.d.ts +1 -0
- package/dist/harness/governance/security/index.js +2 -0
- package/dist/harness/governance/security/risk-evaluator.js +13 -0
- package/dist/harness/governance/security/risk-types.d.ts +12 -0
- package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
- package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
- package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
- package/dist/harness/governance/security/shell-parser-shared.js +188 -0
- package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
- package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
- package/dist/harness/governance/security/shell-parser.d.ts +23 -10
- package/dist/harness/governance/security/shell-parser.js +37 -496
- package/dist/harness/governance/security/temp-path.d.ts +9 -0
- package/dist/harness/governance/security/temp-path.js +13 -2
- package/dist/harness/governance/security/vendor/README.md +24 -0
- package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
- package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
- package/dist/harness/governance/session-acl/seed-roles.js +14 -0
- package/dist/harness/index.d.ts +2 -0
- package/dist/harness/index.js +2 -0
- package/dist/harness/knowledge/fts.js +1 -2
- package/dist/harness/knowledge/index-store.js +59 -9
- package/dist/harness/memory/index.d.ts +6 -2
- package/dist/harness/memory/index.js +4 -1
- package/dist/harness/memory/memory-events.d.ts +25 -0
- package/dist/harness/memory/memory-events.js +38 -0
- package/dist/harness/memory/sqlite/agent-db.js +15 -0
- package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
- package/dist/harness/memory/sqlite/keyword-search.js +4 -3
- package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
- package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
- package/dist/harness/memory/steward-policy.d.ts +3 -0
- package/dist/harness/memory/steward-policy.js +1 -1
- package/dist/harness/memory/types.d.ts +41 -3
- package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
- package/dist/harness/memory/wisdom-attribution.js +287 -0
- package/dist/harness/memory/wisdom-events.d.ts +37 -0
- package/dist/harness/memory/wisdom-events.js +61 -0
- package/dist/harness/memory/wisdom-formation.d.ts +20 -1
- package/dist/harness/memory/wisdom-formation.js +55 -21
- package/dist/harness/memory/wisdom.d.ts +7 -2
- package/dist/harness/memory/wisdom.js +40 -2
- package/dist/harness/observability/observer/hub.js +8 -0
- package/dist/harness/observability/observer/run-snapshot.js +1 -0
- package/dist/harness/observability/observer/types.d.ts +4 -0
- package/dist/harness/run/agent/agent.d.ts +7 -0
- package/dist/harness/run/agent/agent.js +23 -1
- package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
- package/dist/harness/run/reliability/fallback-provider.js +262 -22
- package/dist/harness/run/reliability/harness-events.d.ts +24 -1
- package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
- package/dist/harness/run/reliability/model-error-policy.js +42 -0
- package/dist/harness/run/reliability/provider-wrapper.js +29 -2
- package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
- package/dist/harness/run/reliability/refusal-guard.js +102 -0
- package/dist/harness/run/reliability/run-agent.js +231 -33
- package/dist/harness/run/run-guard/default-run-guard.js +1 -1
- package/dist/harness/run/run-scope.d.ts +35 -0
- package/dist/harness/run/runner.d.ts +141 -2
- package/dist/harness/run/runner.js +592 -42
- package/dist/harness/session/attachments/llm-intent.js +2 -1
- package/dist/harness/session/tasks/render.d.ts +4 -1
- package/dist/harness/session/tasks/render.js +10 -7
- package/dist/harness/shared/events/agent-event-map.d.ts +66 -0
- package/dist/harness/shared/events/agent-event-map.js +5 -0
- package/dist/harness/shared/paths/glob.d.ts +52 -0
- package/dist/harness/shared/paths/glob.js +218 -0
- package/dist/harness/shared/paths/index.d.ts +84 -0
- package/dist/harness/shared/paths/index.js +179 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/integration/agent-runtime/channel-message-source.js +19 -1
- package/dist/integration/index.d.ts +2 -0
- package/dist/integration/index.js +1 -0
- package/dist/integration/observability/loop-watchdog.d.ts +56 -0
- package/dist/integration/observability/loop-watchdog.js +177 -0
- package/dist/integration/observability/metrics.d.ts +3 -0
- package/dist/integration/observability/metrics.js +18 -7
- package/dist/integration/providers/anthropic.d.ts +23 -0
- package/dist/integration/providers/anthropic.js +97 -12
- package/dist/integration/providers/fetch-timeout.d.ts +42 -0
- package/dist/integration/providers/fetch-timeout.js +51 -0
- package/dist/integration/providers/openai.d.ts +10 -0
- package/dist/integration/providers/openai.js +58 -11
- package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
- package/dist/integration/providers/provider-diagnostics.js +89 -0
- package/dist/integration/providers/timeout-coherence.d.ts +52 -0
- package/dist/integration/providers/timeout-coherence.js +68 -0
- package/dist/integration/providers/wire-dump.d.ts +62 -0
- package/dist/integration/providers/wire-dump.js +111 -2
- package/dist/integration/storage/jsonl.js +4 -1
- package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
- package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
- package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
- package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
- package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
- package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
- package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
- package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
- package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
- package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
- package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
- package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
- package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
- package/package.json +8 -2
|
@@ -14,8 +14,11 @@ import { getTextContent } from '@octopi-agent/core/types.js';
|
|
|
14
14
|
import { tightenSessionRights } from '../governance/session-acl/rights.js';
|
|
15
15
|
import { createSessionStateMachine } from '../session/state-machine.js';
|
|
16
16
|
import { HeuristicTokenEstimator } from '../context/index.js';
|
|
17
|
+
import { OpsAuditJournal, OpsAuditFileExportSink } from '../extension/execution-environment/ops-audit.js';
|
|
18
|
+
import { getOctopiHome } from '../../paths.js';
|
|
17
19
|
import { extractLayerQuery } from '../context/layer-types.js';
|
|
18
20
|
import { formatTurnEndContent, formatTurnId, formatTurnStartContent, formatTurnContextXml, isTurnStartContent, joinSlotXml, parseTurnIdFromContent, } from '../context/turn-envelope.js';
|
|
21
|
+
import { collectRunAssistantTexts } from '../memory/wisdom-attribution.js';
|
|
19
22
|
import { splitRuntimeEnvironmentInjection, withRuntimeEnvironmentInjection } from '../context/runtime-datetime.js';
|
|
20
23
|
import { loadRootInstructionsInjection } from '../context/root-instructions.js';
|
|
21
24
|
import { extractTaskQueryHints, renderSessionTasksInjection } from '../session/tasks/render.js';
|
|
@@ -28,6 +31,12 @@ import { readSessionCompact, writeSessionCompact } from '../session/compact.js';
|
|
|
28
31
|
import { InProcessSessionLock, } from './concurrency/session-lease.js';
|
|
29
32
|
import { isToolPermitted } from '../governance/session-acl/tool-rights.js';
|
|
30
33
|
import { resolveToolCapabilities } from '../extension/execution-environment/tool-capabilities.js';
|
|
34
|
+
/**
|
|
35
|
+
* 失败凭证消息中附带残句的截断上限(显示用途;完整残句在带 error 标记的 turn 账本)
|
|
36
|
+
*
|
|
37
|
+
* 展示型截断,与 wire-dump 的消息截断同性质——不是部署可变参数,故不进配置。
|
|
38
|
+
*/
|
|
39
|
+
export const LLM_ERROR_PARTIAL_MAX_CHARS = 2000;
|
|
31
40
|
const DEFAULT_CONFIG = {
|
|
32
41
|
// idleExpiryMs 缺省关闭:上下文租约 opt-in,续聊默认带全量窗口
|
|
33
42
|
};
|
|
@@ -73,6 +82,16 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
73
82
|
sessionId: meta.sessionId,
|
|
74
83
|
data: { ...event.data },
|
|
75
84
|
};
|
|
85
|
+
case 'model_retry':
|
|
86
|
+
// 重试窗口对用户可见:52 分钟停滞期间前端零反馈,正是因为重试不产生任何事件。
|
|
87
|
+
// 不改 stopReason——重试不是终态,是否真停仍由 loopEndReason 决定。
|
|
88
|
+
return {
|
|
89
|
+
type: 'engine.model_retry',
|
|
90
|
+
timestamp: event.timestamp,
|
|
91
|
+
agentId: meta.agentId,
|
|
92
|
+
sessionId: meta.sessionId,
|
|
93
|
+
data: { ...event.data },
|
|
94
|
+
};
|
|
76
95
|
case 'agent_start':
|
|
77
96
|
return { type: 'engine.start', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: {} };
|
|
78
97
|
case 'agent_end':
|
|
@@ -80,7 +99,10 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
80
99
|
state.loopEndReason = event.reason;
|
|
81
100
|
// reason='error' 时映射为 engine.error(向后兼容旧引擎行为)
|
|
82
101
|
if (event.reason === 'error') {
|
|
83
|
-
|
|
102
|
+
const errorText = event.error instanceof Error ? event.error.message : String(event.error ?? 'Unknown error');
|
|
103
|
+
// 收口要落失败凭证(runStopped 消息);不在此留痕的话,重载会话后事故无影无踪
|
|
104
|
+
state.errorMessage = errorText;
|
|
105
|
+
return { type: 'engine.error', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: { error: errorText } };
|
|
84
106
|
}
|
|
85
107
|
return { type: 'engine.end', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: { reason: event.reason } };
|
|
86
108
|
case 'turn_start':
|
|
@@ -88,16 +110,25 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
88
110
|
return { type: 'iteration.start', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: {} };
|
|
89
111
|
case 'assistant_message':
|
|
90
112
|
state.assistantContent = typeof event.message.content === 'string' ? event.message.content : '';
|
|
113
|
+
// 完整消息已定稿,本次调用的部分流出功成身退(不得与正文叠加)
|
|
114
|
+
state.callStreamedContent = '';
|
|
91
115
|
return null;
|
|
92
|
-
case 'turn_end':
|
|
116
|
+
case 'turn_end': {
|
|
93
117
|
// phase 透传给 UI:pre_tools ≠ 本轮 run 结束(见 architecture.md)
|
|
118
|
+
// 正文口径:优先完整消息;失败轮(error=true)只有本次调用的部分流出,
|
|
119
|
+
// 不得回落到上一次调用的回复冒充本次输出
|
|
120
|
+
const turnContent = state.assistantContent || state.callStreamedContent || '';
|
|
121
|
+
state.lastTurnContent = turnContent;
|
|
122
|
+
state.lastTurnError = Boolean(event.error);
|
|
123
|
+
state.assistantContent = '';
|
|
124
|
+
state.callStreamedContent = '';
|
|
94
125
|
return {
|
|
95
126
|
type: 'turn.end',
|
|
96
127
|
timestamp: Date.now(),
|
|
97
128
|
agentId: meta.agentId,
|
|
98
129
|
sessionId: meta.sessionId,
|
|
99
130
|
data: {
|
|
100
|
-
content:
|
|
131
|
+
content: turnContent,
|
|
101
132
|
userText: state.lastUserContent ?? '',
|
|
102
133
|
hasToolCalls: event.hasToolCalls,
|
|
103
134
|
phase: event.phase,
|
|
@@ -107,7 +138,9 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
107
138
|
llmTiming: event.llmTiming,
|
|
108
139
|
},
|
|
109
140
|
};
|
|
141
|
+
}
|
|
110
142
|
case 'llm_stream_delta':
|
|
143
|
+
state.callStreamedContent = (state.callStreamedContent ?? '') + String(event.data?.delta ?? '');
|
|
111
144
|
return { type: 'llm_stream_delta', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: event.data };
|
|
112
145
|
case 'llm_thinking_delta':
|
|
113
146
|
return { type: 'llm_thinking_delta', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: event.data };
|
|
@@ -233,6 +266,8 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
233
266
|
export class SessionAwareRunner {
|
|
234
267
|
/** 本 Runner 生效的 L2 级别(由 effectPolicy 展开) */
|
|
235
268
|
effectPathContainment = "none";
|
|
269
|
+
effectRefuseFinalSymlink = false;
|
|
270
|
+
effectPathDenylist = [];
|
|
236
271
|
effectChannel = "engine";
|
|
237
272
|
effectAllowRoots = [];
|
|
238
273
|
/** Effective effectPolicy.mode (for Runtime injection / UI) */
|
|
@@ -243,6 +278,27 @@ export class SessionAwareRunner {
|
|
|
243
278
|
effectProcessLimits = true;
|
|
244
279
|
effectNetwork;
|
|
245
280
|
effectRequireJail;
|
|
281
|
+
/** ops P0:jail 意图(auto/require/none)——none=授权无笼 */
|
|
282
|
+
effectJail;
|
|
283
|
+
/** ops P2:审计账本开关(effectPolicy.opsAudit;未解析时回落配置缺省 on) */
|
|
284
|
+
/** ops P3:提权策略(resolved;priv_exec 全等匹配面) */
|
|
285
|
+
effectEscalation;
|
|
286
|
+
/** ops P4:危险命令减速带 resolved(§6;full 档 pre-exec 闸 + 确认超时) */
|
|
287
|
+
effectDangerousCommands;
|
|
288
|
+
/** ops P4:特权部署标记(jail=none / full 档 / root 进程)——UI 常驻 PRIVILEGED 数据源 */
|
|
289
|
+
effectPrivileged;
|
|
290
|
+
/** ops P5:kill switch 哨兵路径(run 准入已查;逐工具闸复用同面) */
|
|
291
|
+
killSwitchPaths = [];
|
|
292
|
+
/** ops P2:审计账本开关(effectPolicy.opsAudit;未解析时回落配置缺省 on) */
|
|
293
|
+
effectOpsAudit;
|
|
294
|
+
/** ops P2:hash 链审计账本(懒建;写失败降级申报,不吞) */
|
|
295
|
+
opsJournal;
|
|
296
|
+
/** ops P5:审计外送收口(宿主侧见证副本;未配置则不外送) */
|
|
297
|
+
opsExporter;
|
|
298
|
+
/** ops P2:账本缺省文件名的 agent 锚(每 runner 单 agent;handle 起点锚定) */
|
|
299
|
+
opsAuditAgentId;
|
|
300
|
+
/** ops P2:审计事件的 session 归属(写失败申报等无 run 载荷时用) */
|
|
301
|
+
opsAuditSessionId;
|
|
246
302
|
effectRequireCredentialBindings = false;
|
|
247
303
|
effectHomeWrite;
|
|
248
304
|
effectShellEscape = "allow";
|
|
@@ -275,6 +331,8 @@ export class SessionAwareRunner {
|
|
|
275
331
|
systemPromptAssembler;
|
|
276
332
|
/** Assembler 层缓存清理钩子(可选接线;与 contextDetachIndex 无关) */
|
|
277
333
|
systemPromptAssemblerClear;
|
|
334
|
+
/** Wisdom 归因窗口记账钩子(学习环;不是观测通道,失败不得影响 run 收口) */
|
|
335
|
+
wisdomAttributionSink;
|
|
278
336
|
/** turn 级 Knowledge grounding(可选;arch/knowledge-layer.md §4.4) */
|
|
279
337
|
groundingAssembler;
|
|
280
338
|
/** 模型快照解析器(Gateway 注入;每 run 只调一次) */
|
|
@@ -289,6 +347,81 @@ export class SessionAwareRunner {
|
|
|
289
347
|
this._observerHub = config?.observerHub;
|
|
290
348
|
this.resolveModelOverride = config?.resolveModelOverride;
|
|
291
349
|
}
|
|
350
|
+
/**
|
|
351
|
+
* ops 审计记账(ops P2):写 hash 链账本。
|
|
352
|
+
*
|
|
353
|
+
* `opsAudit: off` 时整体静默(宿主的显式选择);写失败降级为 securityDegraded
|
|
354
|
+
* 申报——P2 不 fail-closed 业务(与 §5.6 记账同策略),P3 提权通道再收紧为硬前置。
|
|
355
|
+
*
|
|
356
|
+
* @param event - §7 事件词表
|
|
357
|
+
* @param data - 事件载荷(hash 走 canonicalJson,键序无关)
|
|
358
|
+
*/
|
|
359
|
+
recordOpsAudit(event, data) {
|
|
360
|
+
if ((this.effectOpsAudit ?? this.config.effectPolicy?.opsAudit ?? 'on') !== 'on')
|
|
361
|
+
return;
|
|
362
|
+
if (!this.opsJournal) {
|
|
363
|
+
// 缺省按 agent 分文件:多 agent 并发追加同一文件会共享 tail → seq 撞号,
|
|
364
|
+
// verify 会误报断裂。分文件 = 各自单写者,链严格成立。
|
|
365
|
+
const path = this.config.effectPolicy?.opsAuditPath ??
|
|
366
|
+
this.config.opsAuditPath ??
|
|
367
|
+
join(getOctopiHome(), 'audit', `ops.${this.opsAuditAgentId ?? 'unknown'}.jsonl`);
|
|
368
|
+
this.opsJournal = new OpsAuditJournal({ path });
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
const entry = this.opsJournal.append(event, data);
|
|
372
|
+
// ops P5 审计外送(原则 8:唯一不可抵赖档):本地链防改写,外送防尾部截断/删除。
|
|
373
|
+
// 外送失败不回滚本地账(已落链),但必须降级申报——丢外送就是丢不可抵赖性。
|
|
374
|
+
const exporter = this.resolveOpsExporter();
|
|
375
|
+
if (exporter) {
|
|
376
|
+
try {
|
|
377
|
+
exporter.forward({
|
|
378
|
+
count: entry.seq,
|
|
379
|
+
tailHash: entry.hash,
|
|
380
|
+
entry,
|
|
381
|
+
forwardedAt: Date.now(),
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch (exportErr) {
|
|
385
|
+
this.noteOpsDegradation(`ops_audit_export_failed: ${exportErr instanceof Error ? exportErr.message : String(exportErr)}`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
catch (err) {
|
|
390
|
+
// 只吞「写失败」这一类,转成降级申报;账本损坏(ops_audit_corrupt)同样走这里。
|
|
391
|
+
this.noteOpsDegradation(`ops_audit_write_failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
/** 外送收口(懒建;仅配置了宿主侧收口路径时启用) */
|
|
395
|
+
resolveOpsExporter() {
|
|
396
|
+
const exportPath = this.config.effectPolicy?.opsAuditExportPath ?? this.config.opsAuditExportPath;
|
|
397
|
+
if (!exportPath)
|
|
398
|
+
return undefined;
|
|
399
|
+
if (!this.opsExporter) {
|
|
400
|
+
this.opsExporter = new OpsAuditFileExportSink({ path: exportPath });
|
|
401
|
+
}
|
|
402
|
+
return this.opsExporter;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* 审计链路降级申报(写失败/外送失败)。
|
|
406
|
+
* 双通道:harness 字段会被下一次 run 起点重置抹掉,必须同时发在线事件(评审实证)。
|
|
407
|
+
*/
|
|
408
|
+
noteOpsDegradation(reason) {
|
|
409
|
+
this.harness.securityDegraded = [
|
|
410
|
+
...(this.harness.securityDegraded ?? []),
|
|
411
|
+
reason,
|
|
412
|
+
];
|
|
413
|
+
this.emitObserved({
|
|
414
|
+
type: 'ops.policy.degraded',
|
|
415
|
+
timestamp: Date.now(),
|
|
416
|
+
agentId: this.opsAuditAgentId,
|
|
417
|
+
sessionId: this.opsAuditSessionId,
|
|
418
|
+
data: {
|
|
419
|
+
degradation: [reason],
|
|
420
|
+
requestedVsEffective: { requestedMode: 'n/a', mode: 'n/a' },
|
|
421
|
+
origin: { sessionId: this.opsAuditSessionId, agentId: this.opsAuditAgentId ?? '' },
|
|
422
|
+
},
|
|
423
|
+
});
|
|
424
|
+
}
|
|
292
425
|
/**
|
|
293
426
|
* 注入 Observer Hub(Gateway / 测试用)
|
|
294
427
|
*
|
|
@@ -374,6 +507,11 @@ export class SessionAwareRunner {
|
|
|
374
507
|
setToolContextProvider(provider) {
|
|
375
508
|
this.toolContextProvider = provider;
|
|
376
509
|
}
|
|
510
|
+
steeringProvider;
|
|
511
|
+
/** 注册一个运行期提示源(只进 steering 接缝);单槽,后注册者覆盖前注册者。 */
|
|
512
|
+
setSteeringProvider(provider) {
|
|
513
|
+
this.steeringProvider = provider;
|
|
514
|
+
}
|
|
377
515
|
/**
|
|
378
516
|
* 设置 persona 解析器
|
|
379
517
|
*
|
|
@@ -405,12 +543,23 @@ export class SessionAwareRunner {
|
|
|
405
543
|
this.systemPromptAssembler = assembler;
|
|
406
544
|
this.systemPromptAssemblerClear = clearSession;
|
|
407
545
|
}
|
|
546
|
+
/**
|
|
547
|
+
* 注入 Wisdom 归因窗口记账(run 收尾;学习环)
|
|
548
|
+
*/
|
|
549
|
+
setWisdomAttributionSink(sink) {
|
|
550
|
+
this.wisdomAttributionSink = sink;
|
|
551
|
+
}
|
|
408
552
|
/**
|
|
409
553
|
* 注入 turn 级 Knowledge grounding(可选)
|
|
410
554
|
*/
|
|
411
555
|
setGroundingAssembler(assembler) {
|
|
412
556
|
this.groundingAssembler = assembler;
|
|
413
557
|
}
|
|
558
|
+
/** 通知委派服务:结果已真正写入父上下文,而非仅仅发进事件总线。 */
|
|
559
|
+
setDelegationDeliveryAck(ack) {
|
|
560
|
+
this.delegationDeliveryAck = ack;
|
|
561
|
+
}
|
|
562
|
+
delegationDeliveryAck;
|
|
414
563
|
/**
|
|
415
564
|
* 处理一条消息
|
|
416
565
|
*
|
|
@@ -420,7 +569,7 @@ export class SessionAwareRunner {
|
|
|
420
569
|
* @param signal - 中止信号
|
|
421
570
|
* @yields AgentEvent 事件流(向后兼容格式)
|
|
422
571
|
*/
|
|
423
|
-
async *handle(sessionId, input, runConfig, signal) {
|
|
572
|
+
async *handle(sessionId, input, runConfig, signal, inboxBinding, initialInboxEntry) {
|
|
424
573
|
/** 本轮文件 undo(L3);中止保留,其余出口 commit */
|
|
425
574
|
let turnFileUndo;
|
|
426
575
|
// run 收口计时(`[timing]` 探针转正,F3):wait/build/run_end 走 eventSink → trace
|
|
@@ -458,6 +607,7 @@ export class SessionAwareRunner {
|
|
|
458
607
|
gateRelease?.();
|
|
459
608
|
return;
|
|
460
609
|
}
|
|
610
|
+
let inboxRun;
|
|
461
611
|
// run.timing 先落 trace(eventSink 时序保真);Hub 侧投递推迟到 recordRunStart 之后——
|
|
462
612
|
// 否则 run_start/context_ready 早于 run 记录创建,会被 ingestEvent 归到上一轮 run
|
|
463
613
|
const pendingObservedTimings = [];
|
|
@@ -468,8 +618,22 @@ export class SessionAwareRunner {
|
|
|
468
618
|
agentId: runConfig.agentId ?? 'default',
|
|
469
619
|
data: { stage: 'run_start', waitMs: Date.now() - timingRunEnter },
|
|
470
620
|
};
|
|
471
|
-
|
|
472
|
-
|
|
621
|
+
try {
|
|
622
|
+
inboxRun = inboxBinding
|
|
623
|
+
? inboxBinding.inbox.open(sessionId, runConfig.agentId ?? 'default', inboxBinding.runId, inboxBinding.entries, { model: runConfig.model, provider: runConfig.modelProvider })
|
|
624
|
+
: undefined;
|
|
625
|
+
if (inboxRun && initialInboxEntry)
|
|
626
|
+
inboxRun.take(initialInboxEntry.id);
|
|
627
|
+
this.config.eventSink?.(runStartTiming, { sessionId, agentId: runConfig.agentId ?? 'default' });
|
|
628
|
+
pendingObservedTimings.push(runStartTiming);
|
|
629
|
+
}
|
|
630
|
+
catch (err) {
|
|
631
|
+
// open/eventSink 抛错不得跳过 release:否则锁泄漏 + inbox active 永不清(评审 F7)
|
|
632
|
+
inboxRun?.close();
|
|
633
|
+
release();
|
|
634
|
+
gateRelease?.();
|
|
635
|
+
throw err;
|
|
636
|
+
}
|
|
473
637
|
// buildMs 从拿锁后起算(含 wait 会双重计时;F3-d 耗时区按分段展示)
|
|
474
638
|
const runStartTs = Date.now();
|
|
475
639
|
const _agentId = runConfig.agentId ?? 'default';
|
|
@@ -477,6 +641,10 @@ export class SessionAwareRunner {
|
|
|
477
641
|
let observerRunId = '';
|
|
478
642
|
let observerFinalMessages;
|
|
479
643
|
let observerEndReason;
|
|
644
|
+
/** Wisdom 归因窗口素材(装配时抓 sources/query,收尾时切本轮 assistant 文本) */
|
|
645
|
+
let wisdomInjectedIds = [];
|
|
646
|
+
let runQueryText = '';
|
|
647
|
+
let runMessagesBase = 0;
|
|
480
648
|
/**
|
|
481
649
|
* 桥接状态(assistant 文本 / 停止原因)。
|
|
482
650
|
*
|
|
@@ -549,9 +717,24 @@ export class SessionAwareRunner {
|
|
|
549
717
|
this.config.sessionTaskService?.attachSession(session);
|
|
550
718
|
// 4c. turn 信封:补闭上一 turn;分配本 turn id(t1,t2,… 会话内单调)
|
|
551
719
|
this.ensurePreviousTurnClosed(session);
|
|
552
|
-
|
|
553
|
-
const
|
|
720
|
+
// 计数器污染防护:非数值(NaN/null 经 JSON 往返)一律回退 0,防 'tNaN' 与静默复用
|
|
721
|
+
const prevTurnSeq = Number(session.metadata?.turnSeq ?? 0);
|
|
722
|
+
const turnSeq = (Number.isFinite(prevTurnSeq) ? prevTurnSeq : 0) + 1;
|
|
723
|
+
let currentTurnId = formatTurnId(turnSeq);
|
|
554
724
|
session.metadata = { ...session.metadata, turnSeq };
|
|
725
|
+
// 计数器分配即持久化:收尾整包 save 之前中断(冻结/被杀)会丢 turnSeq,
|
|
726
|
+
// 续跑随后复用已闭 turn 的 id(2026-10-28 事故链第一环)。
|
|
727
|
+
await this.persistTurnSeq(sessionId, turnSeq);
|
|
728
|
+
const closedInsertedTurnIds = new Set();
|
|
729
|
+
const allocateInsertedTurnId = async () => {
|
|
730
|
+
// consumeMessages 目前被 Loop 串行 await 调用(单消费者);若未来并发化,
|
|
731
|
+
// 这里的 read-increment-write 会双分配同 seq——并发前必须换原子分配
|
|
732
|
+
const prevSeq = Number(session.metadata?.turnSeq ?? 0);
|
|
733
|
+
const seq = (Number.isFinite(prevSeq) ? prevSeq : 0) + 1;
|
|
734
|
+
session.metadata = { ...session.metadata, turnSeq: seq };
|
|
735
|
+
await this.persistTurnSeq(sessionId, seq);
|
|
736
|
+
return formatTurnId(seq);
|
|
737
|
+
};
|
|
555
738
|
// 5. 追加用户消息(正文稍后一次定形为 <turn_start>)
|
|
556
739
|
session.messages.push(input);
|
|
557
740
|
session.meta.lastInteractionAt = Date.now();
|
|
@@ -639,12 +822,69 @@ export class SessionAwareRunner {
|
|
|
639
822
|
// P3:effectPolicy → L2 path containment + session 临时 root
|
|
640
823
|
// 必须在 Runtime 注入之前,system prompt 才能带上 allowRoots / effectMode
|
|
641
824
|
{
|
|
642
|
-
|
|
825
|
+
// ops P2:账本 agent/session 锚先于首笔账(漂移记录)落定
|
|
826
|
+
this.opsAuditAgentId = _agentId;
|
|
827
|
+
this.opsAuditSessionId = sessionId;
|
|
828
|
+
// ops P2 §4.3/§8.4:安全配置漂移守卫——先于解析与探测判定(漂移是配置事实)。
|
|
829
|
+
// 漂移 = 拒新 run + ops.config.security_changed,直至宿主重启/署名确认。
|
|
830
|
+
const integrity = await this.config.securityIntegrity?.recheck();
|
|
831
|
+
if (integrity && !integrity.ok) {
|
|
832
|
+
const driftData = {
|
|
833
|
+
changed: integrity.changed,
|
|
834
|
+
action: 'refuse_new_run',
|
|
835
|
+
// §7 要的旧→新摘要 + 来源/署名态:谁改的无法从文件判定(agent 写 vs 宿主写
|
|
836
|
+
// 同样是磁盘字节),如实记 unattributed + 未署名
|
|
837
|
+
previousFingerprint: this.config.securityIntegrity?.fingerprint ?? null,
|
|
838
|
+
currentFingerprint: integrity.currentFingerprint ?? null,
|
|
839
|
+
source: 'unattributed',
|
|
840
|
+
hostAttested: false,
|
|
841
|
+
origin: { sessionId, agentId: _agentId },
|
|
842
|
+
};
|
|
843
|
+
this.recordOpsAudit('ops.config.security_changed', driftData);
|
|
844
|
+
this.emitObserved({
|
|
845
|
+
type: 'ops.config.security_changed',
|
|
846
|
+
timestamp: Date.now(),
|
|
847
|
+
agentId: _agentId,
|
|
848
|
+
sessionId,
|
|
849
|
+
data: { ...driftData },
|
|
850
|
+
});
|
|
851
|
+
throw new Error(`security_config_drift: security-relevant config changed on disk outside the console channel (changed: ${integrity.changed.join(', ')}); ` +
|
|
852
|
+
`restart required to re-attest (restart adopts what is on disk — treat the human restart as the attestation act). ` +
|
|
853
|
+
`Console/WebUI config writes re-attest automatically; this drift means the file was edited directly, bypassing the console`);
|
|
854
|
+
}
|
|
855
|
+
// ops P5 kill switch:宿主侧急停哨兵——run 准入即拒(不依赖 LLM 判断/agent 合作)
|
|
856
|
+
{
|
|
857
|
+
const { checkKillSwitch, defaultKillSwitchPath } = await import('../extension/execution-environment/kill-switch.js');
|
|
858
|
+
this.killSwitchPaths = [
|
|
859
|
+
this.config.killSwitchPath ?? defaultKillSwitchPath(_agentId),
|
|
860
|
+
];
|
|
861
|
+
const killState = checkKillSwitch(this.killSwitchPaths);
|
|
862
|
+
if (killState.engaged) {
|
|
863
|
+
const killData = {
|
|
864
|
+
path: killState.path,
|
|
865
|
+
action: 'refuse_run',
|
|
866
|
+
origin: { sessionId, agentId: _agentId },
|
|
867
|
+
};
|
|
868
|
+
this.recordOpsAudit('ops.kill_switch.tripped', killData);
|
|
869
|
+
this.emitObserved({
|
|
870
|
+
type: 'ops.kill_switch.tripped',
|
|
871
|
+
timestamp: Date.now(),
|
|
872
|
+
agentId: _agentId,
|
|
873
|
+
sessionId,
|
|
874
|
+
data: { ...killData },
|
|
875
|
+
});
|
|
876
|
+
throw new Error(`kill_switch_active: agent execution is halted by the host sentinel (${killState.path}); ` +
|
|
877
|
+
`remove it (\`octopi ops revive <agentId>\`) to resume`);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
const { resolveEffectiveEffectPolicy, readSessionEffectOverrides, mergeTransactionRoots, requiresJail, buildOpsJailState, } = await import('../extension/execution-environment/effect-policy.js');
|
|
643
881
|
const { probeProcessIsolation } = await import('../extension/execution-environment/process-isolation.js');
|
|
644
882
|
const isolation = await probeProcessIsolation();
|
|
645
883
|
const eff = resolveEffectiveEffectPolicy(this.config.effectPolicy ?? {}, this.config.agentWorkspace ?? effectiveRunConfig.cwd ?? undefined, isolation);
|
|
646
884
|
const sessionExtraRoots = readSessionEffectOverrides(session.metadata).transactionRoots;
|
|
647
885
|
this.effectPathContainment = eff.pathContainment;
|
|
886
|
+
this.effectRefuseFinalSymlink = eff.refuseFinalSymlink;
|
|
887
|
+
this.effectPathDenylist = eff.pathDenylist;
|
|
648
888
|
this.effectChannel = eff.effects;
|
|
649
889
|
this.effectAllowRoots = mergeTransactionRoots(eff.allowRoots, sessionExtraRoots);
|
|
650
890
|
this.effectMode = eff.mode;
|
|
@@ -653,16 +893,61 @@ export class SessionAwareRunner {
|
|
|
653
893
|
this.effectShellEscape = eff.shellEscape;
|
|
654
894
|
this.effectShellJournal = eff.shellJournal;
|
|
655
895
|
this.effectNetwork = eff.network;
|
|
896
|
+
this.effectJail = eff.jail;
|
|
897
|
+
this.effectEscalation = eff.escalation;
|
|
898
|
+
this.effectDangerousCommands = eff.dangerousCommands;
|
|
899
|
+
// ops P4:特权部署标记 = 授权无笼 / full 档 / root·elevated 进程(§5 P4 root 部署语义)
|
|
900
|
+
{
|
|
901
|
+
const { isProcessElevated } = await import('../extension/execution-environment/privileged-exec.js');
|
|
902
|
+
this.effectPrivileged = eff.privileged || (await isProcessElevated());
|
|
903
|
+
}
|
|
656
904
|
this.effectRequireJail = requiresJail(eff);
|
|
905
|
+
// 严格凭证绑定只跟 untrusted 承诺走(历史语义):jail=require/refuse 不得
|
|
906
|
+
// 悄悄改变 host/project 的凭证行为
|
|
657
907
|
this.effectRequireCredentialBindings =
|
|
658
|
-
this.config.requireCredentialBindings === true ||
|
|
908
|
+
this.config.requireCredentialBindings === true ||
|
|
909
|
+
(eff.requestedMode === 'untrusted' && eff.mode === 'untrusted');
|
|
659
910
|
this.effectHomeWrite = eff.mode === 'project' || eff.mode === 'host';
|
|
660
911
|
this.effectShellJournalLimit = eff.shellJournalLimit;
|
|
661
912
|
this.effectUndoLimit = eff.undoLimit;
|
|
662
913
|
// untrusted admission: reduced surface strips egress/exec tools
|
|
663
914
|
this.harness.toolSurface = eff.toolSurface;
|
|
915
|
+
// 无条件重置(空也要写):harness 跨 run 共享,条件赋值会让上一轮的降级
|
|
916
|
+
// 粘到授权 run 上——「授权被记成降级」恰是 ops P0 要消灭的误报
|
|
917
|
+
this.harness.securityDegraded = [...eff.securityDegraded];
|
|
918
|
+
// ops P0:run 开始即记录 jail 意图 × 实测后端——「授权」与「故障」的事后判据
|
|
919
|
+
// (§4.2 ops.jail.state;不等失效才留痕)。进延迟投递队列:run 记录
|
|
920
|
+
// (recordRunStart)建立后才归档,否则 Hub 会把它挂到上一轮 run 或直接丢弃。
|
|
921
|
+
const jailState = { ...buildOpsJailState(eff, isolation) };
|
|
922
|
+
pendingObservedTimings.push({
|
|
923
|
+
type: 'ops.jail.state',
|
|
924
|
+
timestamp: Date.now(),
|
|
925
|
+
agentId: _agentId,
|
|
926
|
+
sessionId,
|
|
927
|
+
data: jailState,
|
|
928
|
+
});
|
|
929
|
+
// ops P2:账本是「事后可查」的持久面(Observer timeline 只是在线视图)
|
|
930
|
+
this.effectOpsAudit = eff.opsAudit;
|
|
931
|
+
// runId 此处尚未生成(createRunId 在工具 scope 装配前);run 归属由
|
|
932
|
+
// pendingObservedTimings → run timeline 承担,账本记 session/agent 锚点
|
|
933
|
+
this.recordOpsAudit('ops.jail.state', {
|
|
934
|
+
...jailState,
|
|
935
|
+
origin: { sessionId, agentId: _agentId },
|
|
936
|
+
});
|
|
664
937
|
if (eff.securityDegraded.length > 0) {
|
|
665
|
-
|
|
938
|
+
const degradedData = {
|
|
939
|
+
degradation: eff.securityDegraded,
|
|
940
|
+
requestedVsEffective: { requestedMode: eff.requestedMode, mode: eff.mode },
|
|
941
|
+
origin: { sessionId, agentId: _agentId },
|
|
942
|
+
};
|
|
943
|
+
this.recordOpsAudit('ops.policy.degraded', degradedData);
|
|
944
|
+
pendingObservedTimings.push({
|
|
945
|
+
type: 'ops.policy.degraded',
|
|
946
|
+
timestamp: Date.now(),
|
|
947
|
+
agentId: _agentId,
|
|
948
|
+
sessionId,
|
|
949
|
+
data: { ...degradedData },
|
|
950
|
+
});
|
|
666
951
|
}
|
|
667
952
|
}
|
|
668
953
|
// Runtime 锚点:时间 + 工具工作目录 + 允许根/效应模式
|
|
@@ -798,6 +1083,12 @@ export class SessionAwareRunner {
|
|
|
798
1083
|
: null;
|
|
799
1084
|
if (assembled.manifest) {
|
|
800
1085
|
const assembledAt = Date.now();
|
|
1086
|
+
const layerQuery = extractLayerQuery(session.messages, { topicHints });
|
|
1087
|
+
// 归因窗口素材(学习环,非观测):本轮 wisdom sources + query + 消息基线
|
|
1088
|
+
wisdomInjectedIds =
|
|
1089
|
+
assembled.manifest.layers.find((l) => l.id === 'wisdom')?.sources ?? [];
|
|
1090
|
+
runQueryText = layerQuery;
|
|
1091
|
+
runMessagesBase = session.messages.length;
|
|
801
1092
|
this.emitObserved({
|
|
802
1093
|
type: 'context.layers.assembled',
|
|
803
1094
|
timestamp: assembledAt,
|
|
@@ -808,7 +1099,7 @@ export class SessionAwareRunner {
|
|
|
808
1099
|
agentId: _agentId,
|
|
809
1100
|
manifest: assembled.manifest,
|
|
810
1101
|
enabledLayerIds: assembled.manifest.layers.map((l) => l.id),
|
|
811
|
-
query:
|
|
1102
|
+
query: layerQuery,
|
|
812
1103
|
assembledAt,
|
|
813
1104
|
},
|
|
814
1105
|
});
|
|
@@ -925,7 +1216,16 @@ export class SessionAwareRunner {
|
|
|
925
1216
|
: undefined;
|
|
926
1217
|
turnFileUndo = fileUndo;
|
|
927
1218
|
const { createUnconfiguredMemoryEffects: unconfMem, resolveSessionUndoPaths, } = await import('../extension/execution-environment/undo-log.js');
|
|
928
|
-
|
|
1219
|
+
// ops P2:效应写口集中拦截 roots 外写入 → ops.system_path.write
|
|
1220
|
+
// (单点覆盖全部文件工具与 shell 账本,不逐工具打补丁)
|
|
1221
|
+
const { OpsAuditedFileEffects } = await import('../extension/execution-environment/ops-audit.js');
|
|
1222
|
+
const fileEffects = new OpsAuditedFileEffects(fileUndo ?? createUnconfiguredFileEffects(), {
|
|
1223
|
+
// roots 为空时 L2 回退 cwd——审计判定不得比 L2 更宽(全记 system_path 是误报)
|
|
1224
|
+
roots: this.effectAllowRoots.length
|
|
1225
|
+
? this.effectAllowRoots
|
|
1226
|
+
: [resolvedToolCwd.cwd ?? baseCwd ?? process.cwd()],
|
|
1227
|
+
record: (event, data) => this.recordOpsAudit(event, data),
|
|
1228
|
+
});
|
|
929
1229
|
const memoryEffects = fileUndo?.memoryEffects ?? unconfMem();
|
|
930
1230
|
const undoRoots = this.config.sessionsDir
|
|
931
1231
|
? [resolveSessionUndoPaths(this.config.sessionsDir, sessionId).root]
|
|
@@ -951,6 +1251,7 @@ export class SessionAwareRunner {
|
|
|
951
1251
|
// 此处再判 effectMode 是等价冗余,已收编。
|
|
952
1252
|
requireCredentialBindings: this.effectRequireCredentialBindings,
|
|
953
1253
|
requireJail: this.effectRequireJail,
|
|
1254
|
+
disableJail: this.effectJail === 'none',
|
|
954
1255
|
homeWrite: this.effectHomeWrite,
|
|
955
1256
|
noteSecurityDegraded: (reason) => {
|
|
956
1257
|
this.harness.securityDegraded = [
|
|
@@ -958,14 +1259,29 @@ export class SessionAwareRunner {
|
|
|
958
1259
|
reason,
|
|
959
1260
|
];
|
|
960
1261
|
},
|
|
1262
|
+
// ops P2:工具侧动作/越权写入 → 统一审计账本(core 钩子,存储归 runner)
|
|
1263
|
+
recordOpsEvent: (record) => {
|
|
1264
|
+
this.recordOpsAudit(record.event, record.data);
|
|
1265
|
+
},
|
|
961
1266
|
pathRoots: this.effectAllowRoots.length
|
|
962
1267
|
? this.effectAllowRoots
|
|
963
1268
|
: resolvedToolCwd.cwd
|
|
964
1269
|
? [resolvedToolCwd.cwd]
|
|
965
1270
|
: undefined,
|
|
966
1271
|
pathContainment: this.effectPathContainment,
|
|
1272
|
+
refuseFinalSymlink: this.effectRefuseFinalSymlink,
|
|
1273
|
+
pathDenylist: this.effectPathDenylist,
|
|
967
1274
|
confirmEffect: this.config.confirmEffect,
|
|
968
1275
|
effectChannel: this.effectChannel,
|
|
1276
|
+
escalation: this.effectEscalation,
|
|
1277
|
+
dangerousCommands: this.effectDangerousCommands,
|
|
1278
|
+
privileged: this.effectPrivileged,
|
|
1279
|
+
// ops P5「参与者身份入账」:提权请求/拒绝审计的 requester 载荷(SEC-2 角色绑定)
|
|
1280
|
+
sessionParticipants: session.participants?.map((p) => ({
|
|
1281
|
+
agentId: p.agentId,
|
|
1282
|
+
roleId: p.roleId,
|
|
1283
|
+
})),
|
|
1284
|
+
killSwitchPaths: this.killSwitchPaths,
|
|
969
1285
|
processLimits: this.effectProcessLimits,
|
|
970
1286
|
shellEscape: this.effectShellEscape,
|
|
971
1287
|
shellJournal: this.effectShellJournal,
|
|
@@ -1070,6 +1386,12 @@ export class SessionAwareRunner {
|
|
|
1070
1386
|
// 定形随 loop 事件增量同步)。写失败不中断 Run(收尾 save 是权威写),
|
|
1071
1387
|
// 失败不推进已同步计数,下个事件重试。
|
|
1072
1388
|
const firstSynced = await this.persistRunMessages(sessionId, _agentId, contextLeasePrefix, runContext.messages);
|
|
1389
|
+
if (firstSynced && initialInboxEntry) {
|
|
1390
|
+
inboxRun?.inbox.ack(initialInboxEntry);
|
|
1391
|
+
const delegationId = initialInboxEntry.message.metadata?.delegationId;
|
|
1392
|
+
if (typeof delegationId === 'string')
|
|
1393
|
+
this.delegationDeliveryAck?.(delegationId);
|
|
1394
|
+
}
|
|
1073
1395
|
let syncedMessageCount = firstSynced ? runContext.messages.length : 0;
|
|
1074
1396
|
// Observer 通道:Run 现场快照(摘要进事件;全文由 Hub/REST 提供)
|
|
1075
1397
|
if (this._observerHub?.isEnabled()) {
|
|
@@ -1137,11 +1459,81 @@ export class SessionAwareRunner {
|
|
|
1137
1459
|
let turnStartIndex = runContext.messages.length;
|
|
1138
1460
|
/** 用户中止(编辑重发标记用) */
|
|
1139
1461
|
let runAborted = false;
|
|
1462
|
+
/** 被接续消息的收尾通道(频道回复捕获等);消费后转发本 Run 全部事件 */
|
|
1463
|
+
const entryObservers = new Set();
|
|
1140
1464
|
// resolvedModel 已在 system assembler 之前解析;此处只组装 run options
|
|
1465
|
+
/** 已入 Run 视图、待转录同步确认的 inbox 条目(ack = 入上下文 + 同步成功) */
|
|
1466
|
+
const pendingInboxAcks = [];
|
|
1467
|
+
const flushInboxAcks = () => {
|
|
1468
|
+
for (const entry of pendingInboxAcks.splice(0)) {
|
|
1469
|
+
inboxRun?.inbox.ack(entry);
|
|
1470
|
+
const delegationId = entry.message.metadata?.delegationId;
|
|
1471
|
+
if (typeof delegationId === 'string')
|
|
1472
|
+
this.delegationDeliveryAck?.(delegationId);
|
|
1473
|
+
}
|
|
1474
|
+
};
|
|
1141
1475
|
const agentRunOptions = {
|
|
1142
1476
|
resolvedModel: resolvedModel ?? undefined,
|
|
1143
1477
|
context: runContext,
|
|
1144
1478
|
runScope,
|
|
1479
|
+
consumeMessages: async () => {
|
|
1480
|
+
const injected = [];
|
|
1481
|
+
if (inboxRun) {
|
|
1482
|
+
for (const entry of inboxRun.drain()) {
|
|
1483
|
+
// 每条注入输入(人话 / 委派结果)开启自己的 turn:
|
|
1484
|
+
// 先闭上一 turn(write-once),再一次定形新 turn 信封(与 wake 路径同构)。
|
|
1485
|
+
// 有序序列交还 Loop 统一 push 进 context.messages(不在此处直接入数组)。
|
|
1486
|
+
injected.push(this.makeTurnEndMessage(currentTurnId));
|
|
1487
|
+
closedInsertedTurnIds.add(currentTurnId);
|
|
1488
|
+
currentTurnId = await allocateInsertedTurnId();
|
|
1489
|
+
entry.message.metadata = { ...entry.message.metadata, turnId: currentTurnId };
|
|
1490
|
+
// 注入 turn 也带 runtime_snapshot(datetime 等);附件/grounding 属 turn 1,不重复
|
|
1491
|
+
this.bakeTurnStart(entry.message, currentTurnId, formatTurnContextXml({
|
|
1492
|
+
turnId: currentTurnId,
|
|
1493
|
+
slotsXml: joinSlotXml([{ tag: 'runtime_snapshot', body: runtimeSnapshotText ?? '' }]),
|
|
1494
|
+
}));
|
|
1495
|
+
injected.push(entry.message);
|
|
1496
|
+
// ack 延到转录同步成功后统一 flush;同步失败/崩溃由 close 的
|
|
1497
|
+
// unacked 重投兜底(at-least-once,见 SessionInbox)
|
|
1498
|
+
pendingInboxAcks.push(entry);
|
|
1499
|
+
if (entry.onEvent)
|
|
1500
|
+
entryObservers.add(entry.onEvent);
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
if (injected.length) {
|
|
1504
|
+
this.emitObserved({
|
|
1505
|
+
type: 'session.inbox.appended',
|
|
1506
|
+
timestamp: Date.now(),
|
|
1507
|
+
sessionId,
|
|
1508
|
+
agentId: _agentId,
|
|
1509
|
+
data: {
|
|
1510
|
+
runId,
|
|
1511
|
+
count: injected.length,
|
|
1512
|
+
messages: injected
|
|
1513
|
+
.filter((m) => m.metadata?.source !== 'turnEnd')
|
|
1514
|
+
.map((m) => ({ role: m.role, content: m.content, metadata: m.metadata })),
|
|
1515
|
+
},
|
|
1516
|
+
});
|
|
1517
|
+
}
|
|
1518
|
+
return injected;
|
|
1519
|
+
},
|
|
1520
|
+
// 只读提示只进 steering 接缝:经 followUp 续命会让 run 被状态快照拖住(评审 F1)
|
|
1521
|
+
steeringExtras: async () => this.steeringProvider ? this.steeringProvider() : [],
|
|
1522
|
+
// 工具部分输出(展示通道):事件从回调直达事件出口——生成器无法在工具执行中
|
|
1523
|
+
// yield,故不进事件 yield 流(generator 消费方如通道回复捕获收不到,属预期取舍);
|
|
1524
|
+
// WS/EventBus 消费方(TUI/WebUI)经 eventSink + emitObserved 正常可见。
|
|
1525
|
+
onToolUpdate: (params) => {
|
|
1526
|
+
const { toolCall, partial } = params;
|
|
1527
|
+
const updateEvent = {
|
|
1528
|
+
type: 'tool.exec.update',
|
|
1529
|
+
timestamp: Date.now(),
|
|
1530
|
+
agentId: meta.agentId,
|
|
1531
|
+
sessionId: meta.sessionId,
|
|
1532
|
+
data: { toolCallId: toolCall.id, toolName: toolCall.name, content: partial.content },
|
|
1533
|
+
};
|
|
1534
|
+
this.config.eventSink?.(updateEvent, meta);
|
|
1535
|
+
this.emitObserved(updateEvent);
|
|
1536
|
+
},
|
|
1145
1537
|
};
|
|
1146
1538
|
for await (const loopEvent of this.agent.run(signal, undefined, agentRunOptions)) {
|
|
1147
1539
|
// 消息数组增长 = 有新消息定形/入列(流式 delta 不 push 消息,不触发)。
|
|
@@ -1150,12 +1542,16 @@ export class SessionAwareRunner {
|
|
|
1150
1542
|
if (runContext.messages.length !== syncedMessageCount) {
|
|
1151
1543
|
if (await this.persistRunMessages(sessionId, _agentId, contextLeasePrefix, runContext.messages)) {
|
|
1152
1544
|
syncedMessageCount = runContext.messages.length;
|
|
1545
|
+
// 转录同步成功 = 注入消息已入父上下文且可恢复 → 确认送达
|
|
1546
|
+
flushInboxAcks();
|
|
1153
1547
|
}
|
|
1154
1548
|
}
|
|
1155
1549
|
else if (loopEvent.type === 'turn_end') {
|
|
1156
1550
|
// 漂移兜底:turn 边界无条件对齐一次(旁路写者整包回退后即使暂无
|
|
1157
1551
|
// 新消息也能自愈;无漂移时幂等零写)
|
|
1158
|
-
await this.persistRunMessages(sessionId, _agentId, contextLeasePrefix, runContext.messages)
|
|
1552
|
+
if (await this.persistRunMessages(sessionId, _agentId, contextLeasePrefix, runContext.messages)) {
|
|
1553
|
+
flushInboxAcks();
|
|
1554
|
+
}
|
|
1159
1555
|
}
|
|
1160
1556
|
if (loopEvent.type === 'agent_end' && loopEvent.reason === 'aborted') {
|
|
1161
1557
|
runAborted = true;
|
|
@@ -1197,6 +1593,16 @@ export class SessionAwareRunner {
|
|
|
1197
1593
|
lastContextTokens = contextTokens;
|
|
1198
1594
|
lastContextWindow = effectiveRunConfig.contextWindow;
|
|
1199
1595
|
}
|
|
1596
|
+
// 被接续消息的调用方收尾通道(如频道回复捕获):转发本 Run 事件;
|
|
1597
|
+
// 单通道故障不得中断事件流
|
|
1598
|
+
for (const observer of entryObservers) {
|
|
1599
|
+
try {
|
|
1600
|
+
observer(adapted);
|
|
1601
|
+
}
|
|
1602
|
+
catch (obsErr) {
|
|
1603
|
+
console.warn(`[octopi] inbox entry observer failed: ${obsErr instanceof Error ? obsErr.message : String(obsErr)}`);
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1200
1606
|
yield adapted;
|
|
1201
1607
|
// Telemetry 旁路(含 stream delta;由 RunTelemetry 决定采样)
|
|
1202
1608
|
this.config.eventSink?.(adapted, meta);
|
|
@@ -1210,10 +1616,7 @@ export class SessionAwareRunner {
|
|
|
1210
1616
|
if (loopEvent.type === 'llm_stream_delta' && loopEvent.data?.delta) {
|
|
1211
1617
|
streamedContent += loopEvent.data.delta;
|
|
1212
1618
|
}
|
|
1213
|
-
//
|
|
1214
|
-
if (loopEvent.type === 'assistant_message') {
|
|
1215
|
-
adaptState.assistantContent = typeof loopEvent.message.content === 'string' ? loopEvent.message.content : '';
|
|
1216
|
-
}
|
|
1619
|
+
// assistantContent 由 adaptLoopEvent 在 assistant_message 事件上单一写入
|
|
1217
1620
|
// turn_start:重置本轮增量游标(afterTurn 只传本轮消息)
|
|
1218
1621
|
if (loopEvent.type === 'turn_start') {
|
|
1219
1622
|
turnStartIndex = runContext.messages.length;
|
|
@@ -1228,13 +1631,17 @@ export class SessionAwareRunner {
|
|
|
1228
1631
|
const turnMessages = runContext.messages.slice(turnStartIndex);
|
|
1229
1632
|
await this.agent.notifyAfterTurn(lastUsage, turnMessages);
|
|
1230
1633
|
turnStartIndex = runContext.messages.length;
|
|
1231
|
-
|
|
1232
|
-
|
|
1634
|
+
// 账本正文 = adaptLoopEvent 按调用算好的快照(失败轮只有本次调用的部分流出);
|
|
1635
|
+
// 失败轮必须带 error 标记,空正文也留账(审计价值),不得拿历史内容凑数
|
|
1636
|
+
const content = adaptState.lastTurnContent ?? '';
|
|
1637
|
+
const turnFailed = Boolean(adaptState.lastTurnError);
|
|
1638
|
+
if (content || turnFailed) {
|
|
1233
1639
|
session.turns.push({
|
|
1234
1640
|
id: `turn_${Date.now()}`,
|
|
1235
1641
|
inputCount: Math.max(0, session.messages.length - 1),
|
|
1236
1642
|
output: { role: 'assistant', content, timestamp: Date.now(), agentId: _agentId },
|
|
1237
|
-
usage
|
|
1643
|
+
// 失败轮没有 usage(loop 的 error turn_end 不带);不得写上一次调用的用量
|
|
1644
|
+
...(turnFailed ? { error: true } : { usage: lastUsage }),
|
|
1238
1645
|
durationMs: 0,
|
|
1239
1646
|
model: effectiveRunConfig.model ?? 'unknown',
|
|
1240
1647
|
timestamp: Date.now(),
|
|
@@ -1265,14 +1672,64 @@ export class SessionAwareRunner {
|
|
|
1265
1672
|
// 引擎主动终止(RunGuard / Budget / Security)必须留下可见凭证:
|
|
1266
1673
|
// 只有事件、没有消息时,UI 看到的就是「跑着跑着突然结束」。
|
|
1267
1674
|
//
|
|
1268
|
-
// 触发条件 = loop 的 agent_end.reason
|
|
1675
|
+
// 触发条件 = loop 的 agent_end.reason('should_stop' 引擎主动停止 / 'error' LLM 彻底失败)。
|
|
1269
1676
|
// 不能只看 stopReason:`security_blocked` 单次拦截后 run 会继续跑完,
|
|
1270
1677
|
// 那样会把正常完成的 run 误报成「已停止」。
|
|
1271
1678
|
//
|
|
1272
1679
|
// 该消息不进 LLM 上下文(buildLlmMessages 跳过 source=runStopped),
|
|
1273
1680
|
// 但进聊天回放(系统提示条)与 session 审计。
|
|
1274
1681
|
// 位置在 turn_end 之前:它属于被终止的这个 turn。
|
|
1275
|
-
if (adaptState.loopEndReason === '
|
|
1682
|
+
if (adaptState.loopEndReason === 'error') {
|
|
1683
|
+
// LLM 彻底失败同样是「无回复收尾」:必须留下可见凭证,
|
|
1684
|
+
// 否则重载会话后这次失败无影无踪(只剩一段被当成正常回复的部分文本)。
|
|
1685
|
+
const body = adaptState.errorMessage ?? '未知错误';
|
|
1686
|
+
// 残句并入凭证消息(显示用途,截断):live 视图里用户看到过的部分输出
|
|
1687
|
+
// 重载后不再消失;完整残句仍以带 error 标记的 turn 账本为准。
|
|
1688
|
+
// 最后一次尝试若以 turn_end(error) 收尾,partial 在 lastTurnContent;
|
|
1689
|
+
// 若直接 abort(无 turn_end),partial 还挂在 callStreamedContent 上。
|
|
1690
|
+
const danglingPartial = adaptState.callStreamedContent ?? '';
|
|
1691
|
+
// 回退只在「最后一个 turn 是失败轮」时启用:最终 abort 不产 turn_end 时
|
|
1692
|
+
// lastTurnContent 会停留在上一轮**成功**的正文上,直接用会把完整回复
|
|
1693
|
+
// 冒充成「中断前的部分输出」
|
|
1694
|
+
const finalPartial = danglingPartial || (adaptState.lastTurnError ? (adaptState.lastTurnContent ?? '') : '');
|
|
1695
|
+
const partialNote = finalPartial
|
|
1696
|
+
? `\n\n---\n中断前的部分输出(非完整回复):\n${finalPartial.slice(0, LLM_ERROR_PARTIAL_MAX_CHARS)}${finalPartial.length > LLM_ERROR_PARTIAL_MAX_CHARS ? '\n…(已截断,完整残句见 turn 账本)' : ''}`
|
|
1697
|
+
: '';
|
|
1698
|
+
session.messages.push({
|
|
1699
|
+
role: 'user',
|
|
1700
|
+
content: `模型调用失败:${body}。可继续对话让 agent 从当前状态接着做,或稍后重试。${partialNote}`,
|
|
1701
|
+
timestamp: Date.now(),
|
|
1702
|
+
metadata: {
|
|
1703
|
+
source: 'runStopped',
|
|
1704
|
+
turnId: currentTurnId,
|
|
1705
|
+
stopReason: 'llm_error',
|
|
1706
|
+
},
|
|
1707
|
+
});
|
|
1708
|
+
session.metadata = {
|
|
1709
|
+
...session.metadata,
|
|
1710
|
+
lastStop: {
|
|
1711
|
+
reason: 'llm_error',
|
|
1712
|
+
message: body,
|
|
1713
|
+
turnId: currentTurnId,
|
|
1714
|
+
at: Date.now(),
|
|
1715
|
+
},
|
|
1716
|
+
};
|
|
1717
|
+
// 最后一次失败尝试的 partial 也留账:abort 路径不再产 turn_end,
|
|
1718
|
+
// 此处不记的话最后尝试的输出只剩前端 live 视图(重载即失)。
|
|
1719
|
+
// 只补「无 turn_end」的缺口;turn_end(error) 路径已在账本里,不得重复记。
|
|
1720
|
+
if (hasTurnEnd && danglingPartial) {
|
|
1721
|
+
session.turns.push({
|
|
1722
|
+
id: `turn_${Date.now()}`,
|
|
1723
|
+
inputCount: Math.max(0, session.messages.length - 1),
|
|
1724
|
+
output: { role: 'assistant', content: danglingPartial, timestamp: Date.now(), agentId: _agentId },
|
|
1725
|
+
durationMs: 0,
|
|
1726
|
+
model: effectiveRunConfig.model ?? 'unknown',
|
|
1727
|
+
timestamp: Date.now(),
|
|
1728
|
+
error: true,
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
else if (adaptState.loopEndReason === 'should_stop') {
|
|
1276
1733
|
const label = adaptState.stopReason === 'behavior_stopped'
|
|
1277
1734
|
? '引擎监督器判定停止'
|
|
1278
1735
|
: adaptState.stopReason === 'policy_stopped'
|
|
@@ -1316,18 +1773,26 @@ export class SessionAwareRunner {
|
|
|
1316
1773
|
session.metadata = restMeta;
|
|
1317
1774
|
clearLastStop = true;
|
|
1318
1775
|
}
|
|
1319
|
-
// turn 闭标(write-once
|
|
1320
|
-
|
|
1776
|
+
// turn 闭标(write-once)。插话开启的旧 turn 在注入时已经闭合。
|
|
1777
|
+
if (!closedInsertedTurnIds.has(currentTurnId)) {
|
|
1778
|
+
this.appendTurnEnd(session.messages, currentTurnId);
|
|
1779
|
+
}
|
|
1321
1780
|
// 11. 引擎异常退出时的 session 一致性修复(须在 Observer final 采样之前)
|
|
1322
1781
|
if (!hasTurnEnd) {
|
|
1323
1782
|
const fallbackContent = streamedContent || '';
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1783
|
+
const failedRun = adaptState.loopEndReason === 'error';
|
|
1784
|
+
// 失败 run 空正文也留账(与 error turn_end 口径一致);正常/崩溃路径仍按有内容才记
|
|
1785
|
+
if (fallbackContent || failedRun) {
|
|
1786
|
+
// 失败 run 的部分流出不得冒充 assistant 回复入历史——失败凭证已由
|
|
1787
|
+
// runStopped 消息承担;只落一条带 error 标记的 turn 账本保留审计。
|
|
1788
|
+
if (!failedRun) {
|
|
1789
|
+
session.messages.push({
|
|
1790
|
+
role: 'assistant',
|
|
1791
|
+
content: fallbackContent,
|
|
1792
|
+
timestamp: Date.now(),
|
|
1793
|
+
agentId: _agentId,
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1331
1796
|
session.turns.push({
|
|
1332
1797
|
id: `turn_${Date.now()}`,
|
|
1333
1798
|
inputCount: Math.max(0, session.messages.length - 1),
|
|
@@ -1336,13 +1801,24 @@ export class SessionAwareRunner {
|
|
|
1336
1801
|
durationMs: 0,
|
|
1337
1802
|
model: effectiveRunConfig.model ?? 'unknown',
|
|
1338
1803
|
timestamp: Date.now(),
|
|
1804
|
+
...(failedRun ? { error: true } : {}),
|
|
1339
1805
|
});
|
|
1340
1806
|
}
|
|
1341
1807
|
}
|
|
1342
1808
|
// Observer:记录最终 messages 与 endReason(真正 close 在 finally,保证异常也闭合)
|
|
1343
1809
|
observerFinalMessages = session.messages;
|
|
1344
1810
|
// P5: 使用 stopReason 区分终态(context_stopped / behavior_stopped / policy_stopped / security_stopped / completed)
|
|
1345
|
-
|
|
1811
|
+
// LLM 错误路径只设 loopEndReason='error'、不设 stopReason;若在此回落到 hasTurnEnd,
|
|
1812
|
+
// 一次彻底失败会被记成 completed(run.timing / Observer / 指标全部失真)。
|
|
1813
|
+
observerEndReason =
|
|
1814
|
+
adaptState.stopReason ??
|
|
1815
|
+
(adaptState.loopEndReason === 'error'
|
|
1816
|
+
? 'error'
|
|
1817
|
+
: adaptState.loopEndReason === 'aborted'
|
|
1818
|
+
? 'aborted'
|
|
1819
|
+
: hasTurnEnd
|
|
1820
|
+
? 'completed'
|
|
1821
|
+
: 'no_turn_end');
|
|
1346
1822
|
// 中止标记:仅在本轮**未完成**被掐断时打标(hasTurnEnd = 正常收尾)。
|
|
1347
1823
|
// 迟到 abort / signal 竞态不得给已完成轮贴编辑重发。
|
|
1348
1824
|
let clearAbortedTurn = false;
|
|
@@ -1400,6 +1876,8 @@ export class SessionAwareRunner {
|
|
|
1400
1876
|
};
|
|
1401
1877
|
}
|
|
1402
1878
|
await this.store.save(sessionId, session);
|
|
1879
|
+
// 收尾权威写成功:剩余注入条目一并确认(此后 close 不再重投)
|
|
1880
|
+
flushInboxAcks();
|
|
1403
1881
|
if (clearAbortedTurn && this.store.updateMetadata) {
|
|
1404
1882
|
await this.store.updateMetadata(sessionId, (meta) => {
|
|
1405
1883
|
delete meta.abortedTurn;
|
|
@@ -1534,8 +2012,28 @@ export class SessionAwareRunner {
|
|
|
1534
2012
|
// 观测收口失败不阻断锁释放
|
|
1535
2013
|
}
|
|
1536
2014
|
}
|
|
2015
|
+
inboxRun?.close();
|
|
1537
2016
|
release();
|
|
1538
2017
|
gateRelease?.();
|
|
2018
|
+
// Wisdom 归因窗口记账(学习环):锁释放后再写,DB 慢不得拖住 session 锁;
|
|
2019
|
+
// 本轮注入 + 结局 + 引用摘录 → 判官批量判决。失败只告警(学习环可由下批窗口补),
|
|
2020
|
+
// 不走 eventSink/Observer——学习记账不是观测通道。
|
|
2021
|
+
if (this.wisdomAttributionSink && wisdomInjectedIds.length > 0 && observerFinalMessages) {
|
|
2022
|
+
try {
|
|
2023
|
+
await this.wisdomAttributionSink({
|
|
2024
|
+
sessionId,
|
|
2025
|
+
agentId: _agentId,
|
|
2026
|
+
outcome: runEndReason,
|
|
2027
|
+
query: runQueryText,
|
|
2028
|
+
injectedIds: wisdomInjectedIds,
|
|
2029
|
+
assistantTexts: collectRunAssistantTexts(observerFinalMessages, runMessagesBase),
|
|
2030
|
+
});
|
|
2031
|
+
}
|
|
2032
|
+
catch (err) {
|
|
2033
|
+
// 学习环静默关闭是严重问题:至少告警一次,不得只吞不报
|
|
2034
|
+
console.warn(`[Runner] wisdom attribution sink failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
1539
2037
|
}
|
|
1540
2038
|
}
|
|
1541
2039
|
/**
|
|
@@ -1568,6 +2066,8 @@ export class SessionAwareRunner {
|
|
|
1568
2066
|
messages: session.messages,
|
|
1569
2067
|
summarize: options.summarize,
|
|
1570
2068
|
compactTargetTokens: options.compactTargetTokens,
|
|
2069
|
+
// 交接式摘要素材:task 快照(裸状态块,不含对话引导语)随指令尾部注入
|
|
2070
|
+
taskSnapshot: renderSessionTasksInjection(session.tasks ?? [], { includeGuidance: false }),
|
|
1571
2071
|
});
|
|
1572
2072
|
if (result.ok && result.summary && result.compacted) {
|
|
1573
2073
|
const snap = {
|
|
@@ -1699,19 +2199,69 @@ export class SessionAwareRunner {
|
|
|
1699
2199
|
}
|
|
1700
2200
|
userMessage.metadata = { ...userMessage.metadata, turnId };
|
|
1701
2201
|
}
|
|
1702
|
-
/**
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
parseTurnIdFromContent(m.content) === turnId);
|
|
1706
|
-
if (exists) {
|
|
1707
|
-
throw new Error(`turn_end already exists (turnId=${turnId})`);
|
|
1708
|
-
}
|
|
1709
|
-
session.messages.push({
|
|
2202
|
+
/** 构造 turn 闭标消息(write-once 由调用处重复检查保证) */
|
|
2203
|
+
makeTurnEndMessage(turnId) {
|
|
2204
|
+
return {
|
|
1710
2205
|
role: 'user',
|
|
1711
2206
|
content: formatTurnEndContent(turnId),
|
|
1712
2207
|
timestamp: Date.now(),
|
|
1713
2208
|
metadata: { source: 'turnEnd', turnId },
|
|
1714
|
-
}
|
|
2209
|
+
};
|
|
2210
|
+
}
|
|
2211
|
+
/**
|
|
2212
|
+
* 追加 turn 闭标(幂等收养,按信封区间判形)。
|
|
2213
|
+
*
|
|
2214
|
+
* turn_end 是状态标记(turn 已闭)而非事件:崩溃续跑时 ensurePreviousTurnClosed
|
|
2215
|
+
* 会为上一个未闭信封补写闭标(它是第二处闭标写者,规则相近),同 id 的历史闭标
|
|
2216
|
+
* 不算「本信封已闭」——只有本信封区间(最后一个同 id turn_start 之后)已存在
|
|
2217
|
+
* 闭标才跳过。曾经的全局 write-once throw 把良性重复升级成 run error
|
|
2218
|
+
* (loop 已 completed 仍被中止,2026-10-28 事故)。
|
|
2219
|
+
*
|
|
2220
|
+
* 边界:找不到同 id turn_start(lastStartIdx=-1,如 abort-before-bake)时按
|
|
2221
|
+
* 「全序列已有一枚闭标即收养」处理——不动消息数组,交由下一轮修复器收敛。
|
|
2222
|
+
*
|
|
2223
|
+
* @param messages - 会话消息序列(append-only)
|
|
2224
|
+
* @param turnId - 本 turn id
|
|
2225
|
+
*/
|
|
2226
|
+
appendTurnEnd(messages, turnId) {
|
|
2227
|
+
let lastStartIdx = -1;
|
|
2228
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
2229
|
+
const m = messages[i];
|
|
2230
|
+
if (isTurnStartContent(m.content) && parseTurnIdFromContent(m.content) === turnId) {
|
|
2231
|
+
lastStartIdx = i;
|
|
2232
|
+
break;
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
const envelopeStart = lastStartIdx + 1;
|
|
2236
|
+
const exists = messages.some((m, i) => i >= envelopeStart &&
|
|
2237
|
+
m.metadata?.source === 'turnEnd' &&
|
|
2238
|
+
parseTurnIdFromContent(m.content) === turnId);
|
|
2239
|
+
if (exists)
|
|
2240
|
+
return;
|
|
2241
|
+
messages.push(this.makeTurnEndMessage(turnId));
|
|
2242
|
+
}
|
|
2243
|
+
/**
|
|
2244
|
+
* 尽力持久化 turnSeq 计数器(缺 updateMetadata 的 store 跳过,收尾整包 save 兜底)。
|
|
2245
|
+
*
|
|
2246
|
+
* 失败不中断 Run(幂等收养已兜住 id 复用的硬失败),但必须留痕:
|
|
2247
|
+
* 2026-10-28 事故的事后诊断正困于「计数器丢失」无任何日志。
|
|
2248
|
+
*
|
|
2249
|
+
* @param sessionId - 会话 id
|
|
2250
|
+
* @param turnSeq - 已分配的最新序号
|
|
2251
|
+
*/
|
|
2252
|
+
async persistTurnSeq(sessionId, turnSeq) {
|
|
2253
|
+
if (!this.store.updateMetadata)
|
|
2254
|
+
return;
|
|
2255
|
+
try {
|
|
2256
|
+
await this.store.updateMetadata(sessionId, (meta) => {
|
|
2257
|
+
meta.turnSeq = turnSeq;
|
|
2258
|
+
});
|
|
2259
|
+
}
|
|
2260
|
+
catch (err) {
|
|
2261
|
+
// 吞掉但留痕:同会话串行互斥下无并发写者(分布式 lease 不覆盖 store 写锁——
|
|
2262
|
+
// 跨进程部署的既有缺口),失败仅使续跑退化到幂等收养路径,不产生新失败面。
|
|
2263
|
+
console.warn(`[Runner] persist turnSeq failed session=${sessionId} seq=${turnSeq}: ${String(err)}`);
|
|
2264
|
+
}
|
|
1715
2265
|
}
|
|
1716
2266
|
/**
|
|
1717
2267
|
* Run 进行中转录增量落盘:把 durable 口径的历史对齐到存储。
|