@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
|
@@ -79,6 +79,11 @@ export interface SenseFilter {
|
|
|
79
79
|
condition?: string;
|
|
80
80
|
/** 代码引用(如 "./handler.ts:shouldExtract"),与 condition 互斥 */
|
|
81
81
|
conditionRef?: string;
|
|
82
|
+
/**
|
|
83
|
+
* 事件累积触发阈值:每收到一个匹配事件计数 +1,累计达到阈值才评估/触发,
|
|
84
|
+
* 触发后清零(缺省 1 = 来一件发一件)。用于「增量 N 条才跑一次」的节流。
|
|
85
|
+
*/
|
|
86
|
+
minEvents?: number;
|
|
82
87
|
/** 该子系统可能产生的事件类型(用于静态循环检测,LLM 子系统建议声明 ['*']) */
|
|
83
88
|
emits?: string[];
|
|
84
89
|
}
|
|
@@ -90,6 +95,10 @@ export interface SenseConfig {
|
|
|
90
95
|
filter?: SenseFilter;
|
|
91
96
|
/** schedule 模式:轮询间隔(毫秒) */
|
|
92
97
|
interval?: number;
|
|
98
|
+
/** schedule 模式:注册后立即补一次首跳(长 interval 跨不过进程生命周期时的保底脉搏) */
|
|
99
|
+
runOnStart?: boolean;
|
|
100
|
+
/** 本子系统的触发冷却(毫秒);缺省用 SenseEngine 全局 defaultCooldownMs */
|
|
101
|
+
cooldownMs?: number;
|
|
93
102
|
isolation: IsolationLevel;
|
|
94
103
|
/** isolation=partial 时,可见的字段列表 */
|
|
95
104
|
fields?: ContextField[];
|
|
@@ -94,12 +94,18 @@ export class RunnerChildRunPort {
|
|
|
94
94
|
switch (event.type) {
|
|
95
95
|
case 'turn.end': {
|
|
96
96
|
const data = event.data;
|
|
97
|
-
|
|
97
|
+
// 失败尝试的 content 是中断残句,不是委派结果;error 布尔标记也不是错误文本
|
|
98
|
+
//(String(true)='true' 会占位并挡住后面 engine.error 的真消息)
|
|
99
|
+
const failed = Boolean(data.error);
|
|
100
|
+
if (!failed && typeof data.content === 'string' && data.content.length > 0) {
|
|
98
101
|
output = data.content;
|
|
99
102
|
}
|
|
100
103
|
addUsage(usage, data.usage);
|
|
101
|
-
if (
|
|
102
|
-
|
|
104
|
+
if (error == null) {
|
|
105
|
+
if (data.error instanceof Error)
|
|
106
|
+
error = data.error.message;
|
|
107
|
+
else if (typeof data.error === 'string' && data.error.length > 0)
|
|
108
|
+
error = data.error;
|
|
103
109
|
}
|
|
104
110
|
break;
|
|
105
111
|
}
|
|
@@ -109,6 +115,14 @@ export class RunnerChildRunPort {
|
|
|
109
115
|
error = message;
|
|
110
116
|
break;
|
|
111
117
|
}
|
|
118
|
+
case 'engine.end': {
|
|
119
|
+
// 非 signal.aborted 触发的 aborted(loop 检测到取消)也要如实归中止,
|
|
120
|
+
// 不得走 default 当成功
|
|
121
|
+
const data = event.data;
|
|
122
|
+
if (data.reason === 'aborted')
|
|
123
|
+
aborted = true;
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
112
126
|
default:
|
|
113
127
|
break;
|
|
114
128
|
}
|
|
@@ -119,13 +133,15 @@ export class RunnerChildRunPort {
|
|
|
119
133
|
}
|
|
120
134
|
if (signal?.aborted)
|
|
121
135
|
aborted = true;
|
|
136
|
+
const finalError = aborted ? (error ?? 'aborted') : error;
|
|
122
137
|
return {
|
|
123
138
|
childSessionId,
|
|
124
139
|
childRunId,
|
|
125
|
-
output
|
|
140
|
+
// 失败/中止不出 output:前一轮成功正文或残句不得冒充「已交付结果」
|
|
141
|
+
...(finalError ? {} : { output }),
|
|
126
142
|
...(artifacts.length > 0 ? { artifacts } : {}),
|
|
127
143
|
usage,
|
|
128
|
-
error:
|
|
144
|
+
error: finalError,
|
|
129
145
|
aborted,
|
|
130
146
|
};
|
|
131
147
|
}
|
|
@@ -26,6 +26,8 @@ export function renderDelegationNotice(delegation) {
|
|
|
26
26
|
`status="${delegation.status}"`,
|
|
27
27
|
`agent="${escapeAttr(delegation.resolvedAgentId ?? delegation.target.agentId ?? '')}"`,
|
|
28
28
|
`task="${escapeAttr(truncate(delegation.task, 120))}"`,
|
|
29
|
+
`parent_run_id="${escapeAttr(delegation.parent.runId)}"`,
|
|
30
|
+
`child_run_id="${escapeAttr(delegation.childRunId ?? '')}"`,
|
|
29
31
|
];
|
|
30
32
|
const body = [];
|
|
31
33
|
if (delegation.output) {
|
|
@@ -37,10 +39,9 @@ export function renderDelegationNotice(delegation) {
|
|
|
37
39
|
if (delegation.artifacts?.length) {
|
|
38
40
|
body.push(`<artifacts>${delegation.artifacts.map((a) => escapeText(a)).join(', ')}</artifacts>`);
|
|
39
41
|
}
|
|
40
|
-
const tag = delegation.status === 'completed' ? 'delegation_completed' : 'delegation_failed';
|
|
41
42
|
return body.length > 0
|
|
42
|
-
?
|
|
43
|
-
:
|
|
43
|
+
? `<delegation_result ${attrs.join(' ')}>${body.join('')}</delegation_result>`
|
|
44
|
+
: `<delegation_result ${attrs.join(' ')}/>`;
|
|
44
45
|
}
|
|
45
46
|
/** 委派终态 → notify 通道 reason */
|
|
46
47
|
export function delegationReason(delegation) {
|
|
@@ -466,9 +466,8 @@ export class DelegateService {
|
|
|
466
466
|
// 条件置位:仅当投递期间未被回滚(仍 delivering)才记已送达。
|
|
467
467
|
// 若 dropped 已回滚成 pending,或父已 get 先行 surfaced,均不得覆盖
|
|
468
468
|
//(catch 的条件回滚同理——两个方向都只动 delivering 自己的占位)。
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
}
|
|
469
|
+
// surfaced 由 Runner 把结果追加进父上下文时确认(见 wiring 的 deliveryAck)。
|
|
470
|
+
// 总线 emit / Runtime 受理只证明通知在投递,不证明父模型已经可见。
|
|
472
471
|
}
|
|
473
472
|
catch (err) {
|
|
474
473
|
// 投递失败条件回滚(仅 delivering,与成功路径的条件置位对称):
|
|
@@ -104,19 +104,20 @@ export function createDelegationRuntime(options) {
|
|
|
104
104
|
delegation: effectiveDelegationPolicy(agent.delegation),
|
|
105
105
|
status: 'idle',
|
|
106
106
|
});
|
|
107
|
+
agent.runner.setDelegationDeliveryAck((delegationId) => {
|
|
108
|
+
if (delegationStore.get(delegationId))
|
|
109
|
+
delegationStore.markSurfaced(delegationId);
|
|
110
|
+
});
|
|
107
111
|
// delegate_* 工具只挂给能委派的 agent(§9.3 命名委派)
|
|
108
112
|
if (effectiveDelegationPolicy(agent.delegation).canDelegate) {
|
|
109
113
|
agent.registerTools?.(delegateTools);
|
|
110
|
-
//
|
|
111
|
-
|
|
112
|
-
agent.agent.setSteeringMessages(async () => {
|
|
114
|
+
// Runner 在每次 Agent.run 组合提示源;不覆盖用户/delegation 的 inbox 消费。
|
|
115
|
+
agent.runner.setSteeringProvider(async () => {
|
|
113
116
|
const { getRunSessionId } = await import('../../run/run-scope.js');
|
|
114
117
|
const sessionId = getRunSessionId(agent.agent.contextSessionId);
|
|
115
118
|
if (!sessionId)
|
|
116
119
|
return [];
|
|
117
120
|
const hint = service.renderStatusHint(sessionId);
|
|
118
|
-
// ephemeral:本轮可见、不落历史。否则「当时的状态」会被固化进 session,
|
|
119
|
-
// 状态过期后仍留在上下文里,且每次状态变化都会打穿前缀缓存。
|
|
120
121
|
return hint
|
|
121
122
|
? [{ role: 'system', content: hint, timestamp: Date.now(), ephemeral: true }]
|
|
122
123
|
: [];
|
|
@@ -17,7 +17,7 @@ export class LLMReflector {
|
|
|
17
17
|
this._model = config.model;
|
|
18
18
|
this._modelName = config.modelName;
|
|
19
19
|
this._memoryStore = config.memoryStore;
|
|
20
|
-
this._temperature = config.temperature
|
|
20
|
+
this._temperature = config.temperature;
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
23
|
* 评估一次执行的质量
|
|
@@ -6,6 +6,36 @@
|
|
|
6
6
|
* @module harness/context/capabilities/compact/engine
|
|
7
7
|
*/
|
|
8
8
|
import type { CompactEngine, CreateCompactEngineOptions } from './types.js';
|
|
9
|
+
/** 输出闸门:摘要落盘前的污染检测(回声/对话体续写)。
|
|
10
|
+
*
|
|
11
|
+
* 失效模式(2026-10-28 实测):模型把对话样本当语料续写,产出「assistant 半句 + 逐字
|
|
12
|
+
* tool-call」的原文复读,使折叠掉的中段信息全丢。本闸门兜底校验:命中即判污染,交由
|
|
13
|
+
* 调用方重试或按 onSummarizeFail 降级(不得静默存坏摘要)。
|
|
14
|
+
*
|
|
15
|
+
* 回声判据是结构性的(评审 F2/F3/F4):单条证据引用合法,成段复读非法——
|
|
16
|
+
* 命中输入行 ≥3 条,或命中字符占输出 ≥60%(输出基本就是复读),才判污染。
|
|
17
|
+
*
|
|
18
|
+
* @param text - 模型输出
|
|
19
|
+
* @param sourceText - 「模型实际看到的会话文本」投影(回声比对源;不得含指令本身——
|
|
20
|
+
* 指令的四段式标题会合法出现在输出里)
|
|
21
|
+
* @returns 命中原因;干净返回 null
|
|
22
|
+
*/
|
|
23
|
+
export declare function detectSummaryContamination(text: string, sourceText?: string): string | null;
|
|
24
|
+
/** 摘要软目标预算(P1c 拍板缺省 clamp(2%, 2k, 8k))。
|
|
25
|
+
*
|
|
26
|
+
* 软目标语义:只写进指令当「尽量控制在 N tokens」,禁止作为 provider max_tokens 硬顶
|
|
27
|
+
* (硬截断产生静默半截摘要,业务完整性优先)。公式即拍板三参数 clamp(2%, 2k, 8k),
|
|
28
|
+
* 不附加「不超过输入」等未记录规则(评审 F13:规格外规则会与模型互相算计)。
|
|
29
|
+
*
|
|
30
|
+
* @param tokensBefore - 输入 token 估算
|
|
31
|
+
* @param budget - 可配置 ratioPct/minTokens/maxTokens
|
|
32
|
+
* @returns 软目标 token 数
|
|
33
|
+
*/
|
|
34
|
+
export declare function summarySoftTargetTokens(tokensBefore: number, budget?: {
|
|
35
|
+
ratioPct?: number;
|
|
36
|
+
minTokens?: number;
|
|
37
|
+
maxTokens?: number;
|
|
38
|
+
}): number;
|
|
9
39
|
/**
|
|
10
40
|
* 创建 CompactEngine
|
|
11
41
|
*
|
|
@@ -6,9 +6,11 @@
|
|
|
6
6
|
* @module harness/context/capabilities/compact/engine
|
|
7
7
|
*/
|
|
8
8
|
import { getTextContent } from '@octopi-agent/core/types.js';
|
|
9
|
+
import { isCannedRefusalText } from '@octopi-agent/core/loop/canned-refusal.js';
|
|
9
10
|
import { HeuristicTokenEstimator } from '../../token-estimator.js';
|
|
10
11
|
import { buildPolicyRegistry } from '../summary/resolver.js';
|
|
11
|
-
import {
|
|
12
|
+
import { HANDOVER_SUMMARY_TASK, buildHandoverPrompt, buildHandoverUserContent, clampSummaryProviderCap, } from './handover.js';
|
|
13
|
+
import { estimateLLMMessages } from '../../token-estimator.js';
|
|
12
14
|
function defaultEstimator() {
|
|
13
15
|
const e = new HeuristicTokenEstimator();
|
|
14
16
|
return {
|
|
@@ -16,8 +18,88 @@ function defaultEstimator() {
|
|
|
16
18
|
estimateText: (t) => e.estimateText(t),
|
|
17
19
|
};
|
|
18
20
|
}
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
+
/** 摘要任务/指令/合并语义已单源化到 ./handover.ts(F8 模板统一)——此处仅保留算法与闸门。 */
|
|
22
|
+
/** 重试仍污染时附加的加严指令(输出闸门二次机会用) */
|
|
23
|
+
const STRICT_RETRY_SUFFIX = '\n\nIMPORTANT: your previous attempt replayed input passages. Write fresh prose only. ' +
|
|
24
|
+
'Do not copy input lines. No dialogue transcript, no role-marker lines, no tool-call syntax.';
|
|
25
|
+
/** 输出闸门形状词表(评审 F3 扩表):对话体/工具调用语法。
|
|
26
|
+
* 角色行用行首语义(防正文误伤);工具调用语法 anywhere 判定——指令已不含这些
|
|
27
|
+
* 字面量(F15),输出里出现即高概率是续写污染。 */
|
|
28
|
+
const TRANSCRIPT_SHAPE = /<function[=_]|<\/?tool_call|<invoke[ \t]|<\/?tool_use|<parameter[ >]|antml:|Tool Calls:|\[(ASSISTANT|USER|TOOL|SYSTEM)\]|^\s*(Assistant|Human|User|System):/im;
|
|
29
|
+
/** 输出闸门:摘要落盘前的污染检测(回声/对话体续写)。
|
|
30
|
+
*
|
|
31
|
+
* 失效模式(2026-10-28 实测):模型把对话样本当语料续写,产出「assistant 半句 + 逐字
|
|
32
|
+
* tool-call」的原文复读,使折叠掉的中段信息全丢。本闸门兜底校验:命中即判污染,交由
|
|
33
|
+
* 调用方重试或按 onSummarizeFail 降级(不得静默存坏摘要)。
|
|
34
|
+
*
|
|
35
|
+
* 回声判据是结构性的(评审 F2/F3/F4):单条证据引用合法,成段复读非法——
|
|
36
|
+
* 命中输入行 ≥3 条,或命中字符占输出 ≥60%(输出基本就是复读),才判污染。
|
|
37
|
+
*
|
|
38
|
+
* @param text - 模型输出
|
|
39
|
+
* @param sourceText - 「模型实际看到的会话文本」投影(回声比对源;不得含指令本身——
|
|
40
|
+
* 指令的四段式标题会合法出现在输出里)
|
|
41
|
+
* @returns 命中原因;干净返回 null
|
|
42
|
+
*/
|
|
43
|
+
export function detectSummaryContamination(text, sourceText) {
|
|
44
|
+
// 内容过滤罐头拒答:网关 200 内联拒答(正文被替换成固定英文罐头)不是摘要,
|
|
45
|
+
// 一律判污染——交由既有的「一次加严重试 → 二次抛错降级」链路处理
|
|
46
|
+
if (isCannedRefusalText(text)) {
|
|
47
|
+
return 'canned_refusal';
|
|
48
|
+
}
|
|
49
|
+
if (TRANSCRIPT_SHAPE.test(text)) {
|
|
50
|
+
return 'transcript_shape';
|
|
51
|
+
}
|
|
52
|
+
if (sourceText) {
|
|
53
|
+
let hits = 0;
|
|
54
|
+
let hitChars = 0;
|
|
55
|
+
for (const line of sourceText.split('\n')) {
|
|
56
|
+
const trimmed = line.trim();
|
|
57
|
+
if (trimmed.length >= 40 && text.includes(trimmed)) {
|
|
58
|
+
hits += 1;
|
|
59
|
+
hitChars += trimmed.length;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (hits >= 3 || (hitChars >= 40 && hitChars >= text.length * 0.6)) {
|
|
63
|
+
return 'verbatim_echo';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
/** 带输出闸门的摘要执行:首次污染给一次加严重试,二次污染抛错交 onSummarizeFail 降级。
|
|
69
|
+
*
|
|
70
|
+
* @param invoke - 摘要调用(strict=true 时需附加加严指令)
|
|
71
|
+
* @param sourceText - 回声比对源(喂给模型的输入文本)
|
|
72
|
+
* @returns 干净摘要文本
|
|
73
|
+
* @throws provider 错误,或 `contaminated_output:*`(二次污染)
|
|
74
|
+
*/
|
|
75
|
+
async function invokeGuardedSummarize(invoke, sourceText) {
|
|
76
|
+
let text = await invoke(false);
|
|
77
|
+
if (detectSummaryContamination(text, sourceText)) {
|
|
78
|
+
text = await invoke(true);
|
|
79
|
+
const again = detectSummaryContamination(text, sourceText);
|
|
80
|
+
if (again) {
|
|
81
|
+
throw new Error(`contaminated_output:${again}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return text;
|
|
85
|
+
}
|
|
86
|
+
/** 摘要软目标预算(P1c 拍板缺省 clamp(2%, 2k, 8k))。
|
|
87
|
+
*
|
|
88
|
+
* 软目标语义:只写进指令当「尽量控制在 N tokens」,禁止作为 provider max_tokens 硬顶
|
|
89
|
+
* (硬截断产生静默半截摘要,业务完整性优先)。公式即拍板三参数 clamp(2%, 2k, 8k),
|
|
90
|
+
* 不附加「不超过输入」等未记录规则(评审 F13:规格外规则会与模型互相算计)。
|
|
91
|
+
*
|
|
92
|
+
* @param tokensBefore - 输入 token 估算
|
|
93
|
+
* @param budget - 可配置 ratioPct/minTokens/maxTokens
|
|
94
|
+
* @returns 软目标 token 数
|
|
95
|
+
*/
|
|
96
|
+
export function summarySoftTargetTokens(tokensBefore, budget) {
|
|
97
|
+
const ratioPct = budget?.ratioPct ?? 2;
|
|
98
|
+
const minTokens = budget?.minTokens ?? 2000;
|
|
99
|
+
const maxTokens = budget?.maxTokens ?? 8000;
|
|
100
|
+
const target = Math.floor((tokensBefore * ratioPct) / 100);
|
|
101
|
+
return Math.min(Math.max(target, minTokens), maxTokens);
|
|
102
|
+
}
|
|
21
103
|
function formatMessagesAsText(messages) {
|
|
22
104
|
const parts = [];
|
|
23
105
|
for (const msg of messages) {
|
|
@@ -69,7 +151,8 @@ function asSummaryMessage(summary) {
|
|
|
69
151
|
*/
|
|
70
152
|
export function createCompactEngine(options) {
|
|
71
153
|
const defaults = {
|
|
72
|
-
|
|
154
|
+
// 能力层缺省与 DefaultContextEngine protectFirstN 同源(5,2026-10-28 拍板交接快照头 5)
|
|
155
|
+
protectHead: options?.defaultProtectHead ?? 5,
|
|
73
156
|
protectTail: options?.defaultProtectTail ?? 20,
|
|
74
157
|
targetTokens: options?.defaultTargetTokens,
|
|
75
158
|
mode: (options?.defaultMode ?? 'structure_only'),
|
|
@@ -98,13 +181,21 @@ export function createCompactEngine(options) {
|
|
|
98
181
|
source: {},
|
|
99
182
|
kind: 'conversation',
|
|
100
183
|
policy: opts.summarizePolicy,
|
|
101
|
-
task:
|
|
184
|
+
task: HANDOVER_SUMMARY_TASK,
|
|
102
185
|
};
|
|
103
186
|
try {
|
|
104
|
-
|
|
187
|
+
// 输出闸门与 summarizeFn 路径对齐:污染给一次加严重试,仍污染按失败降级(不静默存坏摘要)
|
|
188
|
+
let r = await port.extract(unit, {
|
|
105
189
|
signal: opts.signal,
|
|
106
190
|
previousSummary: opts.previousSummary,
|
|
107
191
|
});
|
|
192
|
+
if (detectSummaryContamination(r.text, middleText)) {
|
|
193
|
+
r = await port.extract({ ...unit, task: `${HANDOVER_SUMMARY_TASK}${STRICT_RETRY_SUFFIX}` }, { signal: opts.signal, previousSummary: opts.previousSummary });
|
|
194
|
+
const again = detectSummaryContamination(r.text, middleText);
|
|
195
|
+
if (again) {
|
|
196
|
+
return { error: `contaminated_output:${again}` };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
108
199
|
return { summary: r.text, coverage: r.coverage };
|
|
109
200
|
}
|
|
110
201
|
catch (err) {
|
|
@@ -114,40 +205,84 @@ export function createCompactEngine(options) {
|
|
|
114
205
|
}
|
|
115
206
|
}
|
|
116
207
|
if (summarizeFn) {
|
|
208
|
+
// 交接式契约单源(F8 模板统一):模板/指令/合并语义全走 handover.ts——
|
|
209
|
+
// 与 LLMSummaryCompressor 逐字同构,previousSummary 只有一种格式在迭代合并
|
|
210
|
+
const prompt = buildHandoverPrompt({
|
|
211
|
+
maxTokens,
|
|
212
|
+
summarizePolicy: policy,
|
|
213
|
+
previousSummary: opts.previousSummary,
|
|
214
|
+
foldRange: opts.foldRange,
|
|
215
|
+
taskSnapshot: opts.taskSnapshot,
|
|
216
|
+
});
|
|
117
217
|
// 缓存优先:llmPrefix(会话同形 system+history)+ 尾部 user 指令。
|
|
118
218
|
// 禁止把指令塞进 system 或重排历史——否则打穿前缀缓存。
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
219
|
+
const buildPrefixed = () => [
|
|
220
|
+
...opts.llmPrefix,
|
|
221
|
+
{ role: 'user', content: prompt.tailUser },
|
|
222
|
+
];
|
|
223
|
+
// 无 llmPrefix 回退「policy system + 文本化中段」(旁路/旧调用):
|
|
224
|
+
// tool_call-only assistant / 缺 tool_call_id 的 tool 消息会被严格网关 400。
|
|
225
|
+
const buildTextify = () => [
|
|
226
|
+
{ role: 'system', content: prompt.instruction },
|
|
227
|
+
{ role: 'user', content: buildHandoverUserContent(opts, middleText) },
|
|
228
|
+
];
|
|
229
|
+
// 回声比对源 = 模型实际看到的会话文本投影(评审 F2):llmPrefix 分支含 head/middle/tail
|
|
230
|
+
// 全量历史,只比 middleText 会漏掉 head/tail 区回声;指令本身不得进比对源(四段式标题
|
|
231
|
+
// 会合法出现在输出里)。
|
|
232
|
+
const prefixEchoSource = () => (opts.llmPrefix ?? []).map((m) => String(m.content ?? '')).join('\n');
|
|
233
|
+
let usePrefix = Boolean(opts.llmPrefix?.length);
|
|
234
|
+
let llmMessages = usePrefix ? buildPrefixed() : buildTextify();
|
|
235
|
+
let echoSource = usePrefix ? prefixEchoSource() : middleText;
|
|
236
|
+
// 硬顶 = 软目标 4 倍保险丝(P1c 禁硬截断/静默半截),再按窗口钳制(评审 F5):
|
|
237
|
+
// provider 多按 input+max_tokens ≤ window 校验,压缩恰在会话最满时触发,保险丝可能把
|
|
238
|
+
// 请求顶出窗口——放不下就改走文本化中段旁路(cache-miss 如实降级),仍放不下则如实失败。
|
|
239
|
+
const hardCap = (opts.maxSummaryTokens ?? maxTokens) * 4;
|
|
240
|
+
const windowCapOf = (msgs) => clampSummaryProviderCap({
|
|
241
|
+
hardCap,
|
|
242
|
+
// estimateLLMMessages 口径含 tool_calls/content block/消息开销(同 llm-summarizer)
|
|
243
|
+
inputTokens: estimateLLMMessages(msgs),
|
|
244
|
+
contextWindow: opts.contextWindow,
|
|
245
|
+
maxOutputTokens: opts.maxOutputTokens,
|
|
246
|
+
});
|
|
247
|
+
let providerMaxTokens = windowCapOf(llmMessages);
|
|
248
|
+
// F22 可观测:无前缀/被迫旁路 = cache-miss,如实上报,不静默换请求形状
|
|
249
|
+
if (!usePrefix) {
|
|
250
|
+
opts.emit?.({ type: 'compact.summarize_fallback', reason: 'no_prefix', cached: false });
|
|
129
251
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
252
|
+
if (providerMaxTokens < 256 && usePrefix) {
|
|
253
|
+
usePrefix = false;
|
|
254
|
+
llmMessages = buildTextify();
|
|
255
|
+
echoSource = middleText;
|
|
256
|
+
providerMaxTokens = windowCapOf(llmMessages);
|
|
257
|
+
opts.emit?.({ type: 'compact.summarize_fallback', reason: 'window_guard', cached: false });
|
|
258
|
+
}
|
|
259
|
+
if (providerMaxTokens < 256) {
|
|
260
|
+
// F8R-06 可观测:最终失败也是 cache-miss 旁路结果,与 compressor 侧对称上报
|
|
261
|
+
opts.emit?.({ type: 'compact.summarize_fallback', reason: 'window_exhausted', cached: false });
|
|
262
|
+
return { error: 'window_exhausted:summary request cannot fit the model window' };
|
|
141
263
|
}
|
|
142
264
|
try {
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
265
|
+
const invoke = (strict) => {
|
|
266
|
+
const msgs = strict
|
|
267
|
+
? [
|
|
268
|
+
...llmMessages.slice(0, -1),
|
|
269
|
+
{
|
|
270
|
+
...llmMessages[llmMessages.length - 1],
|
|
271
|
+
content: `${String(llmMessages[llmMessages.length - 1].content)}${STRICT_RETRY_SUFFIX}`,
|
|
272
|
+
},
|
|
273
|
+
]
|
|
274
|
+
: llmMessages;
|
|
275
|
+
return summarizeFn(msgs, {
|
|
276
|
+
previousSummary: opts.previousSummary,
|
|
277
|
+
maxTokens: providerMaxTokens,
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
const text = await invokeGuardedSummarize(invoke, echoSource);
|
|
147
281
|
return { summary: text, coverage: 'full' };
|
|
148
282
|
}
|
|
149
283
|
catch (err) {
|
|
150
|
-
//
|
|
284
|
+
// 吞两类抛错并转 error 通道交 onSummarizeFail 降级:① provider 报错/超时;
|
|
285
|
+
// ② 闸门二次污染(contaminated_output:*)。try 内无其他可抛代码,无其他路径可至此
|
|
151
286
|
return { error: err instanceof Error ? err.message : String(err) };
|
|
152
287
|
}
|
|
153
288
|
}
|
|
@@ -161,8 +296,9 @@ export function createCompactEngine(options) {
|
|
|
161
296
|
const tokensBefore = isMessages
|
|
162
297
|
? estimator.estimateMessages(messages)
|
|
163
298
|
: estimator.estimateText(text);
|
|
164
|
-
|
|
165
|
-
const
|
|
299
|
+
// 边界归一:负数无契约语义,按 0 处理(slice 对负数是另一套语义,会切出意外视图)
|
|
300
|
+
const protectHead = Math.max(0, opts.protectHead ?? defaults.protectHead);
|
|
301
|
+
const protectTail = Math.max(0, opts.protectTail ?? defaults.protectTail);
|
|
166
302
|
const mode = opts.mode ?? defaults.mode;
|
|
167
303
|
const targetTokens = opts.targetTokens ?? defaults.targetTokens;
|
|
168
304
|
const onFail = opts.onSummarizeFail ?? 'truncate';
|
|
@@ -179,7 +315,12 @@ export function createCompactEngine(options) {
|
|
|
179
315
|
if (!isMessages) {
|
|
180
316
|
const headChars = Math.floor(text.length * 0.2);
|
|
181
317
|
const tailChars = Math.floor(text.length * 0.2);
|
|
182
|
-
|
|
318
|
+
// 太短无可拆中段(len<5 时 20%×2 皆为 0):原样返回不丢正文(与消息路径 too_short 同语义)
|
|
319
|
+
if (headChars === 0 && tailChars === 0) {
|
|
320
|
+
return { ok: true, compacted: false, reason: 'too_short', tokensBefore, view: text };
|
|
321
|
+
}
|
|
322
|
+
// slice(-0) === slice(0) 返回全量:tailChars=0 时尾段必须显式取空
|
|
323
|
+
const view = `${text.slice(0, headChars)}\n\n[middle removed]\n\n${tailChars > 0 ? text.slice(-tailChars) : ''}`;
|
|
183
324
|
return {
|
|
184
325
|
ok: true,
|
|
185
326
|
compacted: true,
|
|
@@ -194,7 +335,8 @@ export function createCompactEngine(options) {
|
|
|
194
335
|
return { ok: true, compacted: false, reason: 'too_short', tokensBefore, view: messages };
|
|
195
336
|
}
|
|
196
337
|
const head = messages.slice(0, protectHead);
|
|
197
|
-
|
|
338
|
+
// slice(-0) === slice(0) 返回全量:protectTail=0 时 tail 必须显式为空
|
|
339
|
+
const tail = protectTail > 0 ? messages.slice(-protectTail) : [];
|
|
198
340
|
const dropped = messages.length - head.length - tail.length;
|
|
199
341
|
const placeholder = asSummaryMessage(`[Structural compact] dropped ${dropped} middle messages (head_tail_only)`);
|
|
200
342
|
const view = [...head, placeholder, ...tail];
|
|
@@ -210,12 +352,13 @@ export function createCompactEngine(options) {
|
|
|
210
352
|
};
|
|
211
353
|
}
|
|
212
354
|
if (mode === 'summary_only') {
|
|
213
|
-
const maxTokens = opts.maxSummaryTokens ??
|
|
355
|
+
const maxTokens = opts.maxSummaryTokens ?? summarySoftTargetTokens(tokensBefore, opts.summaryBudget);
|
|
214
356
|
const summarized = await summarizeMiddle(text, messages, opts, maxTokens);
|
|
215
357
|
if (!summarized.summary) {
|
|
216
358
|
if (onFail === 'keep_partial' && opts.previousSummary && isMessages) {
|
|
217
|
-
|
|
218
|
-
|
|
359
|
+
// slice(-0) === slice(0) 返回全量:protectTail=0 时 tail 必须显式为空
|
|
360
|
+
const view = [asSummaryMessage(opts.previousSummary), ...(protectTail > 0 ? messages.slice(-protectTail) : [])];
|
|
361
|
+
return { ok: true, compacted: true, reason: 'partial', tokensBefore, tokensAfter: estimator.estimateMessages(view), summary: opts.previousSummary, fresh: false, view };
|
|
219
362
|
}
|
|
220
363
|
if (isMessages) {
|
|
221
364
|
const view = messages.slice(-Math.max(protectTail, 4));
|
|
@@ -227,6 +370,7 @@ export function createCompactEngine(options) {
|
|
|
227
370
|
tokensAfter: estimator.estimateMessages(view),
|
|
228
371
|
// 摘要失败时旧摘要仍有效:summary 字段保留之(与 structure_only 失败兜底同款)
|
|
229
372
|
summary: opts.previousSummary,
|
|
373
|
+
fresh: false,
|
|
230
374
|
view,
|
|
231
375
|
droppedSummary: 'middle dropped; summarizer unavailable',
|
|
232
376
|
};
|
|
@@ -238,6 +382,7 @@ export function createCompactEngine(options) {
|
|
|
238
382
|
reason: 'summarize_failed_truncate',
|
|
239
383
|
tokensBefore,
|
|
240
384
|
summary: opts.previousSummary,
|
|
385
|
+
fresh: false,
|
|
241
386
|
view,
|
|
242
387
|
};
|
|
243
388
|
}
|
|
@@ -252,6 +397,7 @@ export function createCompactEngine(options) {
|
|
|
252
397
|
tokensBefore,
|
|
253
398
|
tokensAfter: estimator.estimateText(summary),
|
|
254
399
|
summary,
|
|
400
|
+
fresh: true,
|
|
255
401
|
coverage: summarized.coverage,
|
|
256
402
|
view: summary,
|
|
257
403
|
};
|
|
@@ -264,6 +410,7 @@ export function createCompactEngine(options) {
|
|
|
264
410
|
tokensBefore,
|
|
265
411
|
tokensAfter: estimator.estimateMessages(view),
|
|
266
412
|
summary,
|
|
413
|
+
fresh: true,
|
|
267
414
|
coverage: summarized.coverage,
|
|
268
415
|
view,
|
|
269
416
|
droppedSummary: `Conversation compressed from ${tokensBefore} tokens`,
|
|
@@ -271,7 +418,7 @@ export function createCompactEngine(options) {
|
|
|
271
418
|
}
|
|
272
419
|
// structure_only(默认)
|
|
273
420
|
if (!isMessages) {
|
|
274
|
-
const maxTokens = opts.maxSummaryTokens ??
|
|
421
|
+
const maxTokens = opts.maxSummaryTokens ?? summarySoftTargetTokens(tokensBefore, opts.summaryBudget);
|
|
275
422
|
const summarized = await summarizeMiddle(text, [], opts, maxTokens);
|
|
276
423
|
if (!summarized.summary) {
|
|
277
424
|
const head = text.slice(0, Math.max(200, Math.floor(text.length * 0.15)));
|
|
@@ -285,6 +432,7 @@ export function createCompactEngine(options) {
|
|
|
285
432
|
tokensAfter: estimator.estimateText(view),
|
|
286
433
|
// 摘要失败时旧摘要仍有效:summary 字段保留之(与 messages 失败兜底同款)
|
|
287
434
|
summary: opts.previousSummary,
|
|
435
|
+
fresh: false,
|
|
288
436
|
view,
|
|
289
437
|
};
|
|
290
438
|
}
|
|
@@ -298,6 +446,7 @@ export function createCompactEngine(options) {
|
|
|
298
446
|
tokensBefore,
|
|
299
447
|
tokensAfter: estimator.estimateText(view),
|
|
300
448
|
summary,
|
|
449
|
+
fresh: true,
|
|
301
450
|
coverage: summarized.coverage,
|
|
302
451
|
view,
|
|
303
452
|
};
|
|
@@ -307,19 +456,19 @@ export function createCompactEngine(options) {
|
|
|
307
456
|
}
|
|
308
457
|
const head = messages.slice(0, protectHead);
|
|
309
458
|
const middle = messages.slice(protectHead, Math.max(protectHead, messages.length - protectTail));
|
|
310
|
-
|
|
459
|
+
// slice(-0) === slice(0) 返回全量:protectTail=0 时 tail 必须显式为空
|
|
460
|
+
const tail = protectTail > 0 ? messages.slice(-protectTail) : [];
|
|
311
461
|
const headTailTokens = estimator.estimateMessages(head) + estimator.estimateMessages(tail);
|
|
312
|
-
const maxSummaryTokens = opts.maxSummaryTokens ??
|
|
313
|
-
(targetTokens != null
|
|
314
|
-
? Math.max(200, Math.floor(targetTokens * 0.3))
|
|
315
|
-
: Math.max(200, Math.floor(tokensBefore * 0.2)));
|
|
462
|
+
const maxSummaryTokens = opts.maxSummaryTokens ?? summarySoftTargetTokens(tokensBefore, opts.summaryBudget);
|
|
316
463
|
const middleText = formatMessagesAsText(middle);
|
|
317
464
|
const summarized = await summarizeMiddle(middleText, middle, opts, maxSummaryTokens);
|
|
318
465
|
// 摘要即完整更新(previousSummary 已随 prompt 交给 summarizeFn 合并);
|
|
319
466
|
// 摘要失败时仍保留旧摘要兜底
|
|
320
467
|
let summary = opts.previousSummary ?? '';
|
|
468
|
+
let fresh = false;
|
|
321
469
|
if (summarized.summary) {
|
|
322
470
|
summary = summarized.summary;
|
|
471
|
+
fresh = true;
|
|
323
472
|
}
|
|
324
473
|
else if (!summary) {
|
|
325
474
|
const placeholder = `[Structural compact] dropped ${middle.length} middle messages`;
|
|
@@ -335,6 +484,7 @@ export function createCompactEngine(options) {
|
|
|
335
484
|
tokensBefore,
|
|
336
485
|
tokensAfter: estimator.estimateMessages(view),
|
|
337
486
|
summary: placeholder,
|
|
487
|
+
fresh: false,
|
|
338
488
|
view,
|
|
339
489
|
droppedSummary: `${middle.length} messages dropped; summarizer failed`,
|
|
340
490
|
};
|
|
@@ -346,10 +496,12 @@ export function createCompactEngine(options) {
|
|
|
346
496
|
return {
|
|
347
497
|
ok: true,
|
|
348
498
|
compacted: true,
|
|
349
|
-
|
|
499
|
+
// fresh=false(摘要失败仅旧摘要兜底)不得报 'structure_only'——调用方据此不推进覆盖
|
|
500
|
+
reason: fresh ? 'structure_only' : `summarize_failed:${summarized.error ?? 'no_output'}`,
|
|
350
501
|
tokensBefore,
|
|
351
502
|
tokensAfter,
|
|
352
503
|
summary,
|
|
504
|
+
fresh,
|
|
353
505
|
coverage: summarized.coverage ?? (middle.length > 0 ? 'partial' : 'full'),
|
|
354
506
|
view,
|
|
355
507
|
droppedSummary: `Structural compact: head=${head.length} middle=${middle.length} tail=${tail.length}`,
|