@thincoder/core 0.11.5 → 0.12.1
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 +27 -0
- package/abort-provenance.mjs +23 -0
- package/advisor/citations.mjs +5 -1
- package/advisor/compaction.mjs +13 -10
- package/advisor/history.mjs +6 -1
- package/advisor/loop.mjs +35 -10
- package/advisor/messages.mjs +31 -43
- package/advisor/project-context.mjs +49 -45
- package/advisor/run.mjs +82 -26
- package/advisor.mjs +40 -11
- package/agent/assemble.mjs +5 -5
- package/agent/chat-call.mjs +21 -1
- package/agent/completion.mjs +1 -20
- package/agent/dispatch-gates.mjs +8 -3
- package/agent/dispatch-run.mjs +131 -20
- package/agent/dispatch.mjs +23 -22
- package/agent/family-tools.mjs +4 -7
- package/agent/goal-judge.mjs +99 -0
- package/agent/goal-state.mjs +96 -0
- package/agent/helpers.mjs +13 -4
- package/agent/offload.mjs +1 -1
- package/agent/planning-graph-guardrail.mjs +224 -0
- package/agent/planning-prompt.mjs +179 -0
- package/agent/planning-step.mjs +460 -173
- package/agent/post-turn.mjs +23 -33
- package/agent/record-results.mjs +8 -5
- package/agent/run-stages.mjs +18 -38
- package/agent/run-start.mjs +26 -19
- package/agent/setup-reminders.mjs +16 -14
- package/agent/setup.mjs +3 -2
- package/agent/spawn-child.mjs +17 -4
- package/agent/suspension.mjs +42 -21
- package/agent/task-lifecycle.mjs +165 -52
- package/agent/timers.mjs +9 -1
- package/agent/turn-loop.mjs +160 -69
- package/agent/turn-projection.mjs +26 -15
- package/agent/turn-task-state.mjs +4 -4
- package/agent/write-gate-ledger.mjs +1 -1
- package/agent/write-gate.mjs +14 -11
- package/agent-tools/advisor-async.mjs +2 -0
- package/agent-tools/advisor-launch.mjs +27 -13
- package/agent-tools/advisor-settle.mjs +19 -18
- package/agent-tools/advisor.mjs +90 -13
- package/agent-tools/bash-async.mjs +3 -3
- package/agent-tools/batch-ledger-bind.mjs +8 -5
- package/agent-tools/batch-read.mjs +42 -0
- package/agent-tools/batch-record-write.mjs +20 -12
- package/agent-tools/batch-segment-vocab.mjs +6 -4
- package/agent-tools/batch-skeleton.mjs +43 -12
- package/agent-tools/consult.mjs +5 -1
- package/agent-tools/context.mjs +5 -4
- package/agent-tools/design-slots.mjs +7 -4
- package/agent-tools/design-token.mjs +3 -2
- package/agent-tools/doc-graph.mjs +257 -95
- package/agent-tools/escalate-async.mjs +4 -1
- package/agent-tools/goal.mjs +28 -95
- package/agent-tools/plan.mjs +1 -1
- package/agent-tools/review-facts.mjs +56 -7
- package/agent-tools/settings.mjs +35 -1
- package/agent-tools/ssh-transport.mjs +23 -22
- package/agent-tools/step.mjs +24 -4
- package/agent-tools/subagent-actions.mjs +6 -2
- package/agent-tools/subagent-async.mjs +4 -2
- package/agent-tools/subagent.mjs +1 -1
- package/agent-tools/task.mjs +73 -65
- package/agent-tools.mjs +3 -3
- package/agent.mjs +12 -3
- package/auto-think.mjs +16 -3
- package/browser/actions.mjs +5 -1
- package/browser/cdp.mjs +1 -1
- package/browser/pool.mjs +110 -17
- package/compaction-work-state.mjs +103 -13
- package/compress-form.mjs +29 -3
- package/config-defaults.mjs +27 -3
- package/config-io.mjs +3 -14
- package/config-normalize.mjs +24 -4
- package/config-presets.mjs +40 -26
- package/config-warn.mjs +30 -0
- package/config.mjs +139 -63
- package/context-degrade.mjs +4 -4
- package/context-push.mjs +20 -9
- package/context.mjs +65 -20
- package/doc-graph/anchors.mjs +39 -40
- package/doc-graph/clusters.mjs +49 -0
- package/doc-graph/code-parsers.mjs +494 -0
- package/doc-graph/context-pack.mjs +392 -0
- package/doc-graph/dir-signals.mjs +228 -0
- package/doc-graph/edges.mjs +231 -0
- package/doc-graph/format.mjs +70 -0
- package/doc-graph/gc-cmd.mjs +104 -0
- package/doc-graph/gc.mjs +112 -0
- package/doc-graph/glob-work-graph.mjs +307 -0
- package/doc-graph/golden-set.mjs +131 -0
- package/doc-graph/ls-work-graph.mjs +534 -0
- package/doc-graph/outline.mjs +377 -0
- package/doc-graph/output-annotations.mjs +85 -0
- package/doc-graph/process-docs.mjs +68 -0
- package/doc-graph/read-work-graph.mjs +91 -0
- package/doc-graph/rebuild-cmd.mjs +75 -0
- package/doc-graph/resolvers.mjs +322 -0
- package/doc-graph/roots.mjs +86 -0
- package/doc-graph/schema.mjs +110 -0
- package/doc-graph/search-augment.mjs +418 -0
- package/doc-graph/store.mjs +231 -0
- package/doc-graph/target-resolve.mjs +352 -0
- package/doc-graph/walk.mjs +87 -0
- package/doc-graph.mjs +583 -707
- package/explore-distill.mjs +52 -17
- package/generate-title.mjs +7 -4
- package/ledger-close.mjs +6 -6
- package/ledger-cmd.mjs +3 -3
- package/ledger-consistency.mjs +8 -6
- package/ledger-db.mjs +45 -10
- package/ledger-migrate.mjs +25 -10
- package/ledger-read.mjs +1 -1
- package/ledger-write-ops.mjs +6 -6
- package/ledger.mjs +2 -2
- package/model-context.mjs +54 -18
- package/model-specs.mjs +86 -67
- package/package.json +1 -1
- package/prompt-overlays.mjs +3 -3
- package/prompts/advisor-round1.md +6 -5
- package/prompts/common.md +16 -6
- package/prompts/consult-base.md +2 -1
- package/prompts/discipline-engineering.md +1 -1
- package/prompts/discipline-normal.md +12 -8
- package/prompts/knowledge/doc-lookup.md +2 -2
- package/prompts/knowledge/normal-batch-discipline.md +2 -2
- package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
- package/prompts/knowledge/tool-advisor.md +2 -2
- package/prompts/knowledge/tool-apply-patch.md +1 -1
- package/prompts/knowledge/tool-bash.md +2 -2
- package/prompts/knowledge/tool-batch.md +4 -4
- package/prompts/knowledge/tool-glob.md +9 -2
- package/prompts/knowledge/tool-goal.md +9 -6
- package/prompts/knowledge/tool-grep.md +7 -2
- package/prompts/knowledge/tool-ls.md +11 -5
- package/prompts/knowledge/tool-lsp.md +1 -1
- package/prompts/knowledge/tool-operations.md +3 -2
- package/prompts/knowledge/tool-plan.md +1 -1
- package/prompts/knowledge/tool-read.md +7 -6
- package/prompts/knowledge/tool-repo-graph-read.md +12 -0
- package/prompts/knowledge/tool-repo-graph.md +12 -0
- package/prompts/knowledge/tool-step.md +1 -1
- package/prompts/knowledge/tool-subagent.md +2 -2
- package/prompts/knowledge/tool-task.md +10 -9
- package/prompts/knowledge/tool-tree.md +7 -1
- package/prompts/persona-eng-coder.md +1 -1
- package/prompts/persona-eng-designer.md +1 -1
- package/prompts/persona-engineering.md +2 -1
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-normal.md +7 -6
- package/prompts/persona-plan.md +2 -2
- package/prompts/planning-next-moves.md +7 -8
- package/provider/anthropic.mjs +53 -51
- package/provider/core.mjs +85 -34
- package/provider/errors.mjs +33 -10
- package/provider/google.mjs +244 -37
- package/provider/list-models.mjs +28 -14
- package/provider/responses-request.mjs +15 -9
- package/provider/responses.mjs +10 -8
- package/provider/sse.mjs +3 -6
- package/proxy-transport.mjs +228 -119
- package/rules-file.mjs +79 -0
- package/rules.mjs +13 -51
- package/session-lifecycle.mjs +32 -20
- package/team-ledger.mjs +7 -7
- package/think-off.mjs +37 -18
- package/token-window.mjs +48 -31
- package/tool-args.mjs +8 -8
- package/tool-docs/bash.md +1 -1
- package/tool-docs/glob.md +3 -1
- package/tool-docs/goal.md +2 -2
- package/tool-docs/grep.md +3 -1
- package/tool-docs/ls.md +7 -1
- package/tool-docs/read.md +1 -1
- package/tool-docs/repo_graph-read.md +3 -0
- package/tool-docs/repo_graph.md +3 -0
- package/tool-docs/tree.md +1 -1
- package/tools/bash.mjs +53 -8
- package/tools/browser.mjs +4 -4
- package/tools/file.mjs +34 -7
- package/tools/glob-dialect.mjs +57 -7
- package/tools/index.mjs +3 -7
- package/tools/patch.mjs +8 -7
- package/tools/process-doc-mark.mjs +13 -0
- package/tools/search.mjs +152 -37
- package/tools/shared.mjs +6 -0
- package/tools/tree.mjs +211 -8
- package/window-policy.mjs +205 -126
- package/prompts/knowledge/tool-doc-graph-read.md +0 -20
- package/prompts/knowledge/tool-doc-graph.md +0 -49
- package/prompts/knowledge/tool-peek.md +0 -10
- package/prompts/knowledge/tool-repo-outline.md +0 -4
- package/tool-docs/doc_graph-read.md +0 -3
- package/tool-docs/doc_graph.md +0 -3
- package/tool-docs/peek.md +0 -3
- package/tool-docs/repo_outline.md +0 -3
- package/tools/peek.mjs +0 -447
|
@@ -2,17 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
## 能力边界
|
|
4
4
|
全套工具在手 —— 表里的每个工具都是你的。有写权限不等于这一轮第一个动作就是改文件:按 **Explore → Plan → Act → Verify** 真·微循环在主会话内小步快跑,**绝不凭直觉想两句直接开改,也不要把整批活攒成「大探索 → 大规划 → 连改二十轮 → 最后才验」的大瀑布**。
|
|
5
|
-
-
|
|
5
|
+
- **图谱拿全景、扫文档大纲、读源码用完整 `read`**:动手排查或修改某个模块/符号前,**先用 `repo_graph(action="context", query="<文件或符号>")`** 一键拿齐所属需求/设计档、上下游调用链、同级兄弟模块与测试(陌生仓库先 `repo_graph(action="overview")`,批量扫多份文档章节树或按标题抽节用 `repo_graph(action="outline", glob="…")`);**凡要理解、排查或修改的源码文件,直接用 `read` 完整读入整份文件**(先读清上下游完整实现再动手,严禁用 `bash` 切片抓几十行碎片充当读代码)。
|
|
6
|
+
- **标准层先读**:项目声明了 `docRoot.standards` 的地方,动盘改代码或正文文档之前先读它 —— 那一层是这个项目自己的规矩(含子目录 `.md`),不读就动手等于拿通用直觉替它的规则。
|
|
6
7
|
- **多源排查与闭环微步用 `step`**:只要调研要跨 2 个以上来源/模块核查(例如查项目最近变化、多端状态、多包 changelog + git 历史 + 源码落点),或主会话已连续探索 1–2 轮摸清线索、接下来还要读多份文件/翻日志/反复 `grep`,**立刻改用 1–3 个并发 `step(readonly=true)`** 把深挖过程挡在分叉里、只收带锚点的结论;单步「改代码 + 跑测试 + 修到绿」同样交给 `step(goal=..., verify=...)`。它复用主会话 KV 前缀缓存,比主会话连滚 5–10 轮 `read`/`grep` 更干净,比冷启动 `subagent` 更快。
|
|
7
|
-
- **主会话小切片推进(`task` 做微步节拍)**:动盘改任何代码或正文文档前,先把改动切成 **1–3 个文件即可独立验证的微步**,在 `task` 里把当前唯一第 1 步设为 `in_progress
|
|
8
|
-
- **模式护栏边界**:`normal` 模式走主会话轻量微循环并守「一批一档」(已有同主题在途批档直接沿用、没有就先 `batch create`,多轮交流修改期间保持进行中、绝不擅自关批,整批做完收口时再统一独立评审并 `batch close`,每轮附双报表);`tiny`
|
|
8
|
+
- **主会话小切片推进(`task` 做微步节拍)**:动盘改任何代码或正文文档前,先把改动切成 **1–3 个文件即可独立验证的微步**,在 `task` 里把当前唯一第 1 步设为 `in_progress` → 只改本步文件(直接改或交给 `step` 隔离执行)→ **当步立刻跑定向验证**(`doc_check` / 单测 / `lint`)并标 `done`,实测读数写进交付与验证声明 → 再切下一微步。
|
|
9
|
+
- **模式护栏边界**:`normal` 模式走主会话轻量微循环并守「一批一档」(已有同主题在途批档直接沿用、没有就先 `batch create`,多轮交流修改期间保持进行中、绝不擅自关批,整批做完收口时再统一独立评审并 `batch close`,每轮附双报表);`tiny` 模式仅免去建批/评审/双报表过程仪式,**不免去动笔前读清原有需求、设计与完整代码及改后验证**。
|
|
9
10
|
代码归你 —— 整个项目的代码都是你的代码。
|
|
10
11
|
|
|
11
12
|
## 角色与协作立场
|
|
12
13
|
编程是你与人之间的协作劳动。
|
|
13
14
|
方向由人定,最后一句话由人说。
|
|
14
15
|
你确认下来的,就是你的契约。
|
|
15
|
-
你是主工程师:统筹并走完这一批,最终对结果负责——普通模式在主会话内靠 `
|
|
16
|
+
你是主工程师:统筹并走完这一批,最终对结果负责——普通模式在主会话内靠 `repo_graph` 全景图谱与 `task` 小切片微循环直接推进,大块独立编码切片可按需派 `coder`,不像工程模式那样强制走设计席+实施席的硬分权链路。
|
|
16
17
|
派给子代理时,用同一把尺子要求它们:子代理偷工减料,是你的失职,不是它的。
|
|
17
18
|
**子代理编号在报告里要带账**:子代理状态用带台账列的表报 —— 形如 `coder #3 | #938 · <topic> | <task detail> | <status>`;只给序号 ⇒ 违规(用户不必问就能追到)。
|
|
18
19
|
|
|
@@ -23,7 +24,7 @@
|
|
|
23
24
|
- **给更好的选项,连带理由**:不是「我觉得这样更好」,而是每条路各花什么、你推荐哪条,让人好用这个判断反对它。
|
|
24
25
|
|
|
25
26
|
## 确认与批准闸(动手前对齐)
|
|
26
|
-
- **动手前对齐**:用一两句复述任务要点。复述要带查证行 —— 没有查证行的复述是猜测,不是计划。不要停下来等「行 / 好 / 继续」。沉默不是拦。用户当场纠正,按新话走。开工次序是 `
|
|
27
|
+
- **动手前对齐**:用一两句复述任务要点。复述要带查证行 —— 没有查证行的复述是猜测,不是计划。不要停下来等「行 / 好 / 继续」。沉默不是拦。用户当场纠正,按新话走。开工次序是 `repo_graph` 查清模块全景与现状 → 开帐起批并在 `task` 切出第 1 个小微步 → 小步改盘并当场验证 → 推进下一微步,绝不凭直觉想两句就直接动手。
|
|
27
28
|
为什么:用户把这件事交给你,就是要你走完这条链;每改一处再问一次,帐也开不起来。
|
|
28
29
|
- **说过的要求就是契约**:用户说过的每条要求(在对话 / 文档 / 计划里),说出口的那一刻就生效。
|
|
29
30
|
为什么:交付时缩水,等于用户把这件事交给你,收到的却是个折扣版。
|
|
@@ -54,7 +55,7 @@
|
|
|
54
55
|
**管理这一面归你**:普通模式没有设计者角色。开帐、起批、批档过程、收口都是你自己的笔。
|
|
55
56
|
**需求整合 ∥ 设计文本 ∥ 收口文档规整**都是你自己的活;之后会有一轮独立评审。
|
|
56
57
|
**批档 ∥ 台账 ∥ 收口**都由你写。
|
|
57
|
-
方向或范围还不清楚时,先用 `
|
|
58
|
+
方向或范围还不清楚时,先用 `repo_graph` 查清结构与关联文档再摊给用户;`normal` 模式下动手改盘按小微步切片推进:每步在 `task` 只记录当前步骤标题与 `in_progress` 状态,改完立刻验证结清再走下一步,既不凭直觉乱改,也不把十件事攒成最后才验的大瀑布。
|
|
58
59
|
|
|
59
60
|
## 系统接口(本角色收到的字段)
|
|
60
61
|
- **会话头块**(附在一次请求的第一条真用户消息上):
|
package/prompts/persona-plan.md
CHANGED
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
## 怎么做 Plan(必做四步查证,防漏项)
|
|
17
17
|
动笔写计划前必须按顺序完成以下四步查证(父侧已在 `knownFacts` 核实的事实直接采用,不重复查):
|
|
18
18
|
1. **逐条拆需求**:把 `goal` 与需求要点拆成编号条目(含后半句附带条件、文档同步与验证要求),每条后面必须能对应到具体文件与验证动作,防止后半句要求在规划阶段先丢掉。
|
|
19
|
-
2.
|
|
20
|
-
3.
|
|
19
|
+
2. **查权威文档与仓内先例**:优先用 `repo_graph(action="context"|"overview"|"outline")` 结合 `read` / `doc_search` 拿齐所属需求/设计档、核心模块骨架,并找一处同仓已有先例对齐风格、约束与边界(不凭记忆另造一套写法)。
|
|
20
|
+
3. **全仓扫调用方与同族逻辑**:用 `repo_graph(action="impact")` + `grep` / `code_search` 查清要改符号/模块的全部上下游调用方(含跨包/多端、既有测试、权威文档)以及**同族兄弟实现**(防只改一处漏掉同类逻辑)。
|
|
21
21
|
4. **交卷前对照原目标自检**:逐条核对① 每条需求都有落点、② 受影响文件(含须同轮更新的文档)全在盘且标明排除项(什么不改)、③ 边界/风险有具体退路、④ 附本改动定向验证命令。
|
|
22
22
|
|
|
23
23
|
## 报告职责
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
停一拍想清下一步。本轮只输出内部规划笔记(4–8 行、约 250–350 字),禁止调用任何工具,不写给用户的答复草稿;只写自上次规划后的新信号,无则写「无新增」。
|
|
2
2
|
|
|
3
|
-
1.
|
|
4
|
-
2.
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
4. **下一步与收敛尺**:列出最值推进主目标的 1–3 个具体动作与判据,**只补会直接改变核心结论或改盘决策的关键缺口**;若已把长任务放后台并设了 `timer` 且无其他独立可并行活,直接以等待态文字收尾等定时唤醒,严禁 `sleep` 阻塞轮询;当关键证据或实质产出已足以扎实回应用户核心诉求且无未完成落盘/验证/批档义务时即收口答复,不为了填满检查项继续发散。
|
|
3
|
+
1. **主目标对齐**:是否在推进主线、有无被支线带偏;旁枝记备忘。
|
|
4
|
+
2. **查证缺口**:先用 `repo_graph` 拿齐归属与上下游清单;未整档 `read` 的点名补读;对外部系统行为没把握或准备断言时,列搜索工具与查询词;关键分叉标 `question`。已核面简写「已核」。
|
|
5
|
+
3. **更优路径**:一句说明最快推进主目标的动作。
|
|
6
|
+
4. **下一步与收敛**:列 1–3 个动作;证据足以回应核心诉求且无挂账时即收口。
|
|
7
|
+
|
|
8
|
+
需同步任务清单时,正文末另起一行输出 `<task_sync>{...}</task_sync>` 标签。
|
package/provider/anthropic.mjs
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
* Docs: https://docs.anthropic.com/en/api/messages
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { specForModel, requestBudget } from "../config.mjs"
|
|
7
|
+
import { specForModel, requestBudget, policyBudget } from "../config.mjs"
|
|
8
8
|
import { proxyFetch } from "../proxy.mjs"
|
|
9
9
|
import { withUserAgent } from "../client-identity.mjs"
|
|
10
10
|
import { requestWithRetry } from "./retry.mjs"
|
|
11
11
|
import { effectiveFetchTimeoutMs, effectiveBodyIdleMs } from "./core.mjs"
|
|
12
12
|
import { assertPromptFits } from "./errors.mjs"
|
|
13
|
-
import { abortError } from "../abort-provenance.mjs"
|
|
13
|
+
import { abortError, isUserInterrupt, markInterrupted } from "../abort-provenance.mjs"
|
|
14
14
|
// 推理回声的可空表示与累加(设计 = `docs/core/design/AGENT-LOOP.md` §5.4)——四条 transport 同一口径。
|
|
15
15
|
import { appendReasoning } from "./reasoning-echo.mjs"
|
|
16
16
|
|
|
@@ -157,7 +157,7 @@ export function convertMessages(messages) {
|
|
|
157
157
|
* 2026-08-31 会诊 #6:接入 rateGate/recordRate + 429 Retry-After 单次重试
|
|
158
158
|
* (原实现完全绕过 TPM/RPM 闸门与记账——用户配了 tpm 以为受控实际不受控)。
|
|
159
159
|
* 注:5xx/网络退避重试未与 OpenAI 格式对齐(三 transport 共用那步工作量大,见报告)。 */
|
|
160
|
-
export async function chat(provider, { messages, tools, onToken, onReasoning, onWait, signal, toolChoice, parallelToolCalls, logCtx }) {
|
|
160
|
+
export async function chat(provider, { messages, tools, onToken, onReasoning, onWait, signal, toolChoice, parallelToolCalls, logCtx, measuredPrompt, reserveTokens, modelParams, settings }) {
|
|
161
161
|
// Extract system message(s) — Anthropic uses top-level `system` field
|
|
162
162
|
const systemMessages = []
|
|
163
163
|
const chatMessages = []
|
|
@@ -174,7 +174,7 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
174
174
|
|
|
175
175
|
const spec = specForModel(provider.model)
|
|
176
176
|
// §2.2 发送面:只读 maxTokens(输出合同)——请求体与发送前净判共用这一个对象,不各算一套。
|
|
177
|
-
const budget = requestBudget(provider)
|
|
177
|
+
const budget = requestBudget(provider, undefined, reserveTokens, settings)
|
|
178
178
|
const body = {
|
|
179
179
|
model: provider.model,
|
|
180
180
|
messages: adaptedMessages,
|
|
@@ -188,8 +188,8 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
188
188
|
// 2026-08-31:tool_choice 能力层——OpenAI 语义映射到 Anthropic tool_choice
|
|
189
189
|
// (auto→{type:"auto"} / required→{type:"any"} / none→{type:"none"} / 具体函数→{type:"tool",name})
|
|
190
190
|
if (toolChoice !== undefined) body.tool_choice = mapToolChoice(toolChoice)
|
|
191
|
-
if (
|
|
192
|
-
let t =
|
|
191
|
+
if (modelParams?.temperature != null) {
|
|
192
|
+
let t = modelParams?.temperature
|
|
193
193
|
// Anthropic API hard limit is 0-1; models without a declared tempRange still get clamped
|
|
194
194
|
const [tMin, tMax] = spec.tempRange ?? [0, 1]
|
|
195
195
|
t = Math.min(tMax, Math.max(tMin, t))
|
|
@@ -216,7 +216,8 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
216
216
|
// 走 body 会把整块 system 漏在判据外。`estimated`(含 max_tokens)仍供 rateGate / recordRate。
|
|
217
217
|
const estPrompt = estimateRequestTokens({ messages, tools })
|
|
218
218
|
const estimated = estimateRequestTokens(body)
|
|
219
|
-
|
|
219
|
+
// 预算面 = 体那一处已算好的同一个对象(§2.2);判据优先取整量实测(§2.5)——不另算第二份。
|
|
220
|
+
assertPromptFits(provider, estPrompt, logCtx, budget, measuredPrompt)
|
|
220
221
|
await rateGate(provider, estimated, onWait, signal)
|
|
221
222
|
|
|
222
223
|
// 2026-08-31:4xx/5xx/网络与 OpenAI 格式统一退避重试链(原仅 429 Retry-After 单次重试,
|
|
@@ -253,25 +254,20 @@ function mapAnthropicStopReason(reason) {
|
|
|
253
254
|
return reason
|
|
254
255
|
}
|
|
255
256
|
|
|
256
|
-
/** Convert the parsed stream to the core.mjs result shape (usage → OpenAI-compatible).
|
|
257
|
+
/** Convert the parsed stream to the core.mjs result shape (usage → OpenAI-compatible).
|
|
258
|
+
* 展开 `...result` 保留 transport 标记(`interrupted` 等)——字面量重建会静默吞掉它们。 */
|
|
257
259
|
function finishAnthropic(result) {
|
|
260
|
+
const out = { ...result, finishReason: result.finishReason ?? null }
|
|
258
261
|
const usage = result.usage
|
|
259
|
-
if (usage)
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
completion_tokens: usage.output_tokens ?? 0,
|
|
267
|
-
total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),
|
|
268
|
-
prompt_cache_hit_tokens: usage.cache_read_input_tokens ?? 0,
|
|
269
|
-
prompt_cache_miss_tokens: usage.cache_creation_input_tokens ?? 0,
|
|
270
|
-
},
|
|
271
|
-
toolCalls: result.toolCalls,
|
|
272
|
-
}
|
|
262
|
+
if (!usage) return out
|
|
263
|
+
out.usage = {
|
|
264
|
+
prompt_tokens: usage.input_tokens ?? 0,
|
|
265
|
+
completion_tokens: usage.output_tokens ?? 0,
|
|
266
|
+
total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),
|
|
267
|
+
prompt_cache_hit_tokens: usage.cache_read_input_tokens ?? 0,
|
|
268
|
+
prompt_cache_miss_tokens: usage.cache_creation_input_tokens ?? 0,
|
|
273
269
|
}
|
|
274
|
-
return
|
|
270
|
+
return out
|
|
275
271
|
}
|
|
276
272
|
|
|
277
273
|
/**
|
|
@@ -331,41 +327,47 @@ async function parseAnthropicStream(response, { onToken, onReasoning, signal })
|
|
|
331
327
|
let currentEvent = ""
|
|
332
328
|
let currentData = ""
|
|
333
329
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
330
|
+
// 中断面(与 sse ∥ google ∥ responses 同形):用户按停时保留已流出的正文并标 `interrupted`,
|
|
331
|
+
// 不把整轮降级成一条 AbortError(否则内容不入历史、`turn-loop` 的 interrupted 分支也不进)。
|
|
332
|
+
try {
|
|
333
|
+
for await (const chunk of response.body) {
|
|
334
|
+
if (isUserInterrupt(signal)) return markInterrupted(result, signal)
|
|
335
|
+
buffer += decoder.decode(chunk, { stream: true })
|
|
336
|
+
// BOM 剥除(会诊 #12):首个 chunk 可能带 \uFEFF,否则 message_start 事件被静默丢失(含 usage)
|
|
337
|
+
if (buffer.charCodeAt(0) === 0xfeff) buffer = buffer.slice(1)
|
|
338
|
+
const lines = buffer.split("\n")
|
|
339
|
+
buffer = lines.pop()
|
|
343
340
|
|
|
344
|
-
|
|
341
|
+
for (const line of lines) {
|
|
342
|
+
if (line.startsWith("event: ")) {
|
|
343
|
+
if (currentEvent) processEvent(currentEvent, currentData)
|
|
344
|
+
currentEvent = line.slice(7).trim()
|
|
345
|
+
currentData = ""
|
|
346
|
+
} else if (line.startsWith("data: ")) {
|
|
347
|
+
currentData = line.slice(6).trim()
|
|
348
|
+
} else if (line === "" || line === "\r") { // CRLF 空行是 "\r"(会诊 #13)
|
|
349
|
+
if (currentEvent) processEvent(currentEvent, currentData)
|
|
350
|
+
currentEvent = ""
|
|
351
|
+
currentData = ""
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
// Flush remaining
|
|
356
|
+
buffer += decoder.decode()
|
|
357
|
+
for (const line of buffer.split("\n")) {
|
|
345
358
|
if (line.startsWith("event: ")) {
|
|
346
359
|
if (currentEvent) processEvent(currentEvent, currentData)
|
|
347
|
-
currentEvent = line.slice(7)
|
|
348
|
-
currentData = ""
|
|
360
|
+
currentEvent = line.slice(7)
|
|
349
361
|
} else if (line.startsWith("data: ")) {
|
|
350
|
-
currentData = line.slice(6)
|
|
351
|
-
} else if (line === "" || line === "\r") { // CRLF 空行是 "\r"(会诊 #13)
|
|
352
|
-
if (currentEvent) processEvent(currentEvent, currentData)
|
|
353
|
-
currentEvent = ""
|
|
354
|
-
currentData = ""
|
|
362
|
+
currentData = line.slice(6)
|
|
355
363
|
}
|
|
356
364
|
}
|
|
365
|
+
if (currentEvent) processEvent(currentEvent, currentData)
|
|
366
|
+
} catch (e) {
|
|
367
|
+
// 中止可能以 reason 对象 ∥ 非 AbortError 上抛(同 2026-12-01 批的实测):信号是权威。
|
|
368
|
+
if (isUserInterrupt(signal)) return markInterrupted(result, signal)
|
|
369
|
+
throw e
|
|
357
370
|
}
|
|
358
|
-
// Flush remaining
|
|
359
|
-
buffer += decoder.decode()
|
|
360
|
-
for (const line of buffer.split("\n")) {
|
|
361
|
-
if (line.startsWith("event: ")) {
|
|
362
|
-
if (currentEvent) processEvent(currentEvent, currentData)
|
|
363
|
-
currentEvent = line.slice(7)
|
|
364
|
-
} else if (line.startsWith("data: ")) {
|
|
365
|
-
currentData = line.slice(6)
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
if (currentEvent) processEvent(currentEvent, currentData)
|
|
369
371
|
|
|
370
372
|
return result
|
|
371
373
|
}
|
package/provider/core.mjs
CHANGED
|
@@ -4,14 +4,14 @@
|
|
|
4
4
|
* SSE parsing → provider/sse.mjs
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { providerSpec, requestBudget, resolveEnableThinking } from "../config.mjs"
|
|
7
|
+
import { providerSpec, requestBudget, policyBudget, resolveEnableThinking } from "../config.mjs"
|
|
8
8
|
import { DEFAULT_BODY_IDLE_MS } from "../config-defaults.mjs"
|
|
9
9
|
import { resolveProviderSecrets } from "../env-ref.mjs"
|
|
10
10
|
import { proxyFetch } from "../proxy.mjs"
|
|
11
11
|
import { withUserAgent } from "../client-identity.mjs"
|
|
12
12
|
import { escapeMessages, stripLocalMessageFields } from "../escape.mjs"
|
|
13
13
|
import { logEvent, errText, classifyErr, headText } from "../log.mjs"
|
|
14
|
-
import { abortError, annotateAbort, deathLine } from "../abort-provenance.mjs"
|
|
14
|
+
import { abortError, annotateAbort, deathLine, isUserInterrupt, markInterrupted } from "../abort-provenance.mjs"
|
|
15
15
|
import { recordChatTrace } from "../traces/trace-store.mjs"
|
|
16
16
|
import { readSSE } from "./sse.mjs"
|
|
17
17
|
export { readSSE } from "./sse.mjs"
|
|
@@ -52,16 +52,17 @@ export function createProvider(config) {
|
|
|
52
52
|
baseURL: config.baseURL.replace(/\/+$/, ""),
|
|
53
53
|
apiKey: config.apiKey,
|
|
54
54
|
model: config.model,
|
|
55
|
-
maxTokens: config.maxTokens,
|
|
56
|
-
temperature: config.temperature,
|
|
57
|
-
thinking: config.thinking,
|
|
58
|
-
reasoningEffort: config.reasoningEffort,
|
|
59
55
|
tpm: config.tpm,
|
|
60
56
|
rpm: config.rpm,
|
|
61
57
|
format: config.format,
|
|
62
58
|
chatPath: config.chatPath,
|
|
63
59
|
proxy: config.proxy,
|
|
64
60
|
proxyUri: config.proxyUri,
|
|
61
|
+
// 派生运行视图(CONTEXT-COMPACTION.md §2.1 档位上限):会话档位随这次白名单拷贝走(数据来源 = `bindProviderContextPolicy` 落的 `mode`)。
|
|
62
|
+
// 2026-12-03 批:不再拷贝 `contextCaps`——档位上限表与模型窗口声明住设置层
|
|
63
|
+
// (`config.agent.contextCaps` ∥ `config.modelContext`),由读面经 `chat(provider, { settings })` 带过去,
|
|
64
|
+
// provider 形状的对象上不得再有这两个键。
|
|
65
|
+
...(config.mode !== undefined ? { mode: config.mode } : {}),
|
|
65
66
|
}
|
|
66
67
|
}
|
|
67
68
|
|
|
@@ -84,6 +85,38 @@ export function effectiveBodyIdleMs(provider) {
|
|
|
84
85
|
? provider.bodyIdleTimeoutMs : DEFAULT_BODY_IDLE_MS
|
|
85
86
|
}
|
|
86
87
|
|
|
88
|
+
/** 流收尾后的中断判定(2026-12-01 批 interrupt-after-stream)——**唯一判定点**,四条 transport 同覆盖。
|
|
89
|
+
*
|
|
90
|
+
* 为什么不能只在各 transport 的 catch 里判:abort 会把响应体直接终结(socket 被销毁 ∥ 流被解绑),
|
|
91
|
+
* 而 `for await (const chunk of response.body)` 在这种情况下会**正常收尾而不抛错** ⇒ catch 里的
|
|
92
|
+
* `if (e.name === "AbortError" && signal?.reason?.interrupt)` 根本进不去(循环体内那次 `signal.aborted`
|
|
93
|
+
* 检查要有「下一个 chunk」才走得到,abort 后就没有下一个了)。实测(2026-12-01,真实上游):
|
|
94
|
+
* gemini 返回 `interrupted=undefined` 且 `partial=undefined`,OpenAI 形落 `partial=true`、同样无 `interrupted`。
|
|
95
|
+
*
|
|
96
|
+
* 判据(两支同守「完整响应不动」:`finishReason != null` 即已有终态,abort 晚到不得把成功改成失败):
|
|
97
|
+
* - `reason.interrupt === true` ⇒ 标 `interrupted`(+ 有 message 时带 `interruptMessage`,无 message 时
|
|
98
|
+
* 不造假文案——CLI Ctrl+C 首按的「停回合」就是这个形)。已收内容原样保留;`agent/turn-loop.mjs`
|
|
99
|
+
* 的 `if (response.interrupted)` 分支据此提交部分输出、注入 `[User interrupt…]` 并抛 AbortError 续跑。
|
|
100
|
+
* - 其余任何已中止信号(timeout ∥ stop ∥ cancel ∥ **无 reason 的裸 `abort()`**)⇒ 按 `abortError`
|
|
101
|
+
* 抛出:截断的响应不得冒充完成(需求 §6.3「未知要显式」同向——裸 abort 走这一支,`deathLine`
|
|
102
|
+
* 会把它标成 `abort(unknown@provider:…)`)。`partial` **不**豁免:socket 断连是底层表象,发起者是中止方。
|
|
103
|
+
* @param {object} result — transport 返回的统一结果
|
|
104
|
+
* @param {AbortSignal|undefined} signal
|
|
105
|
+
* @returns {object} 同一个 result(必要时就地补字段)
|
|
106
|
+
*/
|
|
107
|
+
export function settleAbortAfterStream(result, signal) {
|
|
108
|
+
if (!result || !signal?.aborted) return result
|
|
109
|
+
// 完整收尾的响应不动:abort 晚到(响应已完)不得把成功改成失败。两支同守。
|
|
110
|
+
if (result.finishReason != null) return result
|
|
111
|
+
if (isUserInterrupt(signal)) {
|
|
112
|
+
if (!result.interrupted) markInterrupted(result, signal)
|
|
113
|
+
return result
|
|
114
|
+
}
|
|
115
|
+
// 已知非用户中止(stop ∥ cancel ∥ timeout)或 reason 缺失的裸 abort:本轮被中止,
|
|
116
|
+
// 截断的结果不得冒充完成——即使 transport 已因 socket 断连判成 `partial`。
|
|
117
|
+
throw abortError(signal, "provider", "post-stream")
|
|
118
|
+
}
|
|
119
|
+
|
|
87
120
|
export async function chat(provider, opts = {}) {
|
|
88
121
|
// LOGGING(docs/design/LOGGING.md):llm:* 事件统一在此落点——所有 chat 调用
|
|
89
122
|
// (主回合/消化轮/compress/distill/advisor/子代理/auto-think/consult)都经本函数,
|
|
@@ -98,7 +131,8 @@ export async function chat(provider, opts = {}) {
|
|
|
98
131
|
const pname = provider?.name ?? provider?.model ?? "unknown"
|
|
99
132
|
logEvent("llm:start", { provider: pname, model: provider?.model ?? "", stage: logCtx.stage, turn: logCtx.turn, auto: logCtx.auto === true, child: logCtx.child })
|
|
100
133
|
try {
|
|
101
|
-
|
|
134
|
+
// 出口补一步中断判定:abort 可能让流循环正常收尾(见 settleAbortAfterStream 档头)。
|
|
135
|
+
const result = settleAbortAfterStream(await chatImpl(provider, opts), opts.signal)
|
|
102
136
|
logEvent("llm:done", {
|
|
103
137
|
provider: pname, model: provider?.model ?? "",
|
|
104
138
|
ms: Date.now() - t0,
|
|
@@ -126,7 +160,7 @@ export async function chat(provider, opts = {}) {
|
|
|
126
160
|
}
|
|
127
161
|
|
|
128
162
|
/** chat 本体(LOG(LLM) 事件包装之外——见上方 chat 包装器)。 */
|
|
129
|
-
async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWait, signal, streamRules, firedPatterns, toolChoice, parallelToolCalls, logCtx }) {
|
|
163
|
+
async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWait, signal, streamRules, firedPatterns, toolChoice, parallelToolCalls, logCtx, measuredPrompt, reserveTokens, modelParams, settings }) {
|
|
130
164
|
// #57(provider-config-family 批):凭据值位 `${env:VAR}` 消费侧解析——单源 `../env-ref.mjs`
|
|
131
165
|
// (CONFIG.md §6.3)。格式分派之前:四 transport ∕ 续写 ∕ advisor ∕ 子代理 ∕ 压缩同享;
|
|
132
166
|
// 未设 ∕ 空串 ∕ 畸形 ⇒ 此处抛错(点名变量,无回退)。
|
|
@@ -138,9 +172,10 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
138
172
|
if (!apiKey) throw new Error(`API key missing for provider "${provider?.name ?? provider?.model ?? "unknown"}" — configure it in Settings (Providers) or ~/.thincoder/config.json`)
|
|
139
173
|
// Sanitize BEFORE format dispatch — image poisoning bricks anthropic/google sessions
|
|
140
174
|
// the same way it bricks OpenAI-format ones (all raster-only).
|
|
141
|
-
// providerSpec: spec with the
|
|
142
|
-
// window/clamping logic below reads the
|
|
143
|
-
|
|
175
|
+
// providerSpec: spec with the context resolution chain (PROVIDER.md §6.15) — the
|
|
176
|
+
// window/clamping logic below reads the resolved value where it matters. 2026-12-03 批:
|
|
177
|
+
// 模型窗口声明住设置层顶层(`settings.modelContext`),经 `opts.settings` 传入,不读 provider 条目。
|
|
178
|
+
const spec = providerSpec(provider, settings)
|
|
144
179
|
messages = stripImagesForTextModel(messages, spec)
|
|
145
180
|
// #853 D-PR32:历史图片累计字节预算——发送前对消息副本累计驱逐(最老先弃;history 本体零触)。
|
|
146
181
|
messages = capHistoryImages(messages)
|
|
@@ -159,9 +194,11 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
159
194
|
const result = await anthropicChat(provider, {
|
|
160
195
|
messages,
|
|
161
196
|
tools: tools?.length ? normalizeTools(tools) : null,
|
|
162
|
-
onToken, onReasoning, onWait, signal, toolChoice,
|
|
197
|
+
onToken, onReasoning, onWait, signal, toolChoice, reserveTokens, modelParams,
|
|
163
198
|
// §6.17 豁免面:内部阶段标签(compress / distill / 续写)需传到发送面净判
|
|
164
199
|
logCtx,
|
|
200
|
+
measuredPrompt,
|
|
201
|
+
settings,
|
|
165
202
|
})
|
|
166
203
|
return result
|
|
167
204
|
}
|
|
@@ -171,9 +208,11 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
171
208
|
const result = await geminiChat(provider, {
|
|
172
209
|
messages,
|
|
173
210
|
tools: tools?.length ? normalizeTools(tools) : null,
|
|
174
|
-
onToken, onReasoning, onWait, signal, toolChoice,
|
|
211
|
+
onToken, onReasoning, onWait, signal, toolChoice, reserveTokens, modelParams,
|
|
175
212
|
// §6.17 豁免面:内部阶段标签(compress / distill / 续写)需传到发送面净判
|
|
176
213
|
logCtx,
|
|
214
|
+
measuredPrompt,
|
|
215
|
+
settings,
|
|
177
216
|
})
|
|
178
217
|
return result
|
|
179
218
|
}
|
|
@@ -186,8 +225,10 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
186
225
|
return responsesChat(provider, {
|
|
187
226
|
messages,
|
|
188
227
|
tools,
|
|
189
|
-
onToken, onReasoning, onWait, signal, toolChoice,
|
|
228
|
+
onToken, onReasoning, onWait, signal, toolChoice, reserveTokens, modelParams,
|
|
190
229
|
logCtx, // §6.17 豁免面(compress / distill / 续写)
|
|
230
|
+
measuredPrompt,
|
|
231
|
+
settings,
|
|
191
232
|
})
|
|
192
233
|
}
|
|
193
234
|
|
|
@@ -207,42 +248,44 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
207
248
|
}
|
|
208
249
|
// 保守抑制(非能力断言):带 `noUsageStream` 的行 = 核不主动发 stream_options.include_usage(glm 族已实测带该参数全 200);逐族等级 = MODEL-SPECS.md §15.2
|
|
209
250
|
if (!spec.noUsageStream) body.stream_options = { include_usage: true }
|
|
210
|
-
// §
|
|
211
|
-
//
|
|
212
|
-
|
|
251
|
+
// §2.2 发送面同源:max_tokens = requestBudget().maxTokens = reserve(**恒有值**——输出预留三档都发出它;
|
|
252
|
+
// 「服务端不发时自己会留多少」那三档已于 2026-11-29 退役,用户侧已无渠道级覆盖可设)。
|
|
253
|
+
// 同一个预算对象也交给发送前净判(§2.2「stats、守卫和压缩使用同一预算对象」)——**体与守卫共用它**:
|
|
254
|
+
// 守卫因此不再另算一份,`reserveTokens` 只需在一处接上,两处分家在结构上不可能。
|
|
255
|
+
const budget = requestBudget(provider, spec, reserveTokens, settings)
|
|
213
256
|
if (budget.maxTokens !== undefined) body.max_tokens = budget.maxTokens
|
|
214
|
-
if (
|
|
215
|
-
let t =
|
|
257
|
+
if (modelParams?.temperature != null) {
|
|
258
|
+
let t = modelParams?.temperature
|
|
216
259
|
if (spec.tempRange) {
|
|
217
260
|
t = Math.min(spec.tempRange[1], Math.max(spec.tempRange[0], t))
|
|
218
261
|
t = Math.round(t * 100) / 100
|
|
219
262
|
}
|
|
220
263
|
body.temperature = t
|
|
221
264
|
}
|
|
222
|
-
if (
|
|
265
|
+
if (modelParams?.thinking) body.thinking = modelParams?.thinking
|
|
223
266
|
// reasoning_effort is a provider-native parameter — routers/proxies (model ID with "/"
|
|
224
267
|
// prefix like kimi/kimi-k3) may misinterpret it, causing empty responses or 400s.
|
|
225
268
|
const isRouter = provider.model.includes("/")
|
|
226
|
-
if (
|
|
227
|
-
if (spec.reasoningEffortEnum && !spec.reasoningEffortEnum.includes(
|
|
269
|
+
if (modelParams?.reasoningEffort && !isRouter && provider.format !== "anthropic" && provider.format !== "google") {
|
|
270
|
+
if (spec.reasoningEffortEnum && !spec.reasoningEffortEnum.includes(modelParams?.reasoningEffort)) {
|
|
228
271
|
throw new Error(
|
|
229
|
-
`reasoning_effort "${
|
|
272
|
+
`reasoning_effort "${modelParams?.reasoningEffort}" not supported by model "${provider.model}"; ` +
|
|
230
273
|
`valid values: ${spec.reasoningEffortEnum.join(", ")}`
|
|
231
274
|
)
|
|
232
275
|
}
|
|
233
|
-
body.reasoning_effort =
|
|
276
|
+
body.reasoning_effort = modelParams?.reasoningEffort
|
|
234
277
|
} else if (
|
|
235
278
|
// D-14(MODEL-SPECS §9.6 · 批 2026-09-20-channel-onboarding):effort 族非百炼渠道的
|
|
236
279
|
// 「off 静默失效」——两端「关思考」发的是 `thinking:null` 标记(CLI cmd-think.mjs / VSC
|
|
237
|
-
// reasoning-mode.mjs),该标记在 `if (
|
|
280
|
+
// reasoning-mode.mjs),该标记在 `if (modelParams?.thinking) body.thinking = …` 那支被 falsy 跳过 ⇒ 服务端默认想 on、不发任何思考字段
|
|
238
281
|
// = UI 显 OFF 实际在想(假告知,同 PROVIDER.md §6.12 先例)。`reasoning_effort:"none"` 是
|
|
239
282
|
// 实测唯一有效 off 路径(hy3 / seed:tok=0、rc 消失)。五 guard 面(MODEL-SPECS §9.9 B-5):
|
|
240
283
|
// 无枚举行(hy4-preview)透传不变 / 显式档优先只携该档(上支)/ 百炼 flash 同义多携 /
|
|
241
284
|
// 枚举不含 "none" 者(kimi-k3)不发 / 含 "/" 路由形态名不发(复用 isRouter)。
|
|
242
|
-
|
|
285
|
+
modelParams?.thinking === null &&
|
|
243
286
|
spec.thinkApi === "effort" &&
|
|
244
287
|
spec.reasoningEffortEnum?.includes("none") &&
|
|
245
|
-
|
|
288
|
+
modelParams?.reasoningEffort == null &&
|
|
246
289
|
!isRouter
|
|
247
290
|
) {
|
|
248
291
|
body.reasoning_effort = "none"
|
|
@@ -250,7 +293,7 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
250
293
|
// enable_thinking — Bailian hybrid-thinking switch (PROVIDER.md §6.12): qwen3.x defaults to
|
|
251
294
|
// thinking ON, so an explicit off must send enable_thinking:false or the server keeps thinking.
|
|
252
295
|
// NOT gated by isRouter: the whitelist keys on model prefix + Bailian host, not the model-ID slash.
|
|
253
|
-
const enableThinking = resolveEnableThinking(provider, spec)
|
|
296
|
+
const enableThinking = resolveEnableThinking(provider, spec, modelParams)
|
|
254
297
|
if (enableThinking !== undefined) body.enable_thinking = enableThinking
|
|
255
298
|
if (tools?.length) body.tools = tools
|
|
256
299
|
// 2026-08-31:tool_choice 能力层(透传 OpenAI 语义);
|
|
@@ -259,9 +302,11 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
259
302
|
if (parallelToolCalls === true) body.parallel_tool_calls = true
|
|
260
303
|
|
|
261
304
|
const estimated = estimateRequestTokens(body)
|
|
262
|
-
// §
|
|
305
|
+
// §2.5 发送面净判(第二道):`estPrompt` = 输入侧估算——不减掉 `max_tokens` 会把输出预算白扣一份。
|
|
306
|
+
// 判据优先取整量实测 `measuredPrompt`(压缩判定读的同一个数);预算面 = 上面体那一处已算好的**同一个
|
|
307
|
+
// 对象** `budget`(两出口在本档逐位相等,已实测)——体与守卫同源,`reserveTokens` 只在一处接上。
|
|
263
308
|
const estPrompt = estimated - (body.max_tokens ?? 0)
|
|
264
|
-
assertPromptFits(provider, estPrompt, logCtx, budget)
|
|
309
|
+
assertPromptFits(provider, estPrompt, logCtx, budget, measuredPrompt)
|
|
265
310
|
await rateGate(provider, estimated, onWait, signal)
|
|
266
311
|
|
|
267
312
|
const response = await requestWithRetry(provider, body, signal, onWait)
|
|
@@ -311,6 +356,11 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
311
356
|
onReasoning,
|
|
312
357
|
onWait,
|
|
313
358
|
signal,
|
|
359
|
+
// 输出预算随本次调用下传(与首次同档):续写是同一逻辑调用的子请求,预算换档会让
|
|
360
|
+
// 「守卫读的数」与「续写那条请求实发的数」分家。
|
|
361
|
+
reserveTokens,
|
|
362
|
+
modelParams,
|
|
363
|
+
settings,
|
|
314
364
|
// TRACES.md §6.1:续写是同一逻辑调用的子请求——logCtx 原样透传(元数据与门控
|
|
315
365
|
// traces.enabled 对续写调用同样生效,不在出口静默越过开关)
|
|
316
366
|
// fix round1(D-TR1):续写子请求标记 isContinuation:true(T-TR14——true =
|
|
@@ -318,8 +368,8 @@ async function chatImpl(provider, { messages, tools, onToken, onReasoning, onWai
|
|
|
318
368
|
logCtx: { ...logCtx, isContinuation: true },
|
|
319
369
|
})
|
|
320
370
|
} catch (error) {
|
|
321
|
-
// §6.14 失败可见性:续写失败注入 _warnings(agent
|
|
322
|
-
if (error?.name === "AbortError") throw error
|
|
371
|
+
// §6.14 失败可见性:续写失败注入 _warnings(agent 机读线可见)不整轮飞出;中断透传
|
|
372
|
+
if (error?.name === "AbortError" || signal?.aborted) throw error
|
|
323
373
|
result._warnings ??= []
|
|
324
374
|
result._warnings.push({ name: "continuation-failed", message: `output continuation failed: ${error.message}` })
|
|
325
375
|
break
|
|
@@ -435,8 +485,9 @@ async function requestWithRetry(provider, body, signal, onWait) {
|
|
|
435
485
|
// 原 call-site 分叉删除)。
|
|
436
486
|
response = await proxyFetch(url, opts, provider.proxyUri)
|
|
437
487
|
} catch (error) {
|
|
438
|
-
//
|
|
439
|
-
|
|
488
|
+
// 中断面:信号是权威(同 `isUserInterrupt` 的档头)——非 `AbortError` 形态的中止不得被当成
|
|
489
|
+
// 可重试网络错误推进重试链。§6.12 站点 #2:fetch 拒否面补标来源。
|
|
490
|
+
if (error.name === "AbortError" || isUserInterrupt(signal)) throw annotateAbort(error, signal, "provider", "request")
|
|
440
491
|
lastError = error
|
|
441
492
|
continue
|
|
442
493
|
}
|
package/provider/errors.mjs
CHANGED
|
@@ -140,11 +140,15 @@ export function classifyResponsesErrorCode(code) {
|
|
|
140
140
|
const CONTEXT_OVERFLOW_PHRASES = ["maximum context length", "context_length_exceeded", "prompt is too long"]
|
|
141
141
|
|
|
142
142
|
/** 越窗 typed 错误(§6.17):三实数逐字带出(prompt / max_tokens / 窗口,另附 limit);kind / retryable
|
|
143
|
-
* 复用同族既有词表(`classifyResponsesErrorCode("context_length_exceeded")`),零新词。
|
|
144
|
-
|
|
143
|
+
* 复用同族既有词表(`classifyResponsesErrorCode("context_length_exceeded")`),零新词。
|
|
144
|
+
* `basis` = 被判那个数的口径(`"measured"` ∥ `"estimated"`,§2.5):A 之后这个数可能来自整量实测、
|
|
145
|
+
* 也可能来自发送面估算,两个口径的数不同量——不标口径,读者拿它跟状态行比对时分不出比的是哪一个。
|
|
146
|
+
* 词表与 stats 面同两条(§2.5「按 `basis` 取两种,不做第三种」);缺省按估算(两条来路都显式传)。 */
|
|
147
|
+
export function contextOverflowError(provider, prompt, budget, remedy, basis) {
|
|
145
148
|
const cls = classifyResponsesErrorCode("context_length_exceeded")
|
|
149
|
+
const word = basis === "measured" ? "measured" : "estimated"
|
|
146
150
|
const err = new Error(
|
|
147
|
-
`context overflow: prompt ~${prompt} tokens · max_tokens ${budget.maxTokens ?? "not sent"}` +
|
|
151
|
+
`context overflow: ${word} prompt ~${prompt} tokens · max_tokens ${budget.maxTokens ?? "not sent"}` +
|
|
148
152
|
` · window ${budget.window} (limit ${budget.limit}) — ${remedy} [model ${provider?.model ?? "unknown"}]`,
|
|
149
153
|
)
|
|
150
154
|
err.kind = cls.kind
|
|
@@ -179,22 +183,41 @@ export function overheadOverflowError(provider, budget, usage) {
|
|
|
179
183
|
return err
|
|
180
184
|
}
|
|
181
185
|
|
|
182
|
-
/**
|
|
186
|
+
/** 发送面净判(`CONTEXT-COMPACTION.md` §2.5 的第二道,四个装配面同形一次调用):判据 = **整量测度的实测值**
|
|
187
|
+
* `measuredPrompt`(= `contextUsage(agent, …).total`,压缩判定与状态行读的**同一个数**);调用方拿不到
|
|
188
|
+
* 整量读数时(非会话链路:标题、蒸馏、顾问、独立基准)退回发送面估算 `estPrompt`
|
|
183
189
|
* (= `estimateRequestTokens(X) − (body.max_tokens ?? 0)`,四面同一定义——不减会把输出预算白扣一份)。
|
|
190
|
+
* 为什么必须以实测为主:只判未校准估算时,校准比 < 1 的长会话(估算比实测高)会被**假越窗**拦在本地——
|
|
191
|
+
* 服务端一次都没收到,而会话本身装得下。
|
|
184
192
|
* 内部阶段豁免:`compress` / `distill` / 续写本身就是越线后用来把上下文降下来的那次调用,
|
|
185
193
|
* 判它 = 判掉止血动作本身(标签已存在,零新增机制)。
|
|
186
|
-
* `budget` =
|
|
187
|
-
*
|
|
194
|
+
* `budget` = **调用方已算好的预算对象**——守卫读**有效窗口**那一支 `policyBudget`(§2.2:压缩阈值、
|
|
195
|
+
* stats、发送前守卫读它);本档不自己重算一次预算(§2.2「stats、守卫和压缩使用同一预算对象」):
|
|
188
196
|
* 重算一处就会与调用方那处按不同窗口算,报文里的 limit 与它拿来判的 limit 成了两个数。
|
|
189
197
|
* 缺参即拒,不给默认值:漏传时 `estPrompt > undefined` 恒为假 ⇒ 守卫静默放行(比不守更贵)。 */
|
|
190
|
-
export function assertPromptFits(provider, estPrompt, logCtx, budget) {
|
|
198
|
+
export function assertPromptFits(provider, estPrompt, logCtx, budget, measuredPrompt) {
|
|
191
199
|
const stage = logCtx?.stage
|
|
192
200
|
if (stage === "compress" || stage === "distill" || logCtx?.isContinuation === true) return
|
|
193
201
|
if (!budget || typeof budget.limit !== "number") {
|
|
194
|
-
throw new Error(`assertPromptFits: budget is required (the
|
|
202
|
+
throw new Error(`assertPromptFits: budget is required (the budget object shared by this call's body and guard) — got ${JSON.stringify(budget)}; a missing budget would silently disable the pre-send guard`)
|
|
195
203
|
}
|
|
196
|
-
|
|
197
|
-
|
|
204
|
+
// 判据优先级:整量实测 > 发送面估算。两个数都是「输入侧」口径(应答的输出预留不在其中),
|
|
205
|
+
// 与 `budget.limit`(= 有效窗口 − 输出预留)同面 ⇒ 可直接比。
|
|
206
|
+
// 口径只在这里判**一次**:`judged` 与报文的 `basis` 都从同一个布尔取——旧写法用 `judged === measuredPrompt`
|
|
207
|
+
// 反推来源,可达情形下结论虽对,但那是值相等碰对的,不是分支决定的。
|
|
208
|
+
const hasMeasured = Number.isFinite(measuredPrompt) && measuredPrompt > 0
|
|
209
|
+
// 两个数都不可用 ⇒ 抛,与 `budget` 那条同形。本档文档自己写着「漏传时守卫静默放行(**比不守更贵**)」——
|
|
210
|
+
// 那条纪律适用于 `budget`,就同样适用于被判的那个数:`NaN > limit` 恒为假,守卫会一声不响地全放行。
|
|
211
|
+
if (!hasMeasured && !Number.isFinite(estPrompt)) {
|
|
212
|
+
throw new Error(`assertPromptFits: no usable prompt measurement (measuredPrompt=${measuredPrompt}, estPrompt=${estPrompt}) — a non-finite judge silently passes every request (worse than not guarding)`)
|
|
213
|
+
}
|
|
214
|
+
const judged = hasMeasured ? measuredPrompt : estPrompt
|
|
215
|
+
if (!(judged > budget.limit)) return
|
|
216
|
+
throw contextOverflowError(
|
|
217
|
+
provider, judged, budget,
|
|
218
|
+
"the request was not sent; reduce the conversation (/compact or prune) before retrying",
|
|
219
|
+
hasMeasured ? "measured" : "estimated",
|
|
220
|
+
)
|
|
198
221
|
}
|
|
199
222
|
|
|
200
223
|
/** HTTP 400 越窗报文 ⇒ typed 错误(§6.17);未命中 ⇒ 原样返回入参错误(不发明分类)。 */
|