@octopi-agent/engine 0.86.38 → 0.97.15
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 +43 -1
- package/dist/config-schema/agent.js +12 -5
- package/dist/config-schema/context.d.ts +7 -2
- package/dist/config-schema/context.js +8 -0
- package/dist/config-schema/engine.d.ts +110 -8
- package/dist/config-schema/governance.d.ts +43 -1
- package/dist/config-schema/governance.js +160 -2
- package/dist/config-schema/models.d.ts +7 -4
- 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-schema/shared.d.ts +3 -0
- package/dist/config-schema/shared.js +12 -0
- package/dist/config-schema/substrate.d.ts +1 -1
- package/dist/config.d.ts +60 -13
- package/dist/config.js +81 -78
- 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 +18 -3
- package/dist/harness/agent/builder.js +42 -17
- package/dist/harness/agent/config-bridge.d.ts +5 -0
- package/dist/harness/agent/config-bridge.js +7 -1
- package/dist/harness/agent/config-integrity.d.ts +72 -0
- package/dist/harness/agent/config-integrity.js +146 -0
- package/dist/harness/agent/tool-purpose.d.ts +9 -1
- package/dist/harness/agent/tool-purpose.js +11 -2
- package/dist/harness/agent/wire-agent-builder.js +11 -3
- package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.d.ts +11 -1
- package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +11 -1
- package/dist/harness/collaboration/autonomous-subsystem/loader.d.ts +13 -0
- package/dist/harness/collaboration/autonomous-subsystem/loader.js +16 -1
- package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +4 -0
- package/dist/harness/collaboration/autonomous-subsystem/runtime.js +3 -1
- package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
- 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/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 +198 -53
- package/dist/harness/context/hybrid-compressor.js +6 -0
- package/dist/harness/context/layer-types.d.ts +36 -0
- package/dist/harness/context/layer-types.js +38 -0
- 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/root-instructions.js +1 -1
- package/dist/harness/context/summarize.d.ts +2 -0
- package/dist/harness/context/summarize.js +7 -2
- package/dist/harness/context/system-prompt-assembler.js +10 -4
- package/dist/harness/context/tool-result-aging.js +2 -2
- package/dist/harness/context/truncate-compressor.js +7 -0
- package/dist/harness/context/turn-envelope.d.ts +4 -3
- package/dist/harness/context/turn-envelope.js +4 -3
- 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 +133 -4
- package/dist/harness/extension/execution-environment/effect-policy.js +263 -14
- 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/isolation.js +5 -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 +200 -0
- package/dist/harness/extension/execution-environment/ops-audit.js +338 -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 +264 -29
- 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/plugin-ecosystem/channel-types.d.ts +5 -0
- package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.d.ts +6 -0
- package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +50 -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 +53 -2
- package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +10 -17
- package/dist/harness/extension/plugin-ecosystem/tools/git-runner.d.ts +31 -0
- package/dist/harness/extension/plugin-ecosystem/tools/git-runner.js +104 -0
- package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.d.ts +111 -0
- package/dist/harness/extension/plugin-ecosystem/tools/git-status-snapshot.js +197 -0
- package/dist/harness/extension/plugin-ecosystem/tools/git-tools.d.ts +8 -8
- package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +9 -100
- package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +6 -0
- package/dist/harness/extension/plugin-ecosystem/tools/index.js +4 -0
- 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/temp-path.d.ts +9 -0
- package/dist/harness/governance/security/temp-path.js +13 -2
- package/dist/harness/governance/session-acl/seed-roles.js +14 -0
- package/dist/harness/index.d.ts +4 -0
- package/dist/harness/index.js +3 -0
- package/dist/harness/knowledge/file-identity.d.ts +8 -0
- package/dist/harness/knowledge/file-identity.js +26 -1
- package/dist/harness/knowledge/fts.js +1 -2
- package/dist/harness/knowledge/grounding.js +5 -5
- package/dist/harness/knowledge/index-store.d.ts +31 -4
- package/dist/harness/knowledge/index-store.js +180 -48
- package/dist/harness/knowledge/ingest.d.ts +115 -115
- package/dist/harness/knowledge/ingest.js +150 -150
- package/dist/harness/knowledge/knowledge-serve-child.js +1 -1
- package/dist/harness/knowledge/purge.js +4 -1
- package/dist/harness/memory/backfill-coverage.js +3 -1
- package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
- package/dist/harness/memory/sqlite/keyword-search.js +4 -3
- package/dist/harness/observability/observer/hub.js +38 -1
- package/dist/harness/observability/observer/run-snapshot.js +1 -0
- package/dist/harness/observability/observer/types.d.ts +27 -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 +31 -0
- package/dist/harness/run/runner.d.ts +132 -2
- package/dist/harness/run/runner.js +679 -60
- package/dist/harness/session/attachments/llm-intent.js +2 -1
- package/dist/harness/session/history/port.js +15 -5
- package/dist/harness/session/in-memory-store.d.ts +5 -0
- package/dist/harness/session/in-memory-store.js +33 -2
- package/dist/harness/session/tasks/render.d.ts +4 -1
- package/dist/harness/session/tasks/render.js +10 -7
- package/dist/harness/session/title.js +25 -9
- package/dist/harness/shared/events/agent-event-map.d.ts +92 -0
- package/dist/harness/shared/events/agent-event-map.js +7 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.js +4 -3
- 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/observability/run-telemetry.d.ts +8 -0
- package/dist/integration/observability/run-telemetry.js +31 -8
- package/dist/integration/observability/trace-collector.js +26 -4
- package/dist/integration/observability/trace-events.d.ts +1 -0
- package/dist/integration/observability/trace-events.js +2 -0
- package/dist/integration/observability/trace-logger.js +27 -17
- 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.d.ts +19 -1
- package/dist/integration/storage/jsonl.js +100 -4
- package/dist/paths.d.ts +19 -0
- package/dist/paths.js +38 -1
- package/dist/subsystems/cognition-steward/conceptualize/handler.js +1 -1
- package/dist/subsystems/memory-steward/backfill/handler.js +1 -1
- package/dist/subsystems/safety-guard/config.yaml +3 -1
- package/dist/subsystems/wisdom-steward/formation/handler.js +1 -1
- package/package.json +3 -2
|
@@ -14,7 +14,9 @@ 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 {
|
|
17
|
+
import { OpsAuditJournal, OpsAuditFileExportSink } from '../extension/execution-environment/ops-audit.js';
|
|
18
|
+
import { getOctopiHome } from '../../paths.js';
|
|
19
|
+
import { extractLayerQuery } from '../context/layer-types.js';
|
|
18
20
|
import { formatTurnEndContent, formatTurnId, formatTurnStartContent, formatTurnContextXml, isTurnStartContent, joinSlotXml, parseTurnIdFromContent, } from '../context/turn-envelope.js';
|
|
19
21
|
import { splitRuntimeEnvironmentInjection, withRuntimeEnvironmentInjection } from '../context/runtime-datetime.js';
|
|
20
22
|
import { loadRootInstructionsInjection } from '../context/root-instructions.js';
|
|
@@ -28,6 +30,12 @@ import { readSessionCompact, writeSessionCompact } from '../session/compact.js';
|
|
|
28
30
|
import { InProcessSessionLock, } from './concurrency/session-lease.js';
|
|
29
31
|
import { isToolPermitted } from '../governance/session-acl/tool-rights.js';
|
|
30
32
|
import { resolveToolCapabilities } from '../extension/execution-environment/tool-capabilities.js';
|
|
33
|
+
/**
|
|
34
|
+
* 失败凭证消息中附带残句的截断上限(显示用途;完整残句在带 error 标记的 turn 账本)
|
|
35
|
+
*
|
|
36
|
+
* 展示型截断,与 wire-dump 的消息截断同性质——不是部署可变参数,故不进配置。
|
|
37
|
+
*/
|
|
38
|
+
export const LLM_ERROR_PARTIAL_MAX_CHARS = 2000;
|
|
31
39
|
const DEFAULT_CONFIG = {
|
|
32
40
|
// idleExpiryMs 缺省关闭:上下文租约 opt-in,续聊默认带全量窗口
|
|
33
41
|
};
|
|
@@ -73,6 +81,16 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
73
81
|
sessionId: meta.sessionId,
|
|
74
82
|
data: { ...event.data },
|
|
75
83
|
};
|
|
84
|
+
case 'model_retry':
|
|
85
|
+
// 重试窗口对用户可见:52 分钟停滞期间前端零反馈,正是因为重试不产生任何事件。
|
|
86
|
+
// 不改 stopReason——重试不是终态,是否真停仍由 loopEndReason 决定。
|
|
87
|
+
return {
|
|
88
|
+
type: 'engine.model_retry',
|
|
89
|
+
timestamp: event.timestamp,
|
|
90
|
+
agentId: meta.agentId,
|
|
91
|
+
sessionId: meta.sessionId,
|
|
92
|
+
data: { ...event.data },
|
|
93
|
+
};
|
|
76
94
|
case 'agent_start':
|
|
77
95
|
return { type: 'engine.start', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: {} };
|
|
78
96
|
case 'agent_end':
|
|
@@ -80,7 +98,10 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
80
98
|
state.loopEndReason = event.reason;
|
|
81
99
|
// reason='error' 时映射为 engine.error(向后兼容旧引擎行为)
|
|
82
100
|
if (event.reason === 'error') {
|
|
83
|
-
|
|
101
|
+
const errorText = event.error instanceof Error ? event.error.message : String(event.error ?? 'Unknown error');
|
|
102
|
+
// 收口要落失败凭证(runStopped 消息);不在此留痕的话,重载会话后事故无影无踪
|
|
103
|
+
state.errorMessage = errorText;
|
|
104
|
+
return { type: 'engine.error', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: { error: errorText } };
|
|
84
105
|
}
|
|
85
106
|
return { type: 'engine.end', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: { reason: event.reason } };
|
|
86
107
|
case 'turn_start':
|
|
@@ -88,25 +109,37 @@ export function adaptLoopEvent(event, meta, state) {
|
|
|
88
109
|
return { type: 'iteration.start', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: {} };
|
|
89
110
|
case 'assistant_message':
|
|
90
111
|
state.assistantContent = typeof event.message.content === 'string' ? event.message.content : '';
|
|
112
|
+
// 完整消息已定稿,本次调用的部分流出功成身退(不得与正文叠加)
|
|
113
|
+
state.callStreamedContent = '';
|
|
91
114
|
return null;
|
|
92
|
-
case 'turn_end':
|
|
115
|
+
case 'turn_end': {
|
|
93
116
|
// phase 透传给 UI:pre_tools ≠ 本轮 run 结束(见 architecture.md)
|
|
117
|
+
// 正文口径:优先完整消息;失败轮(error=true)只有本次调用的部分流出,
|
|
118
|
+
// 不得回落到上一次调用的回复冒充本次输出
|
|
119
|
+
const turnContent = state.assistantContent || state.callStreamedContent || '';
|
|
120
|
+
state.lastTurnContent = turnContent;
|
|
121
|
+
state.lastTurnError = Boolean(event.error);
|
|
122
|
+
state.assistantContent = '';
|
|
123
|
+
state.callStreamedContent = '';
|
|
94
124
|
return {
|
|
95
125
|
type: 'turn.end',
|
|
96
126
|
timestamp: Date.now(),
|
|
97
127
|
agentId: meta.agentId,
|
|
98
128
|
sessionId: meta.sessionId,
|
|
99
129
|
data: {
|
|
100
|
-
content:
|
|
130
|
+
content: turnContent,
|
|
101
131
|
userText: state.lastUserContent ?? '',
|
|
102
132
|
hasToolCalls: event.hasToolCalls,
|
|
103
133
|
phase: event.phase,
|
|
104
134
|
usage: event.usage,
|
|
105
135
|
truncated: event.truncated,
|
|
106
136
|
error: event.error,
|
|
137
|
+
llmTiming: event.llmTiming,
|
|
107
138
|
},
|
|
108
139
|
};
|
|
140
|
+
}
|
|
109
141
|
case 'llm_stream_delta':
|
|
142
|
+
state.callStreamedContent = (state.callStreamedContent ?? '') + String(event.data?.delta ?? '');
|
|
110
143
|
return { type: 'llm_stream_delta', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: event.data };
|
|
111
144
|
case 'llm_thinking_delta':
|
|
112
145
|
return { type: 'llm_thinking_delta', timestamp: event.timestamp, agentId: meta.agentId, sessionId: meta.sessionId, data: event.data };
|
|
@@ -237,9 +270,32 @@ export class SessionAwareRunner {
|
|
|
237
270
|
/** Effective effectPolicy.mode (for Runtime injection / UI) */
|
|
238
271
|
effectMode = 'workspace';
|
|
239
272
|
effectCommitManual = false;
|
|
273
|
+
/** store 缺 syncMessages 通道时只 warn 一次 */
|
|
274
|
+
warnedMissingSync = false;
|
|
240
275
|
effectProcessLimits = true;
|
|
241
276
|
effectNetwork;
|
|
242
277
|
effectRequireJail;
|
|
278
|
+
/** ops P0:jail 意图(auto/require/none)——none=授权无笼 */
|
|
279
|
+
effectJail;
|
|
280
|
+
/** ops P2:审计账本开关(effectPolicy.opsAudit;未解析时回落配置缺省 on) */
|
|
281
|
+
/** ops P3:提权策略(resolved;priv_exec 全等匹配面) */
|
|
282
|
+
effectEscalation;
|
|
283
|
+
/** ops P4:危险命令减速带 resolved(§6;full 档 pre-exec 闸 + 确认超时) */
|
|
284
|
+
effectDangerousCommands;
|
|
285
|
+
/** ops P4:特权部署标记(jail=none / full 档 / root 进程)——UI 常驻 PRIVILEGED 数据源 */
|
|
286
|
+
effectPrivileged;
|
|
287
|
+
/** ops P5:kill switch 哨兵路径(run 准入已查;逐工具闸复用同面) */
|
|
288
|
+
killSwitchPaths = [];
|
|
289
|
+
/** ops P2:审计账本开关(effectPolicy.opsAudit;未解析时回落配置缺省 on) */
|
|
290
|
+
effectOpsAudit;
|
|
291
|
+
/** ops P2:hash 链审计账本(懒建;写失败降级申报,不吞) */
|
|
292
|
+
opsJournal;
|
|
293
|
+
/** ops P5:审计外送收口(宿主侧见证副本;未配置则不外送) */
|
|
294
|
+
opsExporter;
|
|
295
|
+
/** ops P2:账本缺省文件名的 agent 锚(每 runner 单 agent;handle 起点锚定) */
|
|
296
|
+
opsAuditAgentId;
|
|
297
|
+
/** ops P2:审计事件的 session 归属(写失败申报等无 run 载荷时用) */
|
|
298
|
+
opsAuditSessionId;
|
|
243
299
|
effectRequireCredentialBindings = false;
|
|
244
300
|
effectHomeWrite;
|
|
245
301
|
effectShellEscape = "allow";
|
|
@@ -286,6 +342,81 @@ export class SessionAwareRunner {
|
|
|
286
342
|
this._observerHub = config?.observerHub;
|
|
287
343
|
this.resolveModelOverride = config?.resolveModelOverride;
|
|
288
344
|
}
|
|
345
|
+
/**
|
|
346
|
+
* ops 审计记账(ops P2):写 hash 链账本。
|
|
347
|
+
*
|
|
348
|
+
* `opsAudit: off` 时整体静默(宿主的显式选择);写失败降级为 securityDegraded
|
|
349
|
+
* 申报——P2 不 fail-closed 业务(与 §5.6 记账同策略),P3 提权通道再收紧为硬前置。
|
|
350
|
+
*
|
|
351
|
+
* @param event - §7 事件词表
|
|
352
|
+
* @param data - 事件载荷(hash 走 canonicalJson,键序无关)
|
|
353
|
+
*/
|
|
354
|
+
recordOpsAudit(event, data) {
|
|
355
|
+
if ((this.effectOpsAudit ?? this.config.effectPolicy?.opsAudit ?? 'on') !== 'on')
|
|
356
|
+
return;
|
|
357
|
+
if (!this.opsJournal) {
|
|
358
|
+
// 缺省按 agent 分文件:多 agent 并发追加同一文件会共享 tail → seq 撞号,
|
|
359
|
+
// verify 会误报断裂。分文件 = 各自单写者,链严格成立。
|
|
360
|
+
const path = this.config.effectPolicy?.opsAuditPath ??
|
|
361
|
+
this.config.opsAuditPath ??
|
|
362
|
+
join(getOctopiHome(), 'audit', `ops.${this.opsAuditAgentId ?? 'unknown'}.jsonl`);
|
|
363
|
+
this.opsJournal = new OpsAuditJournal({ path });
|
|
364
|
+
}
|
|
365
|
+
try {
|
|
366
|
+
const entry = this.opsJournal.append(event, data);
|
|
367
|
+
// ops P5 审计外送(原则 8:唯一不可抵赖档):本地链防改写,外送防尾部截断/删除。
|
|
368
|
+
// 外送失败不回滚本地账(已落链),但必须降级申报——丢外送就是丢不可抵赖性。
|
|
369
|
+
const exporter = this.resolveOpsExporter();
|
|
370
|
+
if (exporter) {
|
|
371
|
+
try {
|
|
372
|
+
exporter.forward({
|
|
373
|
+
count: entry.seq,
|
|
374
|
+
tailHash: entry.hash,
|
|
375
|
+
entry,
|
|
376
|
+
forwardedAt: Date.now(),
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
catch (exportErr) {
|
|
380
|
+
this.noteOpsDegradation(`ops_audit_export_failed: ${exportErr instanceof Error ? exportErr.message : String(exportErr)}`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
catch (err) {
|
|
385
|
+
// 只吞「写失败」这一类,转成降级申报;账本损坏(ops_audit_corrupt)同样走这里。
|
|
386
|
+
this.noteOpsDegradation(`ops_audit_write_failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** 外送收口(懒建;仅配置了宿主侧收口路径时启用) */
|
|
390
|
+
resolveOpsExporter() {
|
|
391
|
+
const exportPath = this.config.effectPolicy?.opsAuditExportPath ?? this.config.opsAuditExportPath;
|
|
392
|
+
if (!exportPath)
|
|
393
|
+
return undefined;
|
|
394
|
+
if (!this.opsExporter) {
|
|
395
|
+
this.opsExporter = new OpsAuditFileExportSink({ path: exportPath });
|
|
396
|
+
}
|
|
397
|
+
return this.opsExporter;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* 审计链路降级申报(写失败/外送失败)。
|
|
401
|
+
* 双通道:harness 字段会被下一次 run 起点重置抹掉,必须同时发在线事件(评审实证)。
|
|
402
|
+
*/
|
|
403
|
+
noteOpsDegradation(reason) {
|
|
404
|
+
this.harness.securityDegraded = [
|
|
405
|
+
...(this.harness.securityDegraded ?? []),
|
|
406
|
+
reason,
|
|
407
|
+
];
|
|
408
|
+
this.emitObserved({
|
|
409
|
+
type: 'ops.policy.degraded',
|
|
410
|
+
timestamp: Date.now(),
|
|
411
|
+
agentId: this.opsAuditAgentId,
|
|
412
|
+
sessionId: this.opsAuditSessionId,
|
|
413
|
+
data: {
|
|
414
|
+
degradation: [reason],
|
|
415
|
+
requestedVsEffective: { requestedMode: 'n/a', mode: 'n/a' },
|
|
416
|
+
origin: { sessionId: this.opsAuditSessionId, agentId: this.opsAuditAgentId ?? '' },
|
|
417
|
+
},
|
|
418
|
+
});
|
|
419
|
+
}
|
|
289
420
|
/**
|
|
290
421
|
* 注入 Observer Hub(Gateway / 测试用)
|
|
291
422
|
*
|
|
@@ -371,6 +502,11 @@ export class SessionAwareRunner {
|
|
|
371
502
|
setToolContextProvider(provider) {
|
|
372
503
|
this.toolContextProvider = provider;
|
|
373
504
|
}
|
|
505
|
+
steeringProvider;
|
|
506
|
+
/** 注册一个运行期提示源(只进 steering 接缝);单槽,后注册者覆盖前注册者。 */
|
|
507
|
+
setSteeringProvider(provider) {
|
|
508
|
+
this.steeringProvider = provider;
|
|
509
|
+
}
|
|
374
510
|
/**
|
|
375
511
|
* 设置 persona 解析器
|
|
376
512
|
*
|
|
@@ -408,6 +544,11 @@ export class SessionAwareRunner {
|
|
|
408
544
|
setGroundingAssembler(assembler) {
|
|
409
545
|
this.groundingAssembler = assembler;
|
|
410
546
|
}
|
|
547
|
+
/** 通知委派服务:结果已真正写入父上下文,而非仅仅发进事件总线。 */
|
|
548
|
+
setDelegationDeliveryAck(ack) {
|
|
549
|
+
this.delegationDeliveryAck = ack;
|
|
550
|
+
}
|
|
551
|
+
delegationDeliveryAck;
|
|
411
552
|
/**
|
|
412
553
|
* 处理一条消息
|
|
413
554
|
*
|
|
@@ -417,12 +558,11 @@ export class SessionAwareRunner {
|
|
|
417
558
|
* @param signal - 中止信号
|
|
418
559
|
* @yields AgentEvent 事件流(向后兼容格式)
|
|
419
560
|
*/
|
|
420
|
-
async *handle(sessionId, input, runConfig, signal) {
|
|
561
|
+
async *handle(sessionId, input, runConfig, signal, inboxBinding, initialInboxEntry) {
|
|
421
562
|
/** 本轮文件 undo(L3);中止保留,其余出口 commit */
|
|
422
563
|
let turnFileUndo;
|
|
423
|
-
// [timing
|
|
564
|
+
// run 收口计时(`[timing]` 探针转正,F3):wait/build/run_end 走 eventSink → trace
|
|
424
565
|
const timingRunEnter = Date.now();
|
|
425
|
-
console.log(`[timing] stage=run_enter ms=${timingRunEnter} session=${sessionId}`);
|
|
426
566
|
// 1. 并发门控(如果配置了 SessionGate);排队期间响应 abort
|
|
427
567
|
const gate = this.config.sessionGate;
|
|
428
568
|
let gateRelease;
|
|
@@ -456,8 +596,35 @@ export class SessionAwareRunner {
|
|
|
456
596
|
gateRelease?.();
|
|
457
597
|
return;
|
|
458
598
|
}
|
|
459
|
-
|
|
460
|
-
|
|
599
|
+
let inboxRun;
|
|
600
|
+
// run.timing 先落 trace(eventSink 时序保真);Hub 侧投递推迟到 recordRunStart 之后——
|
|
601
|
+
// 否则 run_start/context_ready 早于 run 记录创建,会被 ingestEvent 归到上一轮 run
|
|
602
|
+
const pendingObservedTimings = [];
|
|
603
|
+
const runStartTiming = {
|
|
604
|
+
type: 'run.timing',
|
|
605
|
+
timestamp: Date.now(),
|
|
606
|
+
sessionId,
|
|
607
|
+
agentId: runConfig.agentId ?? 'default',
|
|
608
|
+
data: { stage: 'run_start', waitMs: Date.now() - timingRunEnter },
|
|
609
|
+
};
|
|
610
|
+
try {
|
|
611
|
+
inboxRun = inboxBinding
|
|
612
|
+
? inboxBinding.inbox.open(sessionId, runConfig.agentId ?? 'default', inboxBinding.runId, inboxBinding.entries, { model: runConfig.model, provider: runConfig.modelProvider })
|
|
613
|
+
: undefined;
|
|
614
|
+
if (inboxRun && initialInboxEntry)
|
|
615
|
+
inboxRun.take(initialInboxEntry.id);
|
|
616
|
+
this.config.eventSink?.(runStartTiming, { sessionId, agentId: runConfig.agentId ?? 'default' });
|
|
617
|
+
pendingObservedTimings.push(runStartTiming);
|
|
618
|
+
}
|
|
619
|
+
catch (err) {
|
|
620
|
+
// open/eventSink 抛错不得跳过 release:否则锁泄漏 + inbox active 永不清(评审 F7)
|
|
621
|
+
inboxRun?.close();
|
|
622
|
+
release();
|
|
623
|
+
gateRelease?.();
|
|
624
|
+
throw err;
|
|
625
|
+
}
|
|
626
|
+
// buildMs 从拿锁后起算(含 wait 会双重计时;F3-d 耗时区按分段展示)
|
|
627
|
+
const runStartTs = Date.now();
|
|
461
628
|
const _agentId = runConfig.agentId ?? 'default';
|
|
462
629
|
/** Observer 收口状态(finally 统一关闭,含异常路径) */
|
|
463
630
|
let observerRunId = '';
|
|
@@ -535,9 +702,24 @@ export class SessionAwareRunner {
|
|
|
535
702
|
this.config.sessionTaskService?.attachSession(session);
|
|
536
703
|
// 4c. turn 信封:补闭上一 turn;分配本 turn id(t1,t2,… 会话内单调)
|
|
537
704
|
this.ensurePreviousTurnClosed(session);
|
|
538
|
-
|
|
539
|
-
const
|
|
705
|
+
// 计数器污染防护:非数值(NaN/null 经 JSON 往返)一律回退 0,防 'tNaN' 与静默复用
|
|
706
|
+
const prevTurnSeq = Number(session.metadata?.turnSeq ?? 0);
|
|
707
|
+
const turnSeq = (Number.isFinite(prevTurnSeq) ? prevTurnSeq : 0) + 1;
|
|
708
|
+
let currentTurnId = formatTurnId(turnSeq);
|
|
540
709
|
session.metadata = { ...session.metadata, turnSeq };
|
|
710
|
+
// 计数器分配即持久化:收尾整包 save 之前中断(冻结/被杀)会丢 turnSeq,
|
|
711
|
+
// 续跑随后复用已闭 turn 的 id(2026-10-28 事故链第一环)。
|
|
712
|
+
await this.persistTurnSeq(sessionId, turnSeq);
|
|
713
|
+
const closedInsertedTurnIds = new Set();
|
|
714
|
+
const allocateInsertedTurnId = async () => {
|
|
715
|
+
// consumeMessages 目前被 Loop 串行 await 调用(单消费者);若未来并发化,
|
|
716
|
+
// 这里的 read-increment-write 会双分配同 seq——并发前必须换原子分配
|
|
717
|
+
const prevSeq = Number(session.metadata?.turnSeq ?? 0);
|
|
718
|
+
const seq = (Number.isFinite(prevSeq) ? prevSeq : 0) + 1;
|
|
719
|
+
session.metadata = { ...session.metadata, turnSeq: seq };
|
|
720
|
+
await this.persistTurnSeq(sessionId, seq);
|
|
721
|
+
return formatTurnId(seq);
|
|
722
|
+
};
|
|
541
723
|
// 5. 追加用户消息(正文稍后一次定形为 <turn_start>)
|
|
542
724
|
session.messages.push(input);
|
|
543
725
|
session.meta.lastInteractionAt = Date.now();
|
|
@@ -625,7 +807,62 @@ export class SessionAwareRunner {
|
|
|
625
807
|
// P3:effectPolicy → L2 path containment + session 临时 root
|
|
626
808
|
// 必须在 Runtime 注入之前,system prompt 才能带上 allowRoots / effectMode
|
|
627
809
|
{
|
|
628
|
-
|
|
810
|
+
// ops P2:账本 agent/session 锚先于首笔账(漂移记录)落定
|
|
811
|
+
this.opsAuditAgentId = _agentId;
|
|
812
|
+
this.opsAuditSessionId = sessionId;
|
|
813
|
+
// ops P2 §4.3/§8.4:安全配置漂移守卫——先于解析与探测判定(漂移是配置事实)。
|
|
814
|
+
// 漂移 = 拒新 run + ops.config.security_changed,直至宿主重启/署名确认。
|
|
815
|
+
const integrity = await this.config.securityIntegrity?.recheck();
|
|
816
|
+
if (integrity && !integrity.ok) {
|
|
817
|
+
const driftData = {
|
|
818
|
+
changed: integrity.changed,
|
|
819
|
+
action: 'refuse_new_run',
|
|
820
|
+
// §7 要的旧→新摘要 + 来源/署名态:谁改的无法从文件判定(agent 写 vs 宿主写
|
|
821
|
+
// 同样是磁盘字节),如实记 unattributed + 未署名
|
|
822
|
+
previousFingerprint: this.config.securityIntegrity?.fingerprint ?? null,
|
|
823
|
+
currentFingerprint: integrity.currentFingerprint ?? null,
|
|
824
|
+
source: 'unattributed',
|
|
825
|
+
hostAttested: false,
|
|
826
|
+
origin: { sessionId, agentId: _agentId },
|
|
827
|
+
};
|
|
828
|
+
this.recordOpsAudit('ops.config.security_changed', driftData);
|
|
829
|
+
this.emitObserved({
|
|
830
|
+
type: 'ops.config.security_changed',
|
|
831
|
+
timestamp: Date.now(),
|
|
832
|
+
agentId: _agentId,
|
|
833
|
+
sessionId,
|
|
834
|
+
data: { ...driftData },
|
|
835
|
+
});
|
|
836
|
+
throw new Error(`security_config_drift: security-relevant config changed on disk (changed: ${integrity.changed.join(', ')}); ` +
|
|
837
|
+
`restart required to re-attest (restart adopts what is on disk — treat the human restart as the attestation act; ` +
|
|
838
|
+
`automated attestation lands with the ConfigService write-back)`);
|
|
839
|
+
}
|
|
840
|
+
// ops P5 kill switch:宿主侧急停哨兵——run 准入即拒(不依赖 LLM 判断/agent 合作)
|
|
841
|
+
{
|
|
842
|
+
const { checkKillSwitch, defaultKillSwitchPath } = await import('../extension/execution-environment/kill-switch.js');
|
|
843
|
+
this.killSwitchPaths = [
|
|
844
|
+
this.config.killSwitchPath ?? defaultKillSwitchPath(_agentId),
|
|
845
|
+
];
|
|
846
|
+
const killState = checkKillSwitch(this.killSwitchPaths);
|
|
847
|
+
if (killState.engaged) {
|
|
848
|
+
const killData = {
|
|
849
|
+
path: killState.path,
|
|
850
|
+
action: 'refuse_run',
|
|
851
|
+
origin: { sessionId, agentId: _agentId },
|
|
852
|
+
};
|
|
853
|
+
this.recordOpsAudit('ops.kill_switch.tripped', killData);
|
|
854
|
+
this.emitObserved({
|
|
855
|
+
type: 'ops.kill_switch.tripped',
|
|
856
|
+
timestamp: Date.now(),
|
|
857
|
+
agentId: _agentId,
|
|
858
|
+
sessionId,
|
|
859
|
+
data: { ...killData },
|
|
860
|
+
});
|
|
861
|
+
throw new Error(`kill_switch_active: agent execution is halted by the host sentinel (${killState.path}); ` +
|
|
862
|
+
`remove it (\`octopi ops revive <agentId>\`) to resume`);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
const { resolveEffectiveEffectPolicy, readSessionEffectOverrides, mergeTransactionRoots, requiresJail, buildOpsJailState, } = await import('../extension/execution-environment/effect-policy.js');
|
|
629
866
|
const { probeProcessIsolation } = await import('../extension/execution-environment/process-isolation.js');
|
|
630
867
|
const isolation = await probeProcessIsolation();
|
|
631
868
|
const eff = resolveEffectiveEffectPolicy(this.config.effectPolicy ?? {}, this.config.agentWorkspace ?? effectiveRunConfig.cwd ?? undefined, isolation);
|
|
@@ -639,7 +876,17 @@ export class SessionAwareRunner {
|
|
|
639
876
|
this.effectShellEscape = eff.shellEscape;
|
|
640
877
|
this.effectShellJournal = eff.shellJournal;
|
|
641
878
|
this.effectNetwork = eff.network;
|
|
642
|
-
this.
|
|
879
|
+
this.effectJail = eff.jail;
|
|
880
|
+
this.effectEscalation = eff.escalation;
|
|
881
|
+
this.effectDangerousCommands = eff.dangerousCommands;
|
|
882
|
+
// ops P4:特权部署标记 = 授权无笼 / full 档 / root·elevated 进程(§5 P4 root 部署语义)
|
|
883
|
+
{
|
|
884
|
+
const { isProcessElevated } = await import('../extension/execution-environment/privileged-exec.js');
|
|
885
|
+
this.effectPrivileged = eff.privileged || (await isProcessElevated());
|
|
886
|
+
}
|
|
887
|
+
this.effectRequireJail = requiresJail(eff);
|
|
888
|
+
// 严格凭证绑定只跟 untrusted 承诺走(历史语义):jail=require/refuse 不得
|
|
889
|
+
// 悄悄改变 host/project 的凭证行为
|
|
643
890
|
this.effectRequireCredentialBindings =
|
|
644
891
|
this.config.requireCredentialBindings === true ||
|
|
645
892
|
(eff.requestedMode === 'untrusted' && eff.mode === 'untrusted');
|
|
@@ -648,8 +895,42 @@ export class SessionAwareRunner {
|
|
|
648
895
|
this.effectUndoLimit = eff.undoLimit;
|
|
649
896
|
// untrusted admission: reduced surface strips egress/exec tools
|
|
650
897
|
this.harness.toolSurface = eff.toolSurface;
|
|
898
|
+
// 无条件重置(空也要写):harness 跨 run 共享,条件赋值会让上一轮的降级
|
|
899
|
+
// 粘到授权 run 上——「授权被记成降级」恰是 ops P0 要消灭的误报
|
|
900
|
+
this.harness.securityDegraded = [...eff.securityDegraded];
|
|
901
|
+
// ops P0:run 开始即记录 jail 意图 × 实测后端——「授权」与「故障」的事后判据
|
|
902
|
+
// (§4.2 ops.jail.state;不等失效才留痕)。进延迟投递队列:run 记录
|
|
903
|
+
// (recordRunStart)建立后才归档,否则 Hub 会把它挂到上一轮 run 或直接丢弃。
|
|
904
|
+
const jailState = { ...buildOpsJailState(eff, isolation) };
|
|
905
|
+
pendingObservedTimings.push({
|
|
906
|
+
type: 'ops.jail.state',
|
|
907
|
+
timestamp: Date.now(),
|
|
908
|
+
agentId: _agentId,
|
|
909
|
+
sessionId,
|
|
910
|
+
data: jailState,
|
|
911
|
+
});
|
|
912
|
+
// ops P2:账本是「事后可查」的持久面(Observer timeline 只是在线视图)
|
|
913
|
+
this.effectOpsAudit = eff.opsAudit;
|
|
914
|
+
// runId 此处尚未生成(createRunId 在工具 scope 装配前);run 归属由
|
|
915
|
+
// pendingObservedTimings → run timeline 承担,账本记 session/agent 锚点
|
|
916
|
+
this.recordOpsAudit('ops.jail.state', {
|
|
917
|
+
...jailState,
|
|
918
|
+
origin: { sessionId, agentId: _agentId },
|
|
919
|
+
});
|
|
651
920
|
if (eff.securityDegraded.length > 0) {
|
|
652
|
-
|
|
921
|
+
const degradedData = {
|
|
922
|
+
degradation: eff.securityDegraded,
|
|
923
|
+
requestedVsEffective: { requestedMode: eff.requestedMode, mode: eff.mode },
|
|
924
|
+
origin: { sessionId, agentId: _agentId },
|
|
925
|
+
};
|
|
926
|
+
this.recordOpsAudit('ops.policy.degraded', degradedData);
|
|
927
|
+
pendingObservedTimings.push({
|
|
928
|
+
type: 'ops.policy.degraded',
|
|
929
|
+
timestamp: Date.now(),
|
|
930
|
+
agentId: _agentId,
|
|
931
|
+
sessionId,
|
|
932
|
+
data: { ...degradedData },
|
|
933
|
+
});
|
|
653
934
|
}
|
|
654
935
|
}
|
|
655
936
|
// Runtime 锚点:时间 + 工具工作目录 + 允许根/效应模式
|
|
@@ -852,8 +1133,25 @@ export class SessionAwareRunner {
|
|
|
852
1133
|
pendingGrounding = null;
|
|
853
1134
|
}
|
|
854
1135
|
}
|
|
855
|
-
//
|
|
856
|
-
|
|
1136
|
+
// system prompt 装配 + grounding 全部就绪;buildMs = 组装耗时。
|
|
1137
|
+
// 口径注记(arch/b0-cache-stable-context.md §5):sysChars 是稳定前缀规模,
|
|
1138
|
+
// E8 后不含易变快照——勿与旧 `[timing]` 基线直接对比。
|
|
1139
|
+
const contextReadyTiming = {
|
|
1140
|
+
type: 'run.timing',
|
|
1141
|
+
timestamp: Date.now(),
|
|
1142
|
+
sessionId,
|
|
1143
|
+
agentId: _agentId,
|
|
1144
|
+
data: {
|
|
1145
|
+
stage: 'context_ready',
|
|
1146
|
+
buildMs: Date.now() - runStartTs,
|
|
1147
|
+
msgs: session.messages.length,
|
|
1148
|
+
sysChars: (runContext.systemPrompt ?? '').length,
|
|
1149
|
+
groundingTokens: pendingGrounding ? pendingGrounding.tokens : 0,
|
|
1150
|
+
},
|
|
1151
|
+
};
|
|
1152
|
+
this.config.eventSink?.(contextReadyTiming, { sessionId, agentId: _agentId });
|
|
1153
|
+
// Hub 投递同样推迟到 recordRunStart 之后(见 run_start 处注释)
|
|
1154
|
+
pendingObservedTimings.push(contextReadyTiming);
|
|
857
1155
|
// 更新 harness 的 sessionId/agentId(checkpoint 回退;权威身份在 RunScope ALS)
|
|
858
1156
|
this.harness.sessionId = sessionId;
|
|
859
1157
|
this.harness.agentId = effectiveRunConfig.agentId ?? 'default';
|
|
@@ -895,7 +1193,16 @@ export class SessionAwareRunner {
|
|
|
895
1193
|
: undefined;
|
|
896
1194
|
turnFileUndo = fileUndo;
|
|
897
1195
|
const { createUnconfiguredMemoryEffects: unconfMem, resolveSessionUndoPaths, } = await import('../extension/execution-environment/undo-log.js');
|
|
898
|
-
|
|
1196
|
+
// ops P2:效应写口集中拦截 roots 外写入 → ops.system_path.write
|
|
1197
|
+
// (单点覆盖全部文件工具与 shell 账本,不逐工具打补丁)
|
|
1198
|
+
const { OpsAuditedFileEffects } = await import('../extension/execution-environment/ops-audit.js');
|
|
1199
|
+
const fileEffects = new OpsAuditedFileEffects(fileUndo ?? createUnconfiguredFileEffects(), {
|
|
1200
|
+
// roots 为空时 L2 回退 cwd——审计判定不得比 L2 更宽(全记 system_path 是误报)
|
|
1201
|
+
roots: this.effectAllowRoots.length
|
|
1202
|
+
? this.effectAllowRoots
|
|
1203
|
+
: [resolvedToolCwd.cwd ?? baseCwd ?? process.cwd()],
|
|
1204
|
+
record: (event, data) => this.recordOpsAudit(event, data),
|
|
1205
|
+
});
|
|
899
1206
|
const memoryEffects = fileUndo?.memoryEffects ?? unconfMem();
|
|
900
1207
|
const undoRoots = this.config.sessionsDir
|
|
901
1208
|
? [resolveSessionUndoPaths(this.config.sessionsDir, sessionId).root]
|
|
@@ -917,8 +1224,11 @@ export class SessionAwareRunner {
|
|
|
917
1224
|
memoryEffects,
|
|
918
1225
|
undoRoots,
|
|
919
1226
|
networkPolicy: this.effectNetwork,
|
|
920
|
-
|
|
1227
|
+
// 单源:effectRequireCredentialBindings 已在解析时含 requiresJail(eff)(= untrusted),
|
|
1228
|
+
// 此处再判 effectMode 是等价冗余,已收编。
|
|
1229
|
+
requireCredentialBindings: this.effectRequireCredentialBindings,
|
|
921
1230
|
requireJail: this.effectRequireJail,
|
|
1231
|
+
disableJail: this.effectJail === 'none',
|
|
922
1232
|
homeWrite: this.effectHomeWrite,
|
|
923
1233
|
noteSecurityDegraded: (reason) => {
|
|
924
1234
|
this.harness.securityDegraded = [
|
|
@@ -926,6 +1236,10 @@ export class SessionAwareRunner {
|
|
|
926
1236
|
reason,
|
|
927
1237
|
];
|
|
928
1238
|
},
|
|
1239
|
+
// ops P2:工具侧动作/越权写入 → 统一审计账本(core 钩子,存储归 runner)
|
|
1240
|
+
recordOpsEvent: (record) => {
|
|
1241
|
+
this.recordOpsAudit(record.event, record.data);
|
|
1242
|
+
},
|
|
929
1243
|
pathRoots: this.effectAllowRoots.length
|
|
930
1244
|
? this.effectAllowRoots
|
|
931
1245
|
: resolvedToolCwd.cwd
|
|
@@ -934,6 +1248,15 @@ export class SessionAwareRunner {
|
|
|
934
1248
|
pathContainment: this.effectPathContainment,
|
|
935
1249
|
confirmEffect: this.config.confirmEffect,
|
|
936
1250
|
effectChannel: this.effectChannel,
|
|
1251
|
+
escalation: this.effectEscalation,
|
|
1252
|
+
dangerousCommands: this.effectDangerousCommands,
|
|
1253
|
+
privileged: this.effectPrivileged,
|
|
1254
|
+
// ops P5「参与者身份入账」:提权请求/拒绝审计的 requester 载荷(SEC-2 角色绑定)
|
|
1255
|
+
sessionParticipants: session.participants?.map((p) => ({
|
|
1256
|
+
agentId: p.agentId,
|
|
1257
|
+
roleId: p.roleId,
|
|
1258
|
+
})),
|
|
1259
|
+
killSwitchPaths: this.killSwitchPaths,
|
|
937
1260
|
processLimits: this.effectProcessLimits,
|
|
938
1261
|
shellEscape: this.effectShellEscape,
|
|
939
1262
|
shellJournal: this.effectShellJournal,
|
|
@@ -1034,6 +1357,17 @@ export class SessionAwareRunner {
|
|
|
1034
1357
|
runScope.toolRuntime.messages = baseMsgs;
|
|
1035
1358
|
}
|
|
1036
1359
|
}
|
|
1360
|
+
// Run 进行中转录增量落盘:turn_start 定形后立即同步一次(此后新消息
|
|
1361
|
+
// 定形随 loop 事件增量同步)。写失败不中断 Run(收尾 save 是权威写),
|
|
1362
|
+
// 失败不推进已同步计数,下个事件重试。
|
|
1363
|
+
const firstSynced = await this.persistRunMessages(sessionId, _agentId, contextLeasePrefix, runContext.messages);
|
|
1364
|
+
if (firstSynced && initialInboxEntry) {
|
|
1365
|
+
inboxRun?.inbox.ack(initialInboxEntry);
|
|
1366
|
+
const delegationId = initialInboxEntry.message.metadata?.delegationId;
|
|
1367
|
+
if (typeof delegationId === 'string')
|
|
1368
|
+
this.delegationDeliveryAck?.(delegationId);
|
|
1369
|
+
}
|
|
1370
|
+
let syncedMessageCount = firstSynced ? runContext.messages.length : 0;
|
|
1037
1371
|
// Observer 通道:Run 现场快照(摘要进事件;全文由 Hub/REST 提供)
|
|
1038
1372
|
if (this._observerHub?.isEnabled()) {
|
|
1039
1373
|
observerRunId =
|
|
@@ -1050,6 +1384,10 @@ export class SessionAwareRunner {
|
|
|
1050
1384
|
messages: session.messages,
|
|
1051
1385
|
}) || runId;
|
|
1052
1386
|
if (observerRunId) {
|
|
1387
|
+
// run 记录已建:补投 run_start/context_ready 到 Hub(此前投会被归到上一轮 run)
|
|
1388
|
+
for (const pending of pendingObservedTimings.splice(0)) {
|
|
1389
|
+
this.emitObserved(pending);
|
|
1390
|
+
}
|
|
1053
1391
|
const hubSnapshot = this._observerHub.getRunById(observerRunId);
|
|
1054
1392
|
if (hubSnapshot) {
|
|
1055
1393
|
this.emitObserved({
|
|
@@ -1096,13 +1434,100 @@ export class SessionAwareRunner {
|
|
|
1096
1434
|
let turnStartIndex = runContext.messages.length;
|
|
1097
1435
|
/** 用户中止(编辑重发标记用) */
|
|
1098
1436
|
let runAborted = false;
|
|
1437
|
+
/** 被接续消息的收尾通道(频道回复捕获等);消费后转发本 Run 全部事件 */
|
|
1438
|
+
const entryObservers = new Set();
|
|
1099
1439
|
// resolvedModel 已在 system assembler 之前解析;此处只组装 run options
|
|
1440
|
+
/** 已入 Run 视图、待转录同步确认的 inbox 条目(ack = 入上下文 + 同步成功) */
|
|
1441
|
+
const pendingInboxAcks = [];
|
|
1442
|
+
const flushInboxAcks = () => {
|
|
1443
|
+
for (const entry of pendingInboxAcks.splice(0)) {
|
|
1444
|
+
inboxRun?.inbox.ack(entry);
|
|
1445
|
+
const delegationId = entry.message.metadata?.delegationId;
|
|
1446
|
+
if (typeof delegationId === 'string')
|
|
1447
|
+
this.delegationDeliveryAck?.(delegationId);
|
|
1448
|
+
}
|
|
1449
|
+
};
|
|
1100
1450
|
const agentRunOptions = {
|
|
1101
1451
|
resolvedModel: resolvedModel ?? undefined,
|
|
1102
1452
|
context: runContext,
|
|
1103
1453
|
runScope,
|
|
1454
|
+
consumeMessages: async () => {
|
|
1455
|
+
const injected = [];
|
|
1456
|
+
if (inboxRun) {
|
|
1457
|
+
for (const entry of inboxRun.drain()) {
|
|
1458
|
+
// 每条注入输入(人话 / 委派结果)开启自己的 turn:
|
|
1459
|
+
// 先闭上一 turn(write-once),再一次定形新 turn 信封(与 wake 路径同构)。
|
|
1460
|
+
// 有序序列交还 Loop 统一 push 进 context.messages(不在此处直接入数组)。
|
|
1461
|
+
injected.push(this.makeTurnEndMessage(currentTurnId));
|
|
1462
|
+
closedInsertedTurnIds.add(currentTurnId);
|
|
1463
|
+
currentTurnId = await allocateInsertedTurnId();
|
|
1464
|
+
entry.message.metadata = { ...entry.message.metadata, turnId: currentTurnId };
|
|
1465
|
+
// 注入 turn 也带 runtime_snapshot(datetime 等);附件/grounding 属 turn 1,不重复
|
|
1466
|
+
this.bakeTurnStart(entry.message, currentTurnId, formatTurnContextXml({
|
|
1467
|
+
turnId: currentTurnId,
|
|
1468
|
+
slotsXml: joinSlotXml([{ tag: 'runtime_snapshot', body: runtimeSnapshotText ?? '' }]),
|
|
1469
|
+
}));
|
|
1470
|
+
injected.push(entry.message);
|
|
1471
|
+
// ack 延到转录同步成功后统一 flush;同步失败/崩溃由 close 的
|
|
1472
|
+
// unacked 重投兜底(at-least-once,见 SessionInbox)
|
|
1473
|
+
pendingInboxAcks.push(entry);
|
|
1474
|
+
if (entry.onEvent)
|
|
1475
|
+
entryObservers.add(entry.onEvent);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
if (injected.length) {
|
|
1479
|
+
this.emitObserved({
|
|
1480
|
+
type: 'session.inbox.appended',
|
|
1481
|
+
timestamp: Date.now(),
|
|
1482
|
+
sessionId,
|
|
1483
|
+
agentId: _agentId,
|
|
1484
|
+
data: {
|
|
1485
|
+
runId,
|
|
1486
|
+
count: injected.length,
|
|
1487
|
+
messages: injected
|
|
1488
|
+
.filter((m) => m.metadata?.source !== 'turnEnd')
|
|
1489
|
+
.map((m) => ({ role: m.role, content: m.content, metadata: m.metadata })),
|
|
1490
|
+
},
|
|
1491
|
+
});
|
|
1492
|
+
}
|
|
1493
|
+
return injected;
|
|
1494
|
+
},
|
|
1495
|
+
// 只读提示只进 steering 接缝:经 followUp 续命会让 run 被状态快照拖住(评审 F1)
|
|
1496
|
+
steeringExtras: async () => this.steeringProvider ? this.steeringProvider() : [],
|
|
1497
|
+
// 工具部分输出(展示通道):事件从回调直达事件出口——生成器无法在工具执行中
|
|
1498
|
+
// yield,故不进事件 yield 流(generator 消费方如通道回复捕获收不到,属预期取舍);
|
|
1499
|
+
// WS/EventBus 消费方(TUI/WebUI)经 eventSink + emitObserved 正常可见。
|
|
1500
|
+
onToolUpdate: (params) => {
|
|
1501
|
+
const { toolCall, partial } = params;
|
|
1502
|
+
const updateEvent = {
|
|
1503
|
+
type: 'tool.exec.update',
|
|
1504
|
+
timestamp: Date.now(),
|
|
1505
|
+
agentId: meta.agentId,
|
|
1506
|
+
sessionId: meta.sessionId,
|
|
1507
|
+
data: { toolCallId: toolCall.id, toolName: toolCall.name, content: partial.content },
|
|
1508
|
+
};
|
|
1509
|
+
this.config.eventSink?.(updateEvent, meta);
|
|
1510
|
+
this.emitObserved(updateEvent);
|
|
1511
|
+
},
|
|
1104
1512
|
};
|
|
1105
1513
|
for await (const loopEvent of this.agent.run(signal, undefined, agentRunOptions)) {
|
|
1514
|
+
// 消息数组增长 = 有新消息定形/入列(流式 delta 不 push 消息,不触发)。
|
|
1515
|
+
// 覆盖 assistant/tool/followUp/steering 全部 push 点:push 必发生在
|
|
1516
|
+
// 某个事件 yield 之前,下一迭代开头即可看到。
|
|
1517
|
+
if (runContext.messages.length !== syncedMessageCount) {
|
|
1518
|
+
if (await this.persistRunMessages(sessionId, _agentId, contextLeasePrefix, runContext.messages)) {
|
|
1519
|
+
syncedMessageCount = runContext.messages.length;
|
|
1520
|
+
// 转录同步成功 = 注入消息已入父上下文且可恢复 → 确认送达
|
|
1521
|
+
flushInboxAcks();
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
else if (loopEvent.type === 'turn_end') {
|
|
1525
|
+
// 漂移兜底:turn 边界无条件对齐一次(旁路写者整包回退后即使暂无
|
|
1526
|
+
// 新消息也能自愈;无漂移时幂等零写)
|
|
1527
|
+
if (await this.persistRunMessages(sessionId, _agentId, contextLeasePrefix, runContext.messages)) {
|
|
1528
|
+
flushInboxAcks();
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1106
1531
|
if (loopEvent.type === 'agent_end' && loopEvent.reason === 'aborted') {
|
|
1107
1532
|
runAborted = true;
|
|
1108
1533
|
}
|
|
@@ -1143,6 +1568,16 @@ export class SessionAwareRunner {
|
|
|
1143
1568
|
lastContextTokens = contextTokens;
|
|
1144
1569
|
lastContextWindow = effectiveRunConfig.contextWindow;
|
|
1145
1570
|
}
|
|
1571
|
+
// 被接续消息的调用方收尾通道(如频道回复捕获):转发本 Run 事件;
|
|
1572
|
+
// 单通道故障不得中断事件流
|
|
1573
|
+
for (const observer of entryObservers) {
|
|
1574
|
+
try {
|
|
1575
|
+
observer(adapted);
|
|
1576
|
+
}
|
|
1577
|
+
catch (obsErr) {
|
|
1578
|
+
console.warn(`[octopi] inbox entry observer failed: ${obsErr instanceof Error ? obsErr.message : String(obsErr)}`);
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1146
1581
|
yield adapted;
|
|
1147
1582
|
// Telemetry 旁路(含 stream delta;由 RunTelemetry 决定采样)
|
|
1148
1583
|
this.config.eventSink?.(adapted, meta);
|
|
@@ -1156,10 +1591,7 @@ export class SessionAwareRunner {
|
|
|
1156
1591
|
if (loopEvent.type === 'llm_stream_delta' && loopEvent.data?.delta) {
|
|
1157
1592
|
streamedContent += loopEvent.data.delta;
|
|
1158
1593
|
}
|
|
1159
|
-
//
|
|
1160
|
-
if (loopEvent.type === 'assistant_message') {
|
|
1161
|
-
adaptState.assistantContent = typeof loopEvent.message.content === 'string' ? loopEvent.message.content : '';
|
|
1162
|
-
}
|
|
1594
|
+
// assistantContent 由 adaptLoopEvent 在 assistant_message 事件上单一写入
|
|
1163
1595
|
// turn_start:重置本轮增量游标(afterTurn 只传本轮消息)
|
|
1164
1596
|
if (loopEvent.type === 'turn_start') {
|
|
1165
1597
|
turnStartIndex = runContext.messages.length;
|
|
@@ -1174,13 +1606,17 @@ export class SessionAwareRunner {
|
|
|
1174
1606
|
const turnMessages = runContext.messages.slice(turnStartIndex);
|
|
1175
1607
|
await this.agent.notifyAfterTurn(lastUsage, turnMessages);
|
|
1176
1608
|
turnStartIndex = runContext.messages.length;
|
|
1177
|
-
|
|
1178
|
-
|
|
1609
|
+
// 账本正文 = adaptLoopEvent 按调用算好的快照(失败轮只有本次调用的部分流出);
|
|
1610
|
+
// 失败轮必须带 error 标记,空正文也留账(审计价值),不得拿历史内容凑数
|
|
1611
|
+
const content = adaptState.lastTurnContent ?? '';
|
|
1612
|
+
const turnFailed = Boolean(adaptState.lastTurnError);
|
|
1613
|
+
if (content || turnFailed) {
|
|
1179
1614
|
session.turns.push({
|
|
1180
1615
|
id: `turn_${Date.now()}`,
|
|
1181
1616
|
inputCount: Math.max(0, session.messages.length - 1),
|
|
1182
1617
|
output: { role: 'assistant', content, timestamp: Date.now(), agentId: _agentId },
|
|
1183
|
-
usage
|
|
1618
|
+
// 失败轮没有 usage(loop 的 error turn_end 不带);不得写上一次调用的用量
|
|
1619
|
+
...(turnFailed ? { error: true } : { usage: lastUsage }),
|
|
1184
1620
|
durationMs: 0,
|
|
1185
1621
|
model: effectiveRunConfig.model ?? 'unknown',
|
|
1186
1622
|
timestamp: Date.now(),
|
|
@@ -1211,14 +1647,64 @@ export class SessionAwareRunner {
|
|
|
1211
1647
|
// 引擎主动终止(RunGuard / Budget / Security)必须留下可见凭证:
|
|
1212
1648
|
// 只有事件、没有消息时,UI 看到的就是「跑着跑着突然结束」。
|
|
1213
1649
|
//
|
|
1214
|
-
// 触发条件 = loop 的 agent_end.reason
|
|
1650
|
+
// 触发条件 = loop 的 agent_end.reason('should_stop' 引擎主动停止 / 'error' LLM 彻底失败)。
|
|
1215
1651
|
// 不能只看 stopReason:`security_blocked` 单次拦截后 run 会继续跑完,
|
|
1216
1652
|
// 那样会把正常完成的 run 误报成「已停止」。
|
|
1217
1653
|
//
|
|
1218
1654
|
// 该消息不进 LLM 上下文(buildLlmMessages 跳过 source=runStopped),
|
|
1219
1655
|
// 但进聊天回放(系统提示条)与 session 审计。
|
|
1220
1656
|
// 位置在 turn_end 之前:它属于被终止的这个 turn。
|
|
1221
|
-
if (adaptState.loopEndReason === '
|
|
1657
|
+
if (adaptState.loopEndReason === 'error') {
|
|
1658
|
+
// LLM 彻底失败同样是「无回复收尾」:必须留下可见凭证,
|
|
1659
|
+
// 否则重载会话后这次失败无影无踪(只剩一段被当成正常回复的部分文本)。
|
|
1660
|
+
const body = adaptState.errorMessage ?? '未知错误';
|
|
1661
|
+
// 残句并入凭证消息(显示用途,截断):live 视图里用户看到过的部分输出
|
|
1662
|
+
// 重载后不再消失;完整残句仍以带 error 标记的 turn 账本为准。
|
|
1663
|
+
// 最后一次尝试若以 turn_end(error) 收尾,partial 在 lastTurnContent;
|
|
1664
|
+
// 若直接 abort(无 turn_end),partial 还挂在 callStreamedContent 上。
|
|
1665
|
+
const danglingPartial = adaptState.callStreamedContent ?? '';
|
|
1666
|
+
// 回退只在「最后一个 turn 是失败轮」时启用:最终 abort 不产 turn_end 时
|
|
1667
|
+
// lastTurnContent 会停留在上一轮**成功**的正文上,直接用会把完整回复
|
|
1668
|
+
// 冒充成「中断前的部分输出」
|
|
1669
|
+
const finalPartial = danglingPartial || (adaptState.lastTurnError ? (adaptState.lastTurnContent ?? '') : '');
|
|
1670
|
+
const partialNote = finalPartial
|
|
1671
|
+
? `\n\n---\n中断前的部分输出(非完整回复):\n${finalPartial.slice(0, LLM_ERROR_PARTIAL_MAX_CHARS)}${finalPartial.length > LLM_ERROR_PARTIAL_MAX_CHARS ? '\n…(已截断,完整残句见 turn 账本)' : ''}`
|
|
1672
|
+
: '';
|
|
1673
|
+
session.messages.push({
|
|
1674
|
+
role: 'user',
|
|
1675
|
+
content: `模型调用失败:${body}。可继续对话让 agent 从当前状态接着做,或稍后重试。${partialNote}`,
|
|
1676
|
+
timestamp: Date.now(),
|
|
1677
|
+
metadata: {
|
|
1678
|
+
source: 'runStopped',
|
|
1679
|
+
turnId: currentTurnId,
|
|
1680
|
+
stopReason: 'llm_error',
|
|
1681
|
+
},
|
|
1682
|
+
});
|
|
1683
|
+
session.metadata = {
|
|
1684
|
+
...session.metadata,
|
|
1685
|
+
lastStop: {
|
|
1686
|
+
reason: 'llm_error',
|
|
1687
|
+
message: body,
|
|
1688
|
+
turnId: currentTurnId,
|
|
1689
|
+
at: Date.now(),
|
|
1690
|
+
},
|
|
1691
|
+
};
|
|
1692
|
+
// 最后一次失败尝试的 partial 也留账:abort 路径不再产 turn_end,
|
|
1693
|
+
// 此处不记的话最后尝试的输出只剩前端 live 视图(重载即失)。
|
|
1694
|
+
// 只补「无 turn_end」的缺口;turn_end(error) 路径已在账本里,不得重复记。
|
|
1695
|
+
if (hasTurnEnd && danglingPartial) {
|
|
1696
|
+
session.turns.push({
|
|
1697
|
+
id: `turn_${Date.now()}`,
|
|
1698
|
+
inputCount: Math.max(0, session.messages.length - 1),
|
|
1699
|
+
output: { role: 'assistant', content: danglingPartial, timestamp: Date.now(), agentId: _agentId },
|
|
1700
|
+
durationMs: 0,
|
|
1701
|
+
model: effectiveRunConfig.model ?? 'unknown',
|
|
1702
|
+
timestamp: Date.now(),
|
|
1703
|
+
error: true,
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
else if (adaptState.loopEndReason === 'should_stop') {
|
|
1222
1708
|
const label = adaptState.stopReason === 'behavior_stopped'
|
|
1223
1709
|
? '引擎监督器判定停止'
|
|
1224
1710
|
: adaptState.stopReason === 'policy_stopped'
|
|
@@ -1262,18 +1748,26 @@ export class SessionAwareRunner {
|
|
|
1262
1748
|
session.metadata = restMeta;
|
|
1263
1749
|
clearLastStop = true;
|
|
1264
1750
|
}
|
|
1265
|
-
// turn 闭标(write-once
|
|
1266
|
-
|
|
1751
|
+
// turn 闭标(write-once)。插话开启的旧 turn 在注入时已经闭合。
|
|
1752
|
+
if (!closedInsertedTurnIds.has(currentTurnId)) {
|
|
1753
|
+
this.appendTurnEnd(session.messages, currentTurnId);
|
|
1754
|
+
}
|
|
1267
1755
|
// 11. 引擎异常退出时的 session 一致性修复(须在 Observer final 采样之前)
|
|
1268
1756
|
if (!hasTurnEnd) {
|
|
1269
1757
|
const fallbackContent = streamedContent || '';
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1758
|
+
const failedRun = adaptState.loopEndReason === 'error';
|
|
1759
|
+
// 失败 run 空正文也留账(与 error turn_end 口径一致);正常/崩溃路径仍按有内容才记
|
|
1760
|
+
if (fallbackContent || failedRun) {
|
|
1761
|
+
// 失败 run 的部分流出不得冒充 assistant 回复入历史——失败凭证已由
|
|
1762
|
+
// runStopped 消息承担;只落一条带 error 标记的 turn 账本保留审计。
|
|
1763
|
+
if (!failedRun) {
|
|
1764
|
+
session.messages.push({
|
|
1765
|
+
role: 'assistant',
|
|
1766
|
+
content: fallbackContent,
|
|
1767
|
+
timestamp: Date.now(),
|
|
1768
|
+
agentId: _agentId,
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1277
1771
|
session.turns.push({
|
|
1278
1772
|
id: `turn_${Date.now()}`,
|
|
1279
1773
|
inputCount: Math.max(0, session.messages.length - 1),
|
|
@@ -1282,13 +1776,24 @@ export class SessionAwareRunner {
|
|
|
1282
1776
|
durationMs: 0,
|
|
1283
1777
|
model: effectiveRunConfig.model ?? 'unknown',
|
|
1284
1778
|
timestamp: Date.now(),
|
|
1779
|
+
...(failedRun ? { error: true } : {}),
|
|
1285
1780
|
});
|
|
1286
1781
|
}
|
|
1287
1782
|
}
|
|
1288
1783
|
// Observer:记录最终 messages 与 endReason(真正 close 在 finally,保证异常也闭合)
|
|
1289
1784
|
observerFinalMessages = session.messages;
|
|
1290
1785
|
// P5: 使用 stopReason 区分终态(context_stopped / behavior_stopped / policy_stopped / security_stopped / completed)
|
|
1291
|
-
|
|
1786
|
+
// LLM 错误路径只设 loopEndReason='error'、不设 stopReason;若在此回落到 hasTurnEnd,
|
|
1787
|
+
// 一次彻底失败会被记成 completed(run.timing / Observer / 指标全部失真)。
|
|
1788
|
+
observerEndReason =
|
|
1789
|
+
adaptState.stopReason ??
|
|
1790
|
+
(adaptState.loopEndReason === 'error'
|
|
1791
|
+
? 'error'
|
|
1792
|
+
: adaptState.loopEndReason === 'aborted'
|
|
1793
|
+
? 'aborted'
|
|
1794
|
+
: hasTurnEnd
|
|
1795
|
+
? 'completed'
|
|
1796
|
+
: 'no_turn_end');
|
|
1292
1797
|
// 中止标记:仅在本轮**未完成**被掐断时打标(hasTurnEnd = 正常收尾)。
|
|
1293
1798
|
// 迟到 abort / signal 竞态不得给已完成轮贴编辑重发。
|
|
1294
1799
|
let clearAbortedTurn = false;
|
|
@@ -1312,15 +1817,10 @@ export class SessionAwareRunner {
|
|
|
1312
1817
|
turnFileUndo = undefined;
|
|
1313
1818
|
}
|
|
1314
1819
|
if (abortedMidTurn) {
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
if (m.role === 'user' && !isEngineCarrierSource(m.metadata?.source)) {
|
|
1320
|
-
userIdx = i;
|
|
1321
|
-
break;
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1820
|
+
// 中止轮的用户气泡 = 本轮 input 对象本身(push 于步骤 5,bake 之前就已在列)。
|
|
1821
|
+
// 按对象身份定位而非形状扫描:abort 落在 bake 之前的窗口(上下文装配含 LLM intent)
|
|
1822
|
+
// 时 input 尚未定形 turn_start,形状扫描会误锚到上一轮的开轮信封,截断掉整轮历史
|
|
1823
|
+
const userIdx = session.messages.lastIndexOf(input);
|
|
1324
1824
|
if (userIdx >= 0) {
|
|
1325
1825
|
session.metadata = {
|
|
1326
1826
|
...session.metadata,
|
|
@@ -1351,6 +1851,8 @@ export class SessionAwareRunner {
|
|
|
1351
1851
|
};
|
|
1352
1852
|
}
|
|
1353
1853
|
await this.store.save(sessionId, session);
|
|
1854
|
+
// 收尾权威写成功:剩余注入条目一并确认(此后 close 不再重投)
|
|
1855
|
+
flushInboxAcks();
|
|
1354
1856
|
if (clearAbortedTurn && this.store.updateMetadata) {
|
|
1355
1857
|
await this.store.updateMetadata(sessionId, (meta) => {
|
|
1356
1858
|
delete meta.abortedTurn;
|
|
@@ -1418,11 +1920,34 @@ export class SessionAwareRunner {
|
|
|
1418
1920
|
throw err;
|
|
1419
1921
|
}
|
|
1420
1922
|
finally {
|
|
1421
|
-
//
|
|
1422
|
-
//
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1923
|
+
// run 收口:reason = 观测口径,stopReason = 停止闸门。
|
|
1924
|
+
// 计时进 trace(run.timing);console 保留一条完整生命周期日志——前次事故
|
|
1925
|
+
// 「run 结束原因零日志、只能靠反推落盘消息定位」,该留痕不随探针删除。
|
|
1926
|
+
const runEndReason = observerEndReason ?? (signal?.aborted ? 'aborted' : 'unknown');
|
|
1927
|
+
const runEndDurMs = Date.now() - timingRunEnter;
|
|
1928
|
+
try {
|
|
1929
|
+
const runEndTiming = {
|
|
1930
|
+
type: 'run.timing',
|
|
1931
|
+
timestamp: Date.now(),
|
|
1932
|
+
sessionId,
|
|
1933
|
+
agentId: _agentId,
|
|
1934
|
+
data: {
|
|
1935
|
+
stage: 'run_end',
|
|
1936
|
+
durMs: runEndDurMs,
|
|
1937
|
+
reason: runEndReason,
|
|
1938
|
+
loopEnd: adaptState.loopEndReason,
|
|
1939
|
+
stopReason: adaptState.stopReason,
|
|
1940
|
+
},
|
|
1941
|
+
};
|
|
1942
|
+
this.config.eventSink?.(runEndTiming, { sessionId, agentId: _agentId });
|
|
1943
|
+
// Hub 只收有 run 记录的 run_end(recordRunStart 前失败时不发,避免归到上一轮 run)
|
|
1944
|
+
if (observerRunId)
|
|
1945
|
+
this.emitObserved(runEndTiming);
|
|
1946
|
+
}
|
|
1947
|
+
catch {
|
|
1948
|
+
// finally 内的观测失败不得吞掉后续收口(detachSession / ObserverHub)
|
|
1949
|
+
}
|
|
1950
|
+
console.log(`[Runner] run end session=${sessionId} reason=${runEndReason} dur=${runEndDurMs}ms` +
|
|
1426
1951
|
` loopEnd=${adaptState.loopEndReason ?? 'none'}` +
|
|
1427
1952
|
(adaptState.stopReason ? ` stopReason=${adaptState.stopReason}` : ''));
|
|
1428
1953
|
// 清理 task service 的活 session 缓存(避免长时间运行进程内存泄漏)
|
|
@@ -1462,6 +1987,7 @@ export class SessionAwareRunner {
|
|
|
1462
1987
|
// 观测收口失败不阻断锁释放
|
|
1463
1988
|
}
|
|
1464
1989
|
}
|
|
1990
|
+
inboxRun?.close();
|
|
1465
1991
|
release();
|
|
1466
1992
|
gateRelease?.();
|
|
1467
1993
|
}
|
|
@@ -1496,6 +2022,8 @@ export class SessionAwareRunner {
|
|
|
1496
2022
|
messages: session.messages,
|
|
1497
2023
|
summarize: options.summarize,
|
|
1498
2024
|
compactTargetTokens: options.compactTargetTokens,
|
|
2025
|
+
// 交接式摘要素材:task 快照(裸状态块,不含对话引导语)随指令尾部注入
|
|
2026
|
+
taskSnapshot: renderSessionTasksInjection(session.tasks ?? [], { includeGuidance: false }),
|
|
1499
2027
|
});
|
|
1500
2028
|
if (result.ok && result.summary && result.compacted) {
|
|
1501
2029
|
const snap = {
|
|
@@ -1627,19 +2155,110 @@ export class SessionAwareRunner {
|
|
|
1627
2155
|
}
|
|
1628
2156
|
userMessage.metadata = { ...userMessage.metadata, turnId };
|
|
1629
2157
|
}
|
|
1630
|
-
/**
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
parseTurnIdFromContent(m.content) === turnId);
|
|
1634
|
-
if (exists) {
|
|
1635
|
-
throw new Error(`turn_end already exists (turnId=${turnId})`);
|
|
1636
|
-
}
|
|
1637
|
-
session.messages.push({
|
|
2158
|
+
/** 构造 turn 闭标消息(write-once 由调用处重复检查保证) */
|
|
2159
|
+
makeTurnEndMessage(turnId) {
|
|
2160
|
+
return {
|
|
1638
2161
|
role: 'user',
|
|
1639
2162
|
content: formatTurnEndContent(turnId),
|
|
1640
2163
|
timestamp: Date.now(),
|
|
1641
2164
|
metadata: { source: 'turnEnd', turnId },
|
|
1642
|
-
}
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* 追加 turn 闭标(幂等收养,按信封区间判形)。
|
|
2169
|
+
*
|
|
2170
|
+
* turn_end 是状态标记(turn 已闭)而非事件:崩溃续跑时 ensurePreviousTurnClosed
|
|
2171
|
+
* 会为上一个未闭信封补写闭标(它是第二处闭标写者,规则相近),同 id 的历史闭标
|
|
2172
|
+
* 不算「本信封已闭」——只有本信封区间(最后一个同 id turn_start 之后)已存在
|
|
2173
|
+
* 闭标才跳过。曾经的全局 write-once throw 把良性重复升级成 run error
|
|
2174
|
+
* (loop 已 completed 仍被中止,2026-10-28 事故)。
|
|
2175
|
+
*
|
|
2176
|
+
* 边界:找不到同 id turn_start(lastStartIdx=-1,如 abort-before-bake)时按
|
|
2177
|
+
* 「全序列已有一枚闭标即收养」处理——不动消息数组,交由下一轮修复器收敛。
|
|
2178
|
+
*
|
|
2179
|
+
* @param messages - 会话消息序列(append-only)
|
|
2180
|
+
* @param turnId - 本 turn id
|
|
2181
|
+
*/
|
|
2182
|
+
appendTurnEnd(messages, turnId) {
|
|
2183
|
+
let lastStartIdx = -1;
|
|
2184
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
2185
|
+
const m = messages[i];
|
|
2186
|
+
if (isTurnStartContent(m.content) && parseTurnIdFromContent(m.content) === turnId) {
|
|
2187
|
+
lastStartIdx = i;
|
|
2188
|
+
break;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
const envelopeStart = lastStartIdx + 1;
|
|
2192
|
+
const exists = messages.some((m, i) => i >= envelopeStart &&
|
|
2193
|
+
m.metadata?.source === 'turnEnd' &&
|
|
2194
|
+
parseTurnIdFromContent(m.content) === turnId);
|
|
2195
|
+
if (exists)
|
|
2196
|
+
return;
|
|
2197
|
+
messages.push(this.makeTurnEndMessage(turnId));
|
|
2198
|
+
}
|
|
2199
|
+
/**
|
|
2200
|
+
* 尽力持久化 turnSeq 计数器(缺 updateMetadata 的 store 跳过,收尾整包 save 兜底)。
|
|
2201
|
+
*
|
|
2202
|
+
* 失败不中断 Run(幂等收养已兜住 id 复用的硬失败),但必须留痕:
|
|
2203
|
+
* 2026-10-28 事故的事后诊断正困于「计数器丢失」无任何日志。
|
|
2204
|
+
*
|
|
2205
|
+
* @param sessionId - 会话 id
|
|
2206
|
+
* @param turnSeq - 已分配的最新序号
|
|
2207
|
+
*/
|
|
2208
|
+
async persistTurnSeq(sessionId, turnSeq) {
|
|
2209
|
+
if (!this.store.updateMetadata)
|
|
2210
|
+
return;
|
|
2211
|
+
try {
|
|
2212
|
+
await this.store.updateMetadata(sessionId, (meta) => {
|
|
2213
|
+
meta.turnSeq = turnSeq;
|
|
2214
|
+
});
|
|
2215
|
+
}
|
|
2216
|
+
catch (err) {
|
|
2217
|
+
// 吞掉但留痕:同会话串行互斥下无并发写者(分布式 lease 不覆盖 store 写锁——
|
|
2218
|
+
// 跨进程部署的既有缺口),失败仅使续跑退化到幂等收养路径,不产生新失败面。
|
|
2219
|
+
console.warn(`[Runner] persist turnSeq failed session=${sessionId} seq=${turnSeq}: ${String(err)}`);
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
/**
|
|
2223
|
+
* Run 进行中转录增量落盘:把 durable 口径的历史对齐到存储。
|
|
2224
|
+
*
|
|
2225
|
+
* 口径与收尾合并一致(ephemeral 运行期消息不落历史);调用方契约:
|
|
2226
|
+
* turn_start 定形之后才可同步(bake 原地改写 user 消息)。尽力而为——
|
|
2227
|
+
* 失败不中断 Run(收尾整包 save 是权威写),store 无 syncMessages 时跳过。
|
|
2228
|
+
*
|
|
2229
|
+
* @param sessionId - 会话 id
|
|
2230
|
+
* @param agentId - 本 Run 身份(assistant/tool 归因,首次同步前补齐)
|
|
2231
|
+
* @param keptPrefix - 上下文租约点之前的 Discourse 前缀(与收尾 keptPrefix 同源)
|
|
2232
|
+
* @param runMessages - 本 Run 视图消息(含 ephemeral,此处过滤)
|
|
2233
|
+
* @returns 是否成功对齐(false 时调用方不得推进已同步计数,待下个事件重试)
|
|
2234
|
+
*/
|
|
2235
|
+
async persistRunMessages(sessionId, agentId, keptPrefix, runMessages) {
|
|
2236
|
+
const sync = this.store.syncMessages;
|
|
2237
|
+
if (!sync) {
|
|
2238
|
+
if (!this.warnedMissingSync) {
|
|
2239
|
+
this.warnedMissingSync = true;
|
|
2240
|
+
console.warn('[octopi] SessionStore lacks syncMessages; run transcript incremental persist disabled (final save remains authoritative)');
|
|
2241
|
+
}
|
|
2242
|
+
return true; // 无通道 = 非失败,不需要重试
|
|
2243
|
+
}
|
|
2244
|
+
try {
|
|
2245
|
+
// 模型 2 归因:assistant/tool 消息补齐本 Run 的 agentId。必须发生在该消息
|
|
2246
|
+
// 首次同步之前(已同步前缀不得再原地修改);收尾写回处保留同口径兜底循环。
|
|
2247
|
+
for (const m of runMessages) {
|
|
2248
|
+
if ((m.role === 'assistant' || m.role === 'tool') && m.agentId === undefined) {
|
|
2249
|
+
m.agentId = agentId;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
await sync.call(this.store, sessionId, [
|
|
2253
|
+
...keptPrefix,
|
|
2254
|
+
...runMessages.filter((m) => m.ephemeral !== true),
|
|
2255
|
+
]);
|
|
2256
|
+
return true;
|
|
2257
|
+
}
|
|
2258
|
+
catch (err) {
|
|
2259
|
+
console.warn(`[octopi] run transcript incremental persist failed (session=${sessionId}): ${err instanceof Error ? err.message : String(err)}`);
|
|
2260
|
+
return false;
|
|
2261
|
+
}
|
|
1643
2262
|
}
|
|
1644
2263
|
/** 旧路径:persona + injectedContext 字符串拼接;结果返回给 runContext,不写共享 Agent */
|
|
1645
2264
|
concatSystemPrompt(basePrompt, injectedContext, personaFromResolver) {
|