@thincoder/core 0.11.2 → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/advisor/compaction.mjs +7 -5
- package/advisor/history.mjs +24 -11
- package/advisor/loop.mjs +13 -8
- package/advisor/messages.mjs +72 -8
- package/advisor/run.mjs +24 -13
- package/advisor.mjs +7 -3
- package/agent/chat-call.mjs +14 -9
- package/agent/completion.mjs +28 -40
- package/agent/continue-decision.mjs +14 -8
- package/agent/digest-account.mjs +133 -59
- package/agent/dispatch-run.mjs +1 -1
- package/agent/dispatch.mjs +2 -1
- package/agent/family-tools.mjs +12 -13
- package/agent/helpers.mjs +17 -72
- package/agent/image-heal.mjs +18 -4
- package/agent/post-turn.mjs +13 -26
- package/agent/record-results.mjs +21 -6
- package/agent/run-stages.mjs +72 -37
- package/agent/run-start.mjs +148 -113
- package/agent/setup-reminders.mjs +187 -91
- package/agent/setup.mjs +204 -138
- package/agent/spawn-child.mjs +2 -2
- package/agent/suspension.mjs +43 -15
- package/agent/timers.mjs +4 -1
- package/agent/turn-domain-text.mjs +105 -0
- package/agent/turn-loop.mjs +54 -22
- package/agent/turn-projection.mjs +127 -227
- package/agent/turn-tool-process.mjs +32 -37
- package/agent-tools/advisor-async.mjs +6 -3
- package/agent-tools/advisor-launch.mjs +5 -5
- package/agent-tools/advisor.mjs +1 -1
- package/agent-tools/async-discard.mjs +7 -2
- package/agent-tools/async-settle.mjs +18 -12
- package/agent-tools/bash-async.mjs +5 -2
- package/agent-tools/batch-closeout.mjs +12 -62
- package/agent-tools/batch-ledger-bind.mjs +19 -8
- package/agent-tools/batch-lifecycle.mjs +37 -11
- package/agent-tools/batch-read.mjs +151 -4
- package/agent-tools/batch-record-write.mjs +5 -5
- package/agent-tools/batch-segment-vocab.mjs +84 -4
- package/agent-tools/batch-skeleton.mjs +18 -14
- package/agent-tools/batch-supersede.mjs +1 -1
- package/agent-tools/batch-tier-gate.mjs +36 -119
- package/agent-tools/batch.mjs +30 -20
- package/agent-tools/browser-async.mjs +5 -2
- package/agent-tools/consult.mjs +10 -7
- package/agent-tools/context.mjs +47 -31
- package/agent-tools/digest-budget.mjs +10 -9
- package/agent-tools/eng.mjs +3 -4
- package/agent-tools/escalate-async.mjs +3 -3
- package/agent-tools/goal.mjs +5 -2
- package/agent-tools/judge-domain.mjs +347 -0
- package/agent-tools/manifest.mjs +2 -2
- package/agent-tools/parent-channel.mjs +6 -3
- package/agent-tools/plan.mjs +11 -10
- package/agent-tools/review-facts.mjs +9 -3
- package/agent-tools/skill.mjs +7 -8
- package/agent-tools/spawn-gates.mjs +5 -16
- package/agent-tools/ssh-session.mjs +6 -3
- package/agent-tools/ssh-transfer.mjs +1 -1
- package/agent-tools/subagent-actions.mjs +2 -2
- package/agent-tools/subagent-async.mjs +11 -8
- package/agent-tools/subagent-scheduler.mjs +9 -9
- package/agent-tools/subagent-spawn.mjs +2 -2
- package/agent-tools/subagent.mjs +5 -18
- package/agent-tools/task.mjs +0 -8
- package/agent.mjs +15 -15
- package/auto-think.mjs +5 -2
- package/compaction-work-state.mjs +230 -0
- package/compress-form.mjs +41 -6
- package/config-defaults.mjs +5 -2
- package/config.mjs +53 -17
- package/context-degrade.mjs +79 -48
- package/context-echo.mjs +6 -26
- package/context-push.mjs +328 -31
- package/context.mjs +203 -141
- package/conventions.mjs +1 -1
- package/declaration.mjs +95 -17
- package/escape.mjs +6 -5
- package/explore-distill.mjs +35 -8
- package/generate-title.mjs +10 -1
- package/knowledge/prompt-resources.md +5 -1
- package/ledger-tools.mjs +50 -50
- package/ledger-write-ops.mjs +43 -16
- package/memory/docs.mjs +51 -15
- package/memory/file-list.mjs +6 -0
- package/model-specs.mjs +87 -21
- package/origin-guard.mjs +190 -0
- package/package.json +1 -1
- package/prompt-files.mjs +33 -11
- package/prompt-overlays.mjs +12 -5
- package/prompts/advisor-design.md +55 -36
- package/prompts/advisor-round1.md +18 -7
- package/prompts/advisor-round2.md +18 -7
- package/prompts/advisor-round3.md +18 -7
- package/prompts/common.md +89 -51
- package/prompts/consult-base.md +2 -3
- package/prompts/discipline-engineering.md +474 -440
- package/prompts/discipline-normal.md +107 -31
- package/prompts/knowledge/business-gates.md +23 -15
- package/prompts/knowledge/decision-quality.md +16 -18
- package/prompts/knowledge/doc-lookup.md +22 -27
- package/prompts/knowledge/document-writing.md +31 -49
- package/prompts/knowledge/documentation-evaluation.md +37 -45
- package/prompts/knowledge/evidence-discipline.md +36 -55
- package/prompts/knowledge/normal-coding-workflow.md +27 -21
- package/prompts/knowledge/normal-delivery-collaboration.md +33 -17
- package/prompts/knowledge/normal-work-management.md +10 -7
- package/prompts/knowledge/product-security.md +22 -17
- package/prompts/knowledge/project-records.md +63 -52
- package/prompts/knowledge/tool-apply-patch.md +12 -13
- package/prompts/knowledge/tool-bash.md +13 -4
- package/prompts/knowledge/tool-batch-eng-coder.md +13 -6
- package/prompts/knowledge/tool-batch-eng-designer.md +14 -6
- package/prompts/knowledge/tool-batch-review.md +12 -6
- package/prompts/knowledge/tool-batch.md +76 -62
- package/prompts/knowledge/tool-browser.md +45 -34
- package/prompts/knowledge/tool-context.md +2 -2
- package/prompts/knowledge/tool-delete.md +5 -1
- package/prompts/knowledge/tool-doc-check.md +25 -24
- package/prompts/knowledge/tool-doc-graph-read.md +3 -3
- package/prompts/knowledge/tool-doc-graph.md +15 -15
- package/prompts/knowledge/tool-edit.md +26 -23
- package/prompts/knowledge/tool-execute.md +9 -4
- package/prompts/knowledge/tool-fetch.md +7 -1
- package/prompts/knowledge/tool-file-ops.md +6 -1
- package/prompts/knowledge/tool-git-read.md +3 -1
- package/prompts/knowledge/tool-git.md +1 -1
- package/prompts/knowledge/tool-glob.md +3 -1
- package/prompts/knowledge/tool-grep.md +5 -2
- package/prompts/knowledge/tool-hashline-edit.md +4 -2
- package/prompts/knowledge/tool-insert-after.md +3 -1
- package/prompts/knowledge/tool-ledger-read.md +6 -13
- package/prompts/knowledge/tool-ledger.md +14 -10
- package/prompts/knowledge/tool-ls.md +2 -0
- package/prompts/knowledge/tool-manifest.md +10 -7
- package/prompts/knowledge/tool-memory.md +15 -11
- package/prompts/knowledge/tool-operations.md +59 -71
- package/prompts/knowledge/tool-plan.md +1 -2
- package/prompts/knowledge/tool-process.md +1 -1
- package/prompts/knowledge/tool-read-history.md +6 -7
- package/prompts/knowledge/tool-read.md +1 -0
- package/prompts/knowledge/tool-settings.md +6 -7
- package/prompts/knowledge/tool-ssh.md +37 -15
- package/prompts/knowledge/tool-subagent.md +37 -39
- package/prompts/knowledge/tool-task.md +3 -1
- package/prompts/knowledge/tool-team-ledger.md +5 -1
- package/prompts/knowledge/tool-tree.md +2 -0
- package/prompts/knowledge/tool-wait-for.md +16 -16
- package/prompts/knowledge/tool-write.md +4 -1
- package/prompts/knowledge/upstream-protocol.md +39 -37
- package/prompts/persona-coder.md +1 -3
- package/prompts/persona-eng-coder.md +5 -5
- package/prompts/persona-eng-designer.md +34 -17
- package/prompts/persona-engineering.md +532 -501
- package/prompts/persona-explore.md +0 -2
- package/prompts/persona-normal.md +17 -9
- package/prompts/persona-plan.md +0 -2
- package/prompts/persona-tester.md +0 -2
- package/prompts/subagent-base.md +0 -2
- package/provider/anthropic.mjs +4 -2
- package/provider/core.mjs +5 -3
- package/provider/errors.mjs +41 -7
- package/provider/google.mjs +5 -3
- package/provider/reasoning-echo.mjs +16 -0
- package/provider/responses.mjs +4 -2
- package/provider/sse.mjs +11 -6
- package/rules.mjs +11 -10
- package/session-lifecycle.mjs +115 -81
- package/session-slot-write.mjs +1 -1
- package/session.mjs +23 -20
- package/shell-identity.mjs +129 -22
- package/skip-dirs.mjs +24 -0
- package/team-ledger.mjs +22 -22
- package/text-budget.mjs +1 -1
- package/think-off.mjs +27 -0
- package/token-ttl.mjs +1 -1
- package/token-window.mjs +278 -88
- package/tool-docs/bash.md +0 -2
- package/tool-docs/consult_start.md +2 -2
- package/tool-docs/consult_stop.md +2 -2
- package/tools/browser.mjs +8 -8
- package/tools/execute.mjs +2 -2
- package/tools/file.mjs +17 -11
- package/tools/git.mjs +12 -12
- package/tools/ops.mjs +2 -2
- package/tools/patch.mjs +1 -1
- package/tools/process-doc-mark.mjs +33 -4
- package/tools/repomap.mjs +25 -3
- package/tools/search.mjs +74 -26
- package/tools/shared.mjs +4 -3
- package/tools/ssh.mjs +5 -5
- package/tools/tree.mjs +32 -10
- package/tools/web-deepseek.mjs +1 -1
- package/tools/web.mjs +2 -2
- package/tools/write-gate-params.mjs +3 -3
- package/window-policy.mjs +118 -78
package/context.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* context.mjs — Context management and compaction
|
|
3
3
|
* When no measured token count is available, use estimation as fallback (ASCII/4 + non-ASCII/1, no tokenizer dependency).
|
|
4
4
|
* When a measured value exists (response usage.prompt_tokens), trust it — estimation underestimates CJK by 3-4x and relying solely on it may never trigger compaction.
|
|
5
|
-
* Compaction strategy: summarize everything before the tail into one LLM
|
|
5
|
+
* Compaction strategy: summarize everything before the tail into one LLM summary, keep the latest N messages verbatim.
|
|
6
6
|
* NOTE: no dedicated head is kept (KEEP_HEAD = 0) — in multi-task sessions the earliest messages are
|
|
7
7
|
* typically a COMPLETED earlier task; preserving them verbatim anchored the model's attention on stale
|
|
8
8
|
* work after compaction. The earliest messages now go into the summary (which distinguishes completed
|
|
@@ -13,39 +13,67 @@
|
|
|
13
13
|
|
|
14
14
|
import { chat } from "./provider/index.mjs"
|
|
15
15
|
import { buildCompressMessages } from "./compress-form.mjs"
|
|
16
|
-
import { contextUsage, estimateTokens, keepTailSize, splitHistory,
|
|
17
|
-
|
|
16
|
+
import { contextUsage, estimateTokens, keepTailSize, splitHistory, COMPACTION_SUMMARY_TOKEN_ESTIMATE, rebaseMeasured, tailBudgetTokens, tokenRatioOf } from "./token-window.mjs"
|
|
17
|
+
// 写面单点(机器线按轮嵌套):压缩只做结构编辑,消息怎么进线归 `context-push.mjs`;三段回注住 A 段格位。
|
|
18
|
+
import { flattenHistory, flatIndexOf, positionOf, setInject } from "./context-push.mjs"
|
|
19
|
+
// 会话头块的两个单点(`CONTEXT-COMPACTION.md` §1.1「会话头块」):写入方 = `pushSessionHeadBlock`,
|
|
20
|
+
// 大纲正文 = `sessionOutlineOf`。压缩是本批的第二个刷新点——切走第一条真实用户消息所在轮之后重算一次,
|
|
21
|
+
// 下一次装配就贴到压缩边界后的新锚点上。
|
|
22
|
+
import { pushSessionHeadBlock, sessionOutlineOf } from "./agent/setup-reminders.mjs"
|
|
23
|
+
// 降级留痕(头块写入失败那一支)——核日志单一通道。
|
|
24
|
+
import { logEvent } from "./log.mjs"
|
|
25
|
+
// 压缩后回注的工作状态块(§6.1「工作状态的找回」):块怎么生成住 `compaction-work-state.mjs`;
|
|
26
|
+
// 本档只负责「注在哪」——三段回注的唯一落点是下面的 `reinjectAfterCompaction`。
|
|
27
|
+
import { workStateBlock } from "./compaction-work-state.mjs"
|
|
18
28
|
import { pruneStaleToolOutputs, shrinkOversized } from "./context-degrade.mjs"
|
|
19
29
|
// 固定开销越线判据的另一半(#2398):`limit` 单源 = `policyBudget`(有效窗口——与守卫面同一个数)。
|
|
20
|
-
import { policyBudget
|
|
21
|
-
// 覆盖条数(#2399
|
|
30
|
+
import { policyBudget } from "./config.mjs"
|
|
31
|
+
// 覆盖条数(#2399):按切点算——一层元素全在切点之前才算覆盖,一轮被切开不记(单源 = `turn-projection.mjs`)。
|
|
22
32
|
// 保留窗起点(#2431):`splitHistory` 的必填第四参——切点一处收紧,压缩与 prune 同源受益(§1.2)。
|
|
23
33
|
import { coveredTurnCount, retentionWindowStart } from "./agent/turn-projection.mjs"
|
|
34
|
+
// 压缩请求形的来源面(AGENT-LOOP.md §5.5.4 读(压缩 ∥ 蒸馏请求)行):当前 provider 的 spec 由调用点解出——
|
|
35
|
+
// `specForModel(agent.provider?.model)` 与本档其它 spec 读面同源,不另写族别表。
|
|
36
|
+
import { specForModel } from "./model-specs.mjs"
|
|
37
|
+
import { isThinkingRequest } from "./think-off.mjs"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 保留窗起点 → `splitHistory` 的第四参(拍平下标)。
|
|
42
|
+
* 起点按外层轮元素位置取(`{ turn, msg }`);取不到(轮元素不足窗宽)⇒ 传拍平条数 = 不收紧。
|
|
43
|
+
* 整数守卫在 `splitHistory` 里,本函数只做一次两向换算。
|
|
44
|
+
*/
|
|
45
|
+
function protectFromOf(agent, flat) {
|
|
46
|
+
const pos = retentionWindowStart(agent)
|
|
47
|
+
return pos ? flatIndexOf(agent.history, pos) : flat.length
|
|
48
|
+
}
|
|
24
49
|
|
|
25
50
|
export const SUMMARIZE_PROMPT = `The conversation above is our work log so far — summarize it into a compact summary for use as context in the ongoing conversation.
|
|
26
51
|
Requirements:
|
|
27
52
|
- Write in first person, present tense — these are "my" handover notes, continuing my own train of thought
|
|
28
53
|
- Most important: preserve design decisions and their reasons — architecture choices, API contracts, naming conventions, trade-off rationale. These are the anchors the subsequent code must not deviate from
|
|
54
|
+
- Preserve the user's explicit constraints as their own bullet, quoting the user's own words: forbidden scopes (what the user said not to do or not to touch), allowed scopes (what the user explicitly permitted), priority order (what the user said to do first), and deferred items (what the user said to postpone). Do not rewrite them as design decisions and do not fold them into unresolved issues
|
|
29
55
|
- Distinguish COMPLETED vs IN-PROGRESS work: completed tasks get a ONE-LINE recap each (what was done, key outcome); spend the detail budget on unresolved issues, next steps, and the CURRENT task
|
|
30
56
|
- The user's most recent request defines the current task — anchor on it. Earlier requests are likely already completed and only need the one-line recap; do NOT preserve them at full fidelity
|
|
57
|
+
- My previous handover note is attached above as a message of its own. When it is attached, fold its facts into this new note and produce ONE merged summary covering everything compacted so far: no fact from it may be dropped, and the old note is not repeated beside the new one. The note is not one of those earlier requests — what is still live in it must survive, and "completed ⇒ one-line recap" applies only to work that is actually finished
|
|
31
58
|
- Explicitly list FILES CHANGED: every modified file path plus a one-line "why" — so post-compaction work can re-locate what was edited and where
|
|
32
59
|
- Explicitly list UNRESOLVED ISSUES / TODOs: anything still open plus the next steps — so post-compaction recovery knows where to resume
|
|
33
60
|
- Drop: pleasantries, repetition, fine-grained tool output details
|
|
34
61
|
- Honestly mark uncertain items: anything not actually verified must say "unverified"; do not present guesses as facts
|
|
35
|
-
- Use bullet-point output. Stay under ~1K tokens (≈1000 Chinese chars / 4000 ASCII chars) — a hard target. An oversized summary wastes window and dilutes the tail; the old unbounded-length guidance is deprecated. When over budget, trim in this order: completed recaps to one line; FILES CHANGED why-notes to bare paths; in-progress prose tightened. NEVER cut design anchors
|
|
62
|
+
- Use bullet-point output. Stay under ~1K tokens (≈1000 Chinese chars / 4000 ASCII chars) — a hard target. An oversized summary wastes window and dilutes the tail; the old unbounded-length guidance is deprecated. When over budget, trim in this order: completed recaps to one line; FILES CHANGED why-notes to bare paths; in-progress prose tightened. NEVER cut design anchors, UNRESOLVED ISSUES/TODOs, or user constraints — recovery depends on them.
|
|
36
63
|
`
|
|
37
64
|
|
|
38
|
-
//
|
|
39
|
-
//
|
|
65
|
+
// 压缩摘要的估算(可达性门的 `compactionSummary` 项 ∥ §4 减法链的末项)住 `token-window.mjs` 的
|
|
66
|
+
// `COMPACTION_SUMMARY_TOKEN_ESTIMATE`——尾预算也要用它,而本档 import 那一档(反向就会成环)。
|
|
67
|
+
// 压缩摘要的文本就是摘要正文本身(§6.1)——本档不为它拼任何固定文本;回声明占位已退场,本值不再为它留预算。
|
|
40
68
|
// 残余方向:真实摘要超 1K 时本值低估 `post`(门可能放行一次压不到线下的压缩),不会反向误拦——守卫面仍抛三实数。
|
|
41
|
-
//
|
|
42
|
-
//
|
|
69
|
+
// 压完之后任务表回注、plan 提醒与工作状态块住 `_inject` 的三个格,会话头块住 `agent._sessionHead`——
|
|
70
|
+
// 它们不靠本值计,而在 `fixed` 里(§2.5 六项之一)。
|
|
43
71
|
|
|
44
72
|
/** Task re-injection reminder prefix (after compaction, clear old versions from history first for a single source of truth) */
|
|
45
73
|
const TASK_REINJECT_PREFIX = "[System reminder: your current task list after compaction:"
|
|
46
74
|
|
|
47
|
-
/** Truncation fallback
|
|
48
|
-
const
|
|
75
|
+
/** Truncation fallback summary (deterministic discard, no LLM call — §5.1 第 ⑥ 步) */
|
|
76
|
+
const FALLBACK_COMPACTION_SUMMARY =
|
|
49
77
|
"[Context was truncated because summarization failed. " +
|
|
50
78
|
"The middle portion of earlier work was dropped WITHOUT a summary. " +
|
|
51
79
|
"Re-verify any state you need with tools before relying on it.]\n\n"
|
|
@@ -72,124 +100,126 @@ function anchorText(agent) {
|
|
|
72
100
|
return lines.length > 0 ? lines.join("\n") : null
|
|
73
101
|
}
|
|
74
102
|
|
|
75
|
-
/**
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
// Compaction REBUILDS the machine line (head + note + placeholder + tail), so the pre-compaction
|
|
110
|
-
// _runStartHistoryLen index is stale — a longer array shrank beneath it, and end-of-run exploration
|
|
111
|
-
// distillation would then silently skip or slice from the wrong offset. Reset the boundary to the
|
|
112
|
-
// first verbatim tail message: head.length + 1 in the merge branch (the placeholder rides inside
|
|
113
|
-
// the rewritten tail[0], which keeps its index), head.length + 2 otherwise (the note and the
|
|
114
|
-
// separate "Understood" placeholder sit between head and tail). Exploration before the tail was
|
|
115
|
-
// already covered by the compaction summary, so only the still-raw tail needs distilling. `head`
|
|
116
|
-
// is empty today (KEEP_HEAD = 0) — the formula stays correct if KEEP_HEAD ever grows.
|
|
117
|
-
// (shrinkOversized only truncates message bodies in place and leaves the array length unchanged,
|
|
118
|
-
// so this boundary stays valid there — no reset needed.)
|
|
119
|
-
if (tail[0]?.role === "assistant") {
|
|
120
|
-
const merged = { ...tail[0], content: withPlaceholderPrefix(tail[0].content) }
|
|
121
|
-
agent.history = [
|
|
122
|
-
...head,
|
|
123
|
-
{ role: "user", content: note, ts: now },
|
|
124
|
-
merged,
|
|
125
|
-
...tail.slice(1),
|
|
126
|
-
]
|
|
127
|
-
agent._runStartHistoryLen = head.length + 1
|
|
128
|
-
} else {
|
|
129
|
-
agent.history = [
|
|
130
|
-
...head,
|
|
131
|
-
{ role: "user", content: note, ts: now },
|
|
132
|
-
{ role: "assistant", content: COMPACTION_PLACEHOLDER, ts: now },
|
|
133
|
-
...tail,
|
|
134
|
-
]
|
|
135
|
-
agent._runStartHistoryLen = head.length + 2
|
|
103
|
+
/**
|
|
104
|
+
* 压缩后三段回注的**唯一落点**(CONTEXT-COMPACTION.md §6.1「注在哪里」):顺序写死为
|
|
105
|
+
* 「任务表 → plan 提醒 → 工作状态块」,各写 A 段自己那一格。
|
|
106
|
+
* 三个格位写即覆盖旧值——**不再扫线摘旧版本**:任务表 / plan 提示 / 工作状态块都不是线上消息(§1.1 注入三段)。
|
|
107
|
+
* `null` 或空串 ⇒ 该格清空(没有值的状态与「这一格从来没过」在装配面上同形)。
|
|
108
|
+
* 它不读盘:`workState` 是调用方给的那个值(`applyCompression` 的同名参数),与它同源。
|
|
109
|
+
* @param {object} agent
|
|
110
|
+
* @param {string|null} workState — 已生成的工作状态块;`null` = 台账面读失败 ⇒ 整块不出现
|
|
111
|
+
*/
|
|
112
|
+
function reinjectAfterCompaction(agent, workState) {
|
|
113
|
+
setInject(agent, "tasks", agent.tasks.length > 0
|
|
114
|
+
? `${TASK_REINJECT_PREFIX}\n${agent.tasks.map((t) => `- [${t.status}] ${t.title}`).join("\n")}\nContinue from where you left off.]`
|
|
115
|
+
: null)
|
|
116
|
+
setInject(agent, "plan", agent.planMode
|
|
117
|
+
? "[System reminder: plan mode is active. Explore the codebase read-only, design your solution, then call plan with action='exit' to present it for user approval.]"
|
|
118
|
+
: null)
|
|
119
|
+
setInject(agent, "work-state", workState)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 按结构切一刀(§1.1「压缩的切点」):`from` 之前的轮元素整条移出外层,`to` 之前的消息进摘要,
|
|
124
|
+
* `(to.turn, to.msg)` 起的原文原样留下。`from.turn === to.turn` 时同一轮里切两刀(头段与尾段各留一段)。
|
|
125
|
+
* 切完为空的轮元素整条丢掉——一轮的消息全离开机读线时,它的轮元素就移出外层。
|
|
126
|
+
*/
|
|
127
|
+
function cutTurns(history, from, to) {
|
|
128
|
+
const out = []
|
|
129
|
+
for (let t = 0; t < history.length; t++) {
|
|
130
|
+
const messages = Array.isArray(history[t]?.messages) ? history[t].messages : []
|
|
131
|
+
let kept
|
|
132
|
+
if (t < from.turn || t > to.turn) kept = messages
|
|
133
|
+
else if (t === to.turn) kept = [...(t === from.turn ? messages.slice(0, from.msg) : []), ...messages.slice(to.msg)]
|
|
134
|
+
else if (t === from.turn) kept = messages.slice(0, from.msg)
|
|
135
|
+
else kept = []
|
|
136
|
+
if (kept.length > 0) out.push({ messages: kept })
|
|
136
137
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
// 放在函数尾——上面的摘旧行与回注都会挪下标,身份扫描必须在数组定形之后。
|
|
140
|
-
const estAfter = estimateTokens(
|
|
141
|
-
tail[0]?.role === "assistant"
|
|
142
|
-
? [{ role: "user", content: note }]
|
|
143
|
-
: [{ role: "user", content: note }, { role: "assistant", content: COMPACTION_PLACEHOLDER }],
|
|
144
|
-
)
|
|
138
|
+
return out
|
|
139
|
+
}
|
|
145
140
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
)
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
agent.history.push({
|
|
155
|
-
role: "user",
|
|
156
|
-
content: `${TASK_REINJECT_PREFIX}\n${taskSummary}\nContinue from where you left off.]`,
|
|
157
|
-
})
|
|
141
|
+
/**
|
|
142
|
+
* 摘要支与丢弃支共用的 `workState` 契约(§6.1「契约」):必填、无默认。
|
|
143
|
+
* 默认值等于替调用方决定「这一格要不要指针」——与「压缩面一处拼装」相反;缺传当场抛并点名该参数。
|
|
144
|
+
*/
|
|
145
|
+
function assertWorkState(fnName, workState) {
|
|
146
|
+
if (workState !== null && typeof workState !== "string") {
|
|
147
|
+
const got = workState === undefined ? "undefined(缺传)" : Array.isArray(workState) ? "array" : typeof workState
|
|
148
|
+
throw new Error(`${fnName}:workState 必填(string | null,无默认)——压缩后回注的工作状态块由调用方给,实收 ${got}`)
|
|
158
149
|
}
|
|
150
|
+
}
|
|
159
151
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
152
|
+
/**
|
|
153
|
+
* 两个压缩出口共用的 `outline` 契约(§1.1「会话头块」):必填、无默认,本趟没有大纲就传空串。
|
|
154
|
+
* 它在这里先拦一次,让人读到的错点名 `applyCompression` ∥ `compressFallback` 与 `outline` 本身,
|
|
155
|
+
* 而不是下一层写入方 `pushSessionHeadBlock` 报的同一件事。
|
|
156
|
+
*/
|
|
157
|
+
function assertOutline(fnName, outline) {
|
|
158
|
+
if (typeof outline !== "string") {
|
|
159
|
+
const got = outline === undefined ? "undefined(缺传)" : Array.isArray(outline) ? "array" : typeof outline
|
|
160
|
+
throw new Error(`${fnName}:outline 必填(string,无默认)——本趟的大纲正文由调用方给,没有就传空串;实收 ${got}`)
|
|
166
161
|
}
|
|
162
|
+
}
|
|
167
163
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
164
|
+
/** Replace middle with the compaction summary, then re-inject task/plan/work-state pointers (shared by LLM summary and truncation fallback).
|
|
165
|
+
* `outline` = 本次压缩后重建的依赖大纲正文(必填、无默认:没有就传空串——`pushSessionHeadBlock` 据此省掉大纲那两段)。
|
|
166
|
+
* 它由调用方构好传进来,因为本函数是同步的,而大纲要读库与源文件。 */
|
|
167
|
+
export function applyCompression(agent, headEnd, tailStart, compactionSummary, workState, outline) {
|
|
168
|
+
assertWorkState("applyCompression", workState)
|
|
169
|
+
assertOutline("applyCompression", outline)
|
|
170
|
+
// 切点 = `{ turn, msg }`(§1.1):两个整数下标在函数体开头换算一次,此后只碰结构。
|
|
171
|
+
const from = positionOf(agent.history, headEnd)
|
|
172
|
+
const to = positionOf(agent.history, tailStart)
|
|
173
|
+
// 覆盖条数(#2399):按切点算——该轮元素全在切点之前才算覆盖(一轮被切开不记)。
|
|
174
|
+
const turnsCovered = coveredTurnCount(agent, to)
|
|
175
|
+
// 结构编辑后的实测基线(§3.1「形态」):压缩是**整段删除**——被摘要覆盖的轮元素整条移出外层,
|
|
176
|
+
// 压缩摘要写 `_compactCheckpoint`、由装配拼进 `_inject` 而不落线,所以线上不存在「中段换成压缩摘要」
|
|
177
|
+
// 的替换:被改的那一段就是整段中段,`estAfter` 取 0。位置落在被移出那一段时 `_usageAt` 落到线头。
|
|
178
|
+
const before = agent.history
|
|
179
|
+
const beforeFlat = flattenHistory(before)
|
|
180
|
+
const measuredEnd = agent._usageAt ? flatIndexOf(before, agent._usageAt) : beforeFlat.length
|
|
181
|
+
const estBefore = estimateTokens(beforeFlat.slice(headEnd, tailStart))
|
|
182
|
+
const estAfter = 0
|
|
183
|
+
// _fullHistory already holds every real message (written at the source via pushReal),
|
|
184
|
+
// so compaction only shrinks the machine line — nothing to preserve here.
|
|
185
|
+
// head is normally empty (KEEP_HEAD = 0): with no dedicated head the summary covers every
|
|
186
|
+
// earlier turn, and the post-compaction context anchors on the current task, not on
|
|
187
|
+
// possibly-completed earlier requests.
|
|
188
|
+
//
|
|
189
|
+
// 压缩摘要不落机读线(§1「压缩摘要的位置」):它住 `_inject` 的 `compaction-summary` 格,装配时排在对话之前。
|
|
190
|
+
// 合成占位(`COMPACTION_PLACEHOLDER`)随之退场——没有相邻 assistant 要它隔开了;压缩后的首个
|
|
191
|
+
// 非 system 消息因此是累积段或压缩摘要本身,不会是 assistant(原 tail[0] 的角色)。
|
|
192
|
+
agent.history = cutTurns(before, from, to)
|
|
193
|
+
setInject(agent, "compaction-summary", compactionSummary)
|
|
194
|
+
// 三段回注(任务表 → plan 提醒 → 工作状态块):顺序与落点在 `reinjectAfterCompaction` 一处。
|
|
195
|
+
reinjectAfterCompaction(agent, workState)
|
|
196
|
+
// 会话头块(§1.1「会话头块」):切完元素、`compaction-summary` 格也已写好——第一条真实用户消息所在轮
|
|
197
|
+
// 刚被切走,重算重存一次,下一次装配就贴到压缩边界后的新锚点上(不叠加第二处:整段替换)。
|
|
198
|
+
// 它是可选注入的写入,不是压缩本体:它抛了只记一行日志——不让一次头块写入失败把一次已成功的压缩
|
|
199
|
+
// 报成摘要失败(那条路会再走一遍 `compressFallback`,把好摘要换成降级摘要)。
|
|
200
|
+
try {
|
|
201
|
+
pushSessionHeadBlock(agent, { outline })
|
|
202
|
+
} catch (err) {
|
|
203
|
+
logEvent("session-head:write-skip", { reason: err?.message ?? String(err) })
|
|
174
204
|
}
|
|
175
205
|
// 压缩成果落内存载体(#2399):槽保存取它、恢复播种取它(SESSION.md §2 ∥ CONTEXT-COMPACTION.md §6)。
|
|
176
|
-
agent._compactCheckpoint = {
|
|
177
|
-
// §3.1
|
|
178
|
-
//
|
|
206
|
+
agent._compactCheckpoint = { compactionSummary, turnsCovered }
|
|
207
|
+
// §3.1 基线重定(结构已定形):中段被摘要取走,`measuredEnd` 之后的消息从没被量过,故只按身份找
|
|
208
|
+
// 「旧前缀最后一个还在线上的消息」,其后第一个位置就是新的 `_usageAt`。
|
|
179
209
|
rebaseMeasured(agent, estBefore, estAfter, { before, measuredEnd })
|
|
180
210
|
}
|
|
181
211
|
|
|
182
212
|
/**
|
|
183
213
|
* 可达性门(CONTEXT-COMPACTION.md §6.17「压缩触发判据(可达性门)」):压完之后 `total` 能不能落到阈值之下。
|
|
184
|
-
* `post` 按
|
|
185
|
-
* 那段(与本次压缩同一次 `splitHistory` 产出)。压缩后 `_lastPromptTokens` 失效 ⇒ 只有估算支可比,故走 estimated
|
|
186
|
-
* `_tokRatio`(与 `contextUsage` 的估算支同尺)。
|
|
187
|
-
*
|
|
188
|
-
*
|
|
214
|
+
* `post` 按 §2.5 的同一个测度估:对话面只留 tail、非对话面是 `fixed − compactionSummary` 加压缩摘要预留额。`middle` = 本次会摘掉的
|
|
215
|
+
* 那段(与本次压缩同一次 `splitHistory` 产出)。压缩后 `_lastPromptTokens` 失效 ⇒ 只有估算支可比,故走 estimated 支
|
|
216
|
+
* 并乘同一 `_tokRatio`(与 `contextUsage` 的估算支同尺)。
|
|
217
|
+
* 为什么要有它:非对话面是固定开销、压不掉,把它算进判据左侧会让「固定开销本身逼近阈值」的会话反复触发压缩却
|
|
218
|
+
* 压不出任何东西——每触发一次白付一次摘要请求(台账 `#1833`)。
|
|
189
219
|
*/
|
|
190
220
|
function postCompactionTotal(agent, usage, middle) {
|
|
191
|
-
const ratio = agent
|
|
192
|
-
return Math.round((usage.history - estimateTokens(middle) +
|
|
221
|
+
const ratio = tokenRatioOf(agent)
|
|
222
|
+
return Math.round((usage.history - estimateTokens(middle) + COMPACTION_SUMMARY_TOKEN_ESTIMATE + (usage.fixed - usage.compactionSummary)) * ratio)
|
|
193
223
|
}
|
|
194
224
|
|
|
195
225
|
/**
|
|
@@ -207,8 +237,8 @@ function postCompactionTotal(agent, usage, middle) {
|
|
|
207
237
|
* ```
|
|
208
238
|
*
|
|
209
239
|
* `force` 面也 prune,但不因 prune 就早退,也不因 ④ 就停:`/compact` 与越窗自愈要的是一次真实的压缩动作,
|
|
210
|
-
* prune 只让中段变小、摘要请求更省。第 ③ 步的射程:合格集非空的只有 §7.2
|
|
211
|
-
* `
|
|
240
|
+
* prune 只让中段变小、摘要请求更省。第 ③ 步的射程:合格集非空的只有 §7.2 列的那三类状态(已登记轮不足窗宽∥
|
|
241
|
+
* 本批之前的旧槽——消息上没有 `turn` ∥ 窗内那几轮在线上一条不剩);其余状态下 `tool` 消息全在保留窗内、因而全在保护尾里,prune 返回
|
|
212
242
|
* 0 条——③ 是一步 no-op,常见路径的成本落在 ⑤。
|
|
213
243
|
*
|
|
214
244
|
* 返回是否发生了压缩(摘要成功 ∥ 弃真的发生)。摘要失败一次就走到丢弃,不等连续失败——「一次网络抖动换一个
|
|
@@ -223,9 +253,10 @@ function postCompactionTotal(agent, usage, middle) {
|
|
|
223
253
|
* 可达性门的 `post > threshold`),其余全同(同切分 / 同尾部预算 / 同摘要链 / 同回注 / 同基线重定);
|
|
224
254
|
* `focus` 追加在摘要指令尾段。
|
|
225
255
|
*/
|
|
226
|
-
export async function compressIfNeeded(agent, threshold, callbacks, extras
|
|
227
|
-
//
|
|
228
|
-
|
|
256
|
+
export async function compressIfNeeded(agent, threshold, callbacks, extras, signal) {
|
|
257
|
+
// `extras` 必填、无缺省(§2.3 的同一纪律):本函数的每一次读数与每一条门都按 `fixed` 算,
|
|
258
|
+
// 缺这一段即 system ∥ tools 两段记 0——读数偏低而看起来正常。缺参在 `contextUsage` 那里抛出并点名。
|
|
259
|
+
// 窗口 = 有效窗口(恒等于模型窗口,§2.1)——守卫、尾预算、固定开销判据都从它派生。
|
|
229
260
|
const ratio = tokenRatioOf(agent)
|
|
230
261
|
// 单源(§6.16.4):total 与 stats 面同一函数(既有内联式改调 contextUsage,判定语义零改)。
|
|
231
262
|
// ① 阈值早退(force 跳过)
|
|
@@ -233,29 +264,37 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
|
|
|
233
264
|
if (!extras.force && usage.total <= threshold) return false
|
|
234
265
|
// ② 固定开销单独越线(#2398 · §5):history 归零后 `total` 仍等于固定开销 ⇒ 压缩无解。强压面也不放行
|
|
235
266
|
// (压一次白付一次摘要请求,压完仍抛同一个错);判据窗口 = 有效窗口(§2.2)。
|
|
236
|
-
if (usage.fixedFloor > policyBudget(agent.provider
|
|
267
|
+
if (usage.fixedFloor > policyBudget(agent.provider).limit) return false
|
|
237
268
|
// ③ prune 一次 → 基线按 §3.1 重定(在 prune 内部)→ 重测
|
|
238
269
|
if (pruneStaleToolOutputs(agent).pruned > 0) usage = contextUsage(agent, extras)
|
|
239
270
|
// ④ 未 force 且重测后已够 ⇒ 停:prune 换来的线下,不必再付一次摘要请求
|
|
240
271
|
if (!extras.force && usage.total <= threshold) return false
|
|
241
272
|
const tokens = usage.total
|
|
242
273
|
|
|
243
|
-
|
|
244
|
-
const
|
|
274
|
+
// 切点在拍平视图上算(配对修复与 `suffixTokens` 都在拍平序),保护尾由位置换算一次(§1.2)。
|
|
275
|
+
const flat = flattenHistory(agent.history)
|
|
276
|
+
const keepTail = keepTailSize(agent.provider, flat.length)
|
|
277
|
+
const split = splitHistory(flat, keepTail, tailBudgetTokens(agent.provider, usage.fixed - usage.compactionSummary, ratio), protectFromOf(agent, flat))
|
|
245
278
|
if (!split) {
|
|
246
279
|
// History is too short (≤KEEP_HEAD+keepTail+1 messages) to find a middle section, but tokens exceed threshold — typically a single giant message
|
|
247
280
|
// (large paste / huge injection). When summarization has no room, degrade to deterministic shrinking to ensure context always reduces
|
|
248
281
|
return shrinkOversized(agent)
|
|
249
282
|
}
|
|
250
283
|
|
|
251
|
-
const middle =
|
|
284
|
+
const middle = flat.slice(split.headEnd, split.tailStart)
|
|
252
285
|
// 可达性门(§6.17):压完落不到线下 ⇒ 不压——不为一次没有净减的摘要白付请求。`force` 全文豁免(模型主动压缩 ∥
|
|
253
286
|
// 守卫强压:模型判定优先于阈值,压后仍超由守卫面抛三实数)。到不了线下的格仍由守卫 `enforceContextFit` 兜住。
|
|
254
287
|
// 判据的输入是 prune 之后的 `usage` 与 prune 之后的 `middle`(同一次 `splitHistory` 产出),判据本身零改。
|
|
255
288
|
if (!extras.force && postCompactionTotal(agent, usage, middle) > threshold) return false
|
|
256
289
|
|
|
290
|
+
// 工作状态块(§6.1「消费者表」):计算点绑在可达性门之后、摘要请求之前——没压缩的回合零 I/O,
|
|
291
|
+
// 一次压缩只读一次盘、开一次库。第 ⑥ 步转 `compressFallback` 复用这个值,不重读;它不抛(降级给 `null`)。
|
|
292
|
+
const workState = await workStateBlock({ cwd: agent.cwd, boundary: agent.cwd })
|
|
293
|
+
// 会话头块的依赖大纲同在这一刻重建(与 workState 同一处 I/O 面:压缩之后才付这份成本)。
|
|
294
|
+
const outline = await sessionOutlineOf(agent)
|
|
295
|
+
|
|
257
296
|
// Compression request form v2/v3 (§6.14 / D-CC20): continuation — same system + same tools declaration (the turn's own
|
|
258
|
-
// array) + the middle's verbatim messages + one tail instruction. 首现即复用回合所建前缀 ⟺ 带 tools 声明(无 tool_choice)
|
|
297
|
+
// array) + the previous summary right after system (§6.2) + the middle's verbatim messages + one tail instruction. 首现即复用回合所建前缀 ⟺ 带 tools 声明(无 tool_choice)
|
|
259
298
|
// 且 `reasoning_effort` 与回合侧同值——v2 探针复测:8 格 84–98%(读数详表见批次档 §5);不带 tools / 带 tool_choice:"none" / effort 异值 ⇒ 首现 0%(自建项复跑例外);无 extras.tools ⇒ 不发 tools。
|
|
260
299
|
// ⚠️ **不带 `tool_choice`**(设计 §6.14 备选② · 预注册判定规则「S3 <0.9 且 S4 ≥0.9 ⇒ 采纳 v2 减 tool_choice」启用——实测该参数使服务端丢弃 tools 区 ⇒ 首现命中 0%)。
|
|
261
300
|
// ⚠️ v3(父侧 2026-09-18 裁定):**随带与回合请求同源的 `reasoning_effort`**——下行不再覆盖 `agent.provider.reasoningEffort`(回合调用 `chat(agent.provider, …)` 同字段;
|
|
@@ -267,9 +306,24 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
|
|
|
267
306
|
// the lifecycle is surfaced, never the summary body. N = the number of history messages being summarized.
|
|
268
307
|
callbacks?.onCompressStart?.({ messages: middle.length })
|
|
269
308
|
const startedAt = performance.now()
|
|
270
|
-
// F-CC2 焦点块(§6.16.2
|
|
271
|
-
//
|
|
272
|
-
|
|
309
|
+
// F-CC2 焦点块(§6.16.2):仅模型主动面携带——追加在**指令末条尾段**(焦点块不改写 `SUMMARIZE_PROMPT` 本身,
|
|
310
|
+
// 只追加在指令末条;无 focus ⇒ 末条就是 `SUMMARIZE_PROMPT` 原文)。
|
|
311
|
+
// 累积摘要(§6.2):上一次摘要紧随 `system`、在被摘要的中段之前;首次压缩(尚无检查点)传 null,不插这一条。
|
|
312
|
+
// 检查点里可能是降级文本(`FALLBACK_COMPACTION_SUMMARY`)——照给、不分支(§6.2 D-3):那句说的是「那段没有摘要」,
|
|
313
|
+
// 是这段历史的真话;丢掉就既无原文也无交代。
|
|
314
|
+
// 来源面(AGENT-LOOP.md §5.5.4 读(压缩 ∥ 蒸馏请求)行):当前 provider 名与当下 spec 由本调用点显式传入,构造器不补默认。
|
|
315
|
+
const spec = specForModel(agent.provider?.model)
|
|
316
|
+
const messages = buildCompressMessages(
|
|
317
|
+
flat,
|
|
318
|
+
split.tailStart,
|
|
319
|
+
extras?.systemPrompt,
|
|
320
|
+
SUMMARIZE_PROMPT,
|
|
321
|
+
agent._compactCheckpoint?.compactionSummary ?? null,
|
|
322
|
+
agent.provider?.name,
|
|
323
|
+
spec,
|
|
324
|
+
isThinkingRequest({ ...agent.provider, thinking: null }, spec),
|
|
325
|
+
Array.isArray(extras?.tools) && extras.tools.length > 0,
|
|
326
|
+
)
|
|
273
327
|
if (extras.focus) {
|
|
274
328
|
const last = messages.at(-1)
|
|
275
329
|
messages[messages.length - 1] = { ...last, content: last.content + focusBlock(String(extras.focus), anchorText(agent)) }
|
|
@@ -292,9 +346,9 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
|
|
|
292
346
|
},
|
|
293
347
|
})
|
|
294
348
|
// Blank-summary guard (§6.14 退化面 3): a blank summary would land in applyCompression as
|
|
295
|
-
// "middle dropped + empty
|
|
349
|
+
// "middle dropped + empty compaction summary" and still count as success — treat it as this call failing.
|
|
296
350
|
if (!summary.content?.trim()) throw new Error("compaction summary is empty")
|
|
297
|
-
applyCompression(agent, split.headEnd, split.tailStart,
|
|
351
|
+
applyCompression(agent, split.headEnd, split.tailStart, summary.content, workState, outline)
|
|
298
352
|
// Completion info for the compression panel (D-C2): tokens freed = the pre-compression prompt
|
|
299
353
|
// estimate (`tokens` — the value that tripped the threshold, incl. system/tools overhead on the
|
|
300
354
|
// pure-estimation path) minus the post-compression estimate on the SAME basis (`contextUsage`
|
|
@@ -315,7 +369,7 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
|
|
|
315
369
|
// ⑥ 摘要失败,或压后仍在线上一档之上 ⇒ 丢弃(零网络、确定性),再重测。
|
|
316
370
|
const after = contextUsage(agent, extras)
|
|
317
371
|
if (!summarized || after.total > threshold) {
|
|
318
|
-
if (compressFallback(agent)) return true
|
|
372
|
+
if (compressFallback(agent, workState, outline)) return true
|
|
319
373
|
// 没有中段可丢:无摘要产物,把摘要那个错交回调用点(既有失败链记一行回执)。
|
|
320
374
|
if (summaryError) throw summaryError
|
|
321
375
|
}
|
|
@@ -328,19 +382,23 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
|
|
|
328
382
|
* 丢弃要报量(§5.1):`discardedMessages` = 被丢弃的消息条数;`discardedTurns` = 其中全部记录消息都落在
|
|
329
383
|
* 该区间的轮次数(与 §6 的覆盖账同一本);`tailMessages` = 留下的尾部条数——只报留下的条数,读的人推不出丢了什么。
|
|
330
384
|
*/
|
|
331
|
-
export function compressFallback(agent) {
|
|
332
|
-
|
|
385
|
+
export function compressFallback(agent, workState, outline) {
|
|
386
|
+
assertWorkState("compressFallback", workState)
|
|
387
|
+
assertOutline("compressFallback", outline)
|
|
333
388
|
const ratio = tokenRatioOf(agent)
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
389
|
+
// 非对话面底数 = `fixed − compactionSummary`(§2.3 表 ∥ §4):压缩摘要格那一份先减掉、尾预算再按预留额加回来。
|
|
390
|
+
// 本函数没有 extras 形参(调用点只有同档的 `compressIfNeeded`),非对话面就取本回合暂存那一份。
|
|
391
|
+
const usage = contextUsage(agent, agent?._ctxBasis?.overhead ?? {})
|
|
392
|
+
const flat = flattenHistory(agent.history)
|
|
393
|
+
const keepTail = keepTailSize(agent.provider, flat.length)
|
|
394
|
+
const split = splitHistory(flat, keepTail, tailBudgetTokens(agent.provider, usage.fixed - usage.compactionSummary, ratio), protectFromOf(agent, flat))
|
|
337
395
|
if (!split) return false
|
|
338
|
-
const tailMessages =
|
|
396
|
+
const tailMessages = flat.length - split.tailStart
|
|
339
397
|
const discardedMessages = split.tailStart - split.headEnd
|
|
340
|
-
const discardedTurns = coveredTurnCount(agent, split.tailStart)
|
|
341
|
-
applyCompression(agent, split.headEnd, split.tailStart,
|
|
398
|
+
const discardedTurns = coveredTurnCount(agent, positionOf(agent.history, split.tailStart))
|
|
399
|
+
applyCompression(agent, split.headEnd, split.tailStart, FALLBACK_COMPACTION_SUMMARY, workState, outline)
|
|
342
400
|
// Fallback completion info (D-C2): mode marks the deterministic-discard path — the panel shows the
|
|
343
|
-
// degradation
|
|
401
|
+
// degradation summary on the same callback, distinguished by `mode === "fallback"` alone.
|
|
344
402
|
agent._lastCompressInfo = { mode: "fallback", discardedMessages, discardedTurns, tailMessages }
|
|
345
403
|
return true
|
|
346
404
|
}
|
|
@@ -348,7 +406,11 @@ export function compressFallback(agent) {
|
|
|
348
406
|
// ─── 迁出面(import 面保持:TUI / verify-compress / VSC 对拍经本档取——先例 = 下方 explore-distill 再导出)──
|
|
349
407
|
export { estimateTokens }
|
|
350
408
|
// ─── 拆分转口(2026-10-01 拆分批 · #755 ∥ #786):写缝 ∥ 回声 ∥ 降级三面外提——消费面 / 单元测试档 import 面零改 ───
|
|
351
|
-
|
|
409
|
+
// 机读线按轮嵌套(2026-11-17):写面与装配面的全部入口经本档转出,调用方不必另记一道路径。
|
|
410
|
+
export {
|
|
411
|
+
beginTurn, pushReal, pushInject, setInject, setSessionHead, retain, pushRecord,
|
|
412
|
+
flattenHistory, assembleRequestMessages, flatIndexOf, positionOf, INJECT_SLOTS,
|
|
413
|
+
} from "./context-push.mjs"
|
|
352
414
|
export { isAssistantEchoPair, mergeAdjacentAssistantEchoes } from "./context-echo.mjs"
|
|
353
415
|
export { pruneStaleToolOutputs } from "./context-degrade.mjs"
|
|
354
416
|
// ─── End-of-run exploration distillation(2026-09-05 module-split:524 > 500 硬限——verbatim
|
package/conventions.mjs
CHANGED
|
@@ -191,4 +191,4 @@ export function isStatePath(p, conv) {
|
|
|
191
191
|
// 迁出面(2026-10-01 拆分批 · #755 ∥ #786):声明装载面外提 `declaration.mjs`——本档经
|
|
192
192
|
// 转口保名(消费面 / 单元测试档 import 面零改;`DEFAULT_DECLARATION` 另供本档分类裁判缺省取用)。
|
|
193
193
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
194
|
-
export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredIndexScope, isInDeclaredScope, declaredPublicRoots, declaredWritableRoots, clearDeclarationCache } from "./declaration.mjs"
|
|
194
|
+
export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredIndexScope, isInDeclaredScope, declaredPublicRoots, declaredWritableRoots, clearDeclarationCache, docLayers, docLayerOf } from "./declaration.mjs"
|