@thincoder/core 0.11.4 → 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 +33 -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 +22 -41
- 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
package/provider/google.mjs
CHANGED
|
@@ -8,13 +8,16 @@ import { proxyFetch } from "../proxy.mjs"
|
|
|
8
8
|
import { withUserAgent } from "../client-identity.mjs"
|
|
9
9
|
import { requestWithRetry } from "./retry.mjs"
|
|
10
10
|
import { effectiveFetchTimeoutMs, effectiveBodyIdleMs } from "./core.mjs"
|
|
11
|
-
import { abortError, timeoutError } from "../abort-provenance.mjs"
|
|
11
|
+
import { abortError, timeoutError, isUserInterrupt, markInterrupted } from "../abort-provenance.mjs"
|
|
12
12
|
import { terminateBody } from "../stream-destroy.mjs"
|
|
13
|
-
import { requestBudget } from "../config.mjs"
|
|
13
|
+
import { requestBudget, policyBudget } from "../config.mjs"
|
|
14
|
+
import { providerSpec } from "../model-specs.mjs"
|
|
15
|
+
import { googleThinkingOff } from "../think-off.mjs"
|
|
14
16
|
import { DEFAULT_BODY_IDLE_MS } from "../config-defaults.mjs"
|
|
15
17
|
import { assertPromptFits } from "./errors.mjs"
|
|
16
18
|
// 推理回声的可空表示与累加(设计 = `docs/core/design/AGENT-LOOP.md` §5.4)——四条 transport 同一口径。
|
|
17
19
|
import { appendReasoning } from "./reasoning-echo.mjs"
|
|
20
|
+
import { logEvent } from "../log.mjs"
|
|
18
21
|
|
|
19
22
|
/** OpenAI 语义 tool_choice → Gemini FunctionCallingConfig(2026-08-31 能力层)。 */
|
|
20
23
|
function mapFunctionCallingConfig(choice) {
|
|
@@ -26,14 +29,135 @@ function mapFunctionCallingConfig(choice) {
|
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
|
|
29
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* Gemini v1beta `Schema` 已实测可接受的字段集(白名单;未列出的键一律不发——它们在那份 proto 里没有位置)。
|
|
34
|
+
* 2026-12-01 对 gemini-4-neon 逐项实测(同一 key):
|
|
35
|
+
* 纯文本请求 200,工具声明里带下列任一被剥离的键即 400 INVALID_ARGUMENT「Unknown name … Cannot find field」
|
|
36
|
+
* (实测被拒:$schema ∥ $id ∥ $comment ∥ $ref ∥ additionalProperties ∥ propertyNames ∥ patternProperties ∥
|
|
37
|
+
* definitions ∥ $defs ∥ dependencies ∥ const ∥ examples ∥ readOnly ∥ writeOnly ∥ deprecated ∥
|
|
38
|
+
* exclusiveMinimum ∥ exclusiveMaximum ∥ multipleOf ∥ contains ∥ prefixItems ∥ unevaluatedProperties ∥
|
|
39
|
+
* if ∥ then ∥ else ∥ uniqueItems)。工具声明来自本机工具与外部 MCP 服务器,形态不受本仓控制,
|
|
40
|
+
* 所以投影发生在发送面而不是各工具定义处。
|
|
41
|
+
*/
|
|
42
|
+
const GEMINI_SCHEMA_KEYS = new Set([
|
|
43
|
+
"type", "format", "title", "description", "nullable", "default", "enum", "example",
|
|
44
|
+
"pattern", "minimum", "maximum", "minLength", "maxLength", "propertyOrdering",
|
|
45
|
+
"properties", "required", "items", "minItems", "maxItems", "anyOf", "oneOf", "allOf", "not",
|
|
46
|
+
])
|
|
47
|
+
/** `Schema.type` 的合法枚举(实测:数组形与 `"string|null"` 简写均 400——proto 字段非 repeating)。 */
|
|
48
|
+
const GEMINI_SCHEMA_TYPES = new Set(["object", "array", "string", "number", "integer", "boolean", "null"])
|
|
49
|
+
/** 递归上限:`$ref` 环 ∥ 病态深 schema 的兜底(越过即降级空 schema,请求照发)。 */
|
|
50
|
+
const MAX_SCHEMA_DEPTH = 24
|
|
51
|
+
/** 节点预算(一次投影整体计数):`$ref` 组成的**无环** DAG 在一个深度上限内也能展开成指数级节点——
|
|
52
|
+
* 深度墙拦不住它,而展开跑在请求装配路径上。耗尽即降级空 schema(形态降级、请求照发)。 */
|
|
53
|
+
const MAX_SCHEMA_NODES = 2000
|
|
54
|
+
/** 标量键的值型(实测:`format: 5` ∥ `description: 5` ∥ `pattern: {}` → 400 TYPE_STRING)。 */
|
|
55
|
+
const SCHEMA_STRING_KEYS = new Set(["format", "title", "description", "pattern"])
|
|
56
|
+
/** 整数键的值型(实测:`maxLength: true` → 400 TYPE_INT64)。 */
|
|
57
|
+
const SCHEMA_NUMBER_KEYS = new Set(["minimum", "maximum", "minLength", "maxLength", "minItems", "maxItems"])
|
|
58
|
+
|
|
59
|
+
function isSchemaObject(v) {
|
|
60
|
+
return v !== null && typeof v === "object" && !Array.isArray(v)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 放宽形 `type`(数组 ∥ `"a|null"`)→ 单个枚举值 + nullable 标记;归不出唯一值 ⇒ 不落 `type`。 */
|
|
64
|
+
function normalizeSchemaType(raw) {
|
|
65
|
+
const names = Array.isArray(raw) ? raw.filter((t) => typeof t === "string") : typeof raw === "string" ? [raw] : []
|
|
66
|
+
const concrete = names.filter((t) => GEMINI_SCHEMA_TYPES.has(t) && t !== "null")
|
|
67
|
+
return { type: concrete.length === 1 ? concrete[0] : undefined, nullable: names.includes("null") }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 本地 JSON Pointer(`#/definitions/<k>` ∥ `#/$defs/<k>`);远程 ∥ 外部引用一律不解析。 */
|
|
71
|
+
function localSchemaRef(ref, root) {
|
|
72
|
+
if (typeof ref !== "string" || !ref.startsWith("#/")) return null
|
|
73
|
+
let node = root
|
|
74
|
+
for (const raw of ref.slice(2).split("/")) {
|
|
75
|
+
const key = raw.replace(/~1/g, "/").replace(/~0/g, "~")
|
|
76
|
+
if (!isSchemaObject(node)) return null
|
|
77
|
+
node = node[key]
|
|
78
|
+
if (node === undefined) return null
|
|
79
|
+
}
|
|
80
|
+
return isSchemaObject(node) ? node : null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* JSON Schema → Gemini `Schema` 的白名单投影(生产面唯一调用方 = `normalizeTools`;导出是给直取的单测用)。
|
|
85
|
+
* 降级原则:形态不认识就删该键或折成空 schema,不抛错——工具仍可调用,整轮不因声明形态 400。
|
|
86
|
+
* 只作用于这一次请求的 `parameters` 副本:工具定义与历史零改动。
|
|
87
|
+
*/
|
|
88
|
+
export function sanitizeSchema(node, root = node, depth = 0, refChain = new Set(), budget = { left: MAX_SCHEMA_NODES }) {
|
|
89
|
+
if (depth >= MAX_SCHEMA_DEPTH || budget.left <= 0) return {}
|
|
90
|
+
budget.left--
|
|
91
|
+
// 布尔 schema(`true` / `false`)在 proto 里无对应表达(实测 400)⇒ 折成「任意」= `{}`
|
|
92
|
+
if (!isSchemaObject(node)) return {}
|
|
93
|
+
if (typeof node.$ref === "string") {
|
|
94
|
+
const target = localSchemaRef(node.$ref, root)
|
|
95
|
+
if (!target || refChain.has(node.$ref)) return {} // 解析不到 ∥ 递归定义 ⇒ 降级
|
|
96
|
+
const resolved = sanitizeSchema(target, root, depth + 1, new Set(refChain).add(node.$ref), budget)
|
|
97
|
+
// `$ref` 的兄弟键(`description` ∥ `default` ∥ `nullable` …)在 2020-12 里有意义,
|
|
98
|
+
// 而 proto 里 `$ref` 本身不能发——兄弟键按同一投影并回,同键以兄弟为准。
|
|
99
|
+
const { $ref: _dropped, ...siblings } = node
|
|
100
|
+
if (Object.keys(siblings).length === 0) return resolved
|
|
101
|
+
const merged = { ...resolved, ...sanitizeSchema(siblings, root, depth + 1, refChain, budget) }
|
|
102
|
+
// 兄弟支自己没有 `properties`,它带到合并步的 `required` 在那边已被跳过——合并后统一裁一次。
|
|
103
|
+
if (merged.properties && Array.isArray(node.required)) {
|
|
104
|
+
const names = node.required.filter((v) => typeof v === "string" && Object.hasOwn(merged.properties, v))
|
|
105
|
+
if (names.length) merged.required = names
|
|
106
|
+
else delete merged.required
|
|
107
|
+
}
|
|
108
|
+
return merged
|
|
109
|
+
}
|
|
110
|
+
const out = {}
|
|
111
|
+
const { type, nullable } = normalizeSchemaType(node.type)
|
|
112
|
+
if (type) out.type = type
|
|
113
|
+
if (nullable || node.nullable === true) out.nullable = true
|
|
114
|
+
for (const key of GEMINI_SCHEMA_KEYS) {
|
|
115
|
+
if (key === "type" || key === "nullable" || key === "required" || !(key in node)) continue
|
|
116
|
+
const value = node[key]
|
|
117
|
+
if (key === "properties") {
|
|
118
|
+
if (!isSchemaObject(value)) continue
|
|
119
|
+
out.properties = {}
|
|
120
|
+
for (const [name, sub] of Object.entries(value)) out.properties[name] = sanitizeSchema(sub, root, depth + 1, refChain, budget)
|
|
121
|
+
} else if (key === "items") {
|
|
122
|
+
out.items = sanitizeSchema(Array.isArray(value) ? value[0] : value, root, depth + 1, refChain, budget)
|
|
123
|
+
} else if (key === "anyOf" || key === "oneOf" || key === "allOf") {
|
|
124
|
+
if (!Array.isArray(value)) continue
|
|
125
|
+
out[key] = value.map((sub) => sanitizeSchema(sub, root, depth + 1, refChain, budget))
|
|
126
|
+
} else if (key === "not") {
|
|
127
|
+
out.not = sanitizeSchema(value, root, depth + 1, refChain, budget)
|
|
128
|
+
} else if (key === "enum") {
|
|
129
|
+
// proto 侧是 `repeated string`(实测:数字枚举 ∥ 混合枚举 → 400 TYPE_STRING)⇒
|
|
130
|
+
// 只发全字符串枚举;含非字符串就整键丢弃(不把数字改写成字符串——那会换掉工具参数的值型)。
|
|
131
|
+
if (Array.isArray(value) && value.every((v) => typeof v === "string")) out.enum = value
|
|
132
|
+
} else if (SCHEMA_STRING_KEYS.has(key)) {
|
|
133
|
+
// 值型也得守(实测:`format: 5` ∥ `description: 5` ∥ `pattern: {}` 均 400)
|
|
134
|
+
if (typeof value === "string") out[key] = value
|
|
135
|
+
} else if (SCHEMA_NUMBER_KEYS.has(key)) {
|
|
136
|
+
// 实测:`maxLength: true` 400(TYPE_INT64)
|
|
137
|
+
if (Number.isFinite(value)) out[key] = value
|
|
138
|
+
} else if (key === "propertyOrdering") {
|
|
139
|
+
if (Array.isArray(value) && value.every((v) => typeof v === "string")) out[key] = value
|
|
140
|
+
} else if (key === "default" || key === "example") {
|
|
141
|
+
out[key] = value // 任意 JSON(实测对象亦可)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// `required` 只能点名留在 `properties` 里的键($ref 解析后属性表可能已被重塑)。放在循环之后:
|
|
145
|
+
// 不依赖白名单字面量的迭代次序——按字母序整理白名单时这一支不能静默失效。
|
|
146
|
+
if (out.properties && Array.isArray(node.required)) {
|
|
147
|
+
const names = node.required.filter((v) => typeof v === "string" && Object.hasOwn(out.properties, v))
|
|
148
|
+
if (names.length) out.required = names
|
|
149
|
+
}
|
|
150
|
+
return out
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Convert OpenAI-format tools to Gemini format(`parameters` 过发送面投影——见 `sanitizeSchema`) */
|
|
30
154
|
export function normalizeTools(tools) {
|
|
31
155
|
if (!tools?.length) return null
|
|
32
156
|
return [{
|
|
33
157
|
functionDeclarations: tools.map((t) => ({
|
|
34
158
|
name: t.function.name,
|
|
35
159
|
description: t.function.description || "",
|
|
36
|
-
parameters: t.function.parameters || { type: "object", properties: {} },
|
|
160
|
+
parameters: sanitizeSchema(t.function.parameters || { type: "object", properties: {} }),
|
|
37
161
|
})),
|
|
38
162
|
}]
|
|
39
163
|
}
|
|
@@ -42,9 +166,29 @@ export function normalizeTools(tools) {
|
|
|
42
166
|
* Convert OpenAI-format messages to Gemini contents array.
|
|
43
167
|
* Gemini: [{ role: "user"|"model", parts: [{ text } | { functionCall } | { functionResponse }] }]
|
|
44
168
|
* system → systemInstruction (top-level in request body)
|
|
169
|
+
*
|
|
170
|
+
* 思考签名(`PROVIDER.md` §6.24):Gemini 3 起**当前回合内每一步的首个 `functionCall`**必须带
|
|
171
|
+
* `thoughtSignature`,缺则 400 `Function call … is missing a thought_signature`。签名只存在于
|
|
172
|
+
* Gemini 产出的轮里:换 provider 续跑、会话被截断压缩、或历史由别的模型写成时,手里没有真签名。
|
|
173
|
+
* 这种缺口用官方哨兵 `skip_thought_signature_validator` 补上(文档原文:there is no other way to
|
|
174
|
+
* skip validation——它不伪造推理,只是让请求合法);同一 message 内的后续并行调用保持不带字段
|
|
175
|
+
* (官方示例同形:并行调用只有首个 part 带签名)。
|
|
45
176
|
*/
|
|
177
|
+
export const SKIP_THOUGHT_SIGNATURE = "skip_thought_signature_validator"
|
|
178
|
+
|
|
46
179
|
export function convertMessages(messages) {
|
|
47
180
|
const contents = []
|
|
181
|
+
// tool 结果名解析表:assistant 声明过的 `tool_call.id → 工具名`。旧会话与异 provider 历史的
|
|
182
|
+
// `tool` 消息常缺 `name`,id 也不是 `<name>_<N>` 约定形——声明面才是权威。
|
|
183
|
+
const declaredNames = new Map()
|
|
184
|
+
for (const m of messages) {
|
|
185
|
+
if (m.role !== "assistant") continue
|
|
186
|
+
for (const call of m.tool_calls ?? []) {
|
|
187
|
+
const id = call?.id ?? call?.tool_call_id
|
|
188
|
+
const name = call?.function?.name ?? call?.name
|
|
189
|
+
if (typeof id === "string" && id && typeof name === "string" && name) declaredNames.set(id, name)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
48
192
|
for (const m of messages) {
|
|
49
193
|
// system messages are hoisted to systemInstruction by the caller — check the
|
|
50
194
|
// ORIGINAL role (the remapped role below can never be "system")
|
|
@@ -67,6 +211,7 @@ export function convertMessages(messages) {
|
|
|
67
211
|
}
|
|
68
212
|
}
|
|
69
213
|
if (m.role === "assistant") {
|
|
214
|
+
let firstCall = true
|
|
70
215
|
for (const call of m.tool_calls ?? []) {
|
|
71
216
|
let args = {}
|
|
72
217
|
const rawArguments = call.function?.arguments ?? call.arguments
|
|
@@ -74,13 +219,21 @@ export function convertMessages(messages) {
|
|
|
74
219
|
const part = { functionCall: { name: call.function?.name ?? call.name, args } }
|
|
75
220
|
const thoughtSignature = call.extra_content?.google?.thought_signature
|
|
76
221
|
if (typeof thoughtSignature === "string" && thoughtSignature) part.thoughtSignature = thoughtSignature
|
|
222
|
+
else if (firstCall) part.thoughtSignature = SKIP_THOUGHT_SIGNATURE // 本步首个调用缺签名 ⇒ 官方哨兵;后续并行调用保持不带
|
|
223
|
+
firstCall = false
|
|
77
224
|
parts.push(part)
|
|
78
225
|
}
|
|
79
226
|
}
|
|
80
227
|
if (m.role === "tool") {
|
|
81
228
|
const callId = String(m.tool_call_id ?? "")
|
|
82
|
-
const name = m.name || (/_
|
|
83
|
-
if (!name)
|
|
229
|
+
const name = m.name || declaredNames.get(callId) || (/_[0-9]+$/.test(callId) ? callId.replace(/_[0-9]+$/, "") : "")
|
|
230
|
+
if (!name) {
|
|
231
|
+
// 名字三面(消息 `name` ∥ 声明面 id 表 ∥ `<name>_<N>` 约定)都取不到 = 该结果在 Gemini 协议里
|
|
232
|
+
// 无法表达(`functionResponse.name` 是必填字段)。丢掉一条结果 vs 整轮 400 失败:选前者并留痕——
|
|
233
|
+
// 现场读数(2026-12-01 gemini-4-neon)是后者把整个会话卡死在重试提示上。
|
|
234
|
+
logEvent("google:unmatched-tool-result", { toolCallId: callId })
|
|
235
|
+
continue
|
|
236
|
+
}
|
|
84
237
|
parts.push({ functionResponse: { name, response: { result: String(m.content ?? "") } } })
|
|
85
238
|
}
|
|
86
239
|
if (parts.length === 0) continue
|
|
@@ -96,23 +249,60 @@ export function convertMessages(messages) {
|
|
|
96
249
|
return contents
|
|
97
250
|
}
|
|
98
251
|
|
|
252
|
+
/**
|
|
253
|
+
* 内置工具声明:`providers[].grounding === true` 的 Google 渠道每轮带上 `google_search`。
|
|
254
|
+
* 官方实测(2026-12-01,gemini-4-neon):它与 `functionDeclarations` 并存时 **必须**同时发
|
|
255
|
+
* `toolConfig.includeServerSideToolInvocations: true`,否则 400「Please enable tool_config.
|
|
256
|
+
* include_server_side_tool_invocations to use Built-in tools with Function calling」。
|
|
257
|
+
* 只在渠道为 Google 格式时生效——其它格式的服务端没有这个工具。
|
|
258
|
+
*/
|
|
259
|
+
export const GOOGLE_SEARCH_TOOL = { google_search: {} }
|
|
260
|
+
|
|
261
|
+
/** 请求的 `tools` 数组:工具声明 + (接地开启时)内置搜索工具。全空 ⇒ null(字段不落)。
|
|
262
|
+
* 单源给 `chat` 与单测用——`chat` 里不再另拼一遍列表。 */
|
|
263
|
+
export function buildToolList(tools, grounding) {
|
|
264
|
+
const list = [...(tools ?? [])]
|
|
265
|
+
if (grounding === true) list.push(GOOGLE_SEARCH_TOOL)
|
|
266
|
+
return list.length ? list : null
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** 请求的 `toolConfig`:`tool_choice` 与接地的两个必然项合成一个对象。
|
|
270
|
+
* - 只给 `toolChoice` ⇒ 仅 `functionCallingConfig`(原行为零变);
|
|
271
|
+
* - 只开接地 ⇒ 仅 `includeServerSideToolInvocations`(实测:与 functionDeclarations 同发时不带它即 400);
|
|
272
|
+
* - 两样都无 ⇒ null(字段不落)。 */
|
|
273
|
+
export function buildToolConfig(toolChoice, grounding) {
|
|
274
|
+
const withChoice = toolChoice !== undefined
|
|
275
|
+
const withGrounding = grounding === true
|
|
276
|
+
if (!withChoice && !withGrounding) return null
|
|
277
|
+
return {
|
|
278
|
+
...(withChoice ? { functionCallingConfig: mapFunctionCallingConfig(toolChoice) } : {}),
|
|
279
|
+
...(withGrounding ? { includeServerSideToolInvocations: true } : {}),
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
99
283
|
/** Build and send a Gemini chat request. Returns the same shape as core.mjs chat.
|
|
100
284
|
* 2026-08-31 会诊 #6:接入 rateGate/recordRate(原实现完全绕过 TPM/RPM 闸门)。 */
|
|
101
|
-
export async function chat(provider, { messages, tools, onToken, onReasoning, onWait, signal, toolChoice, logCtx }) {
|
|
285
|
+
export async function chat(provider, { messages, tools, onToken, onReasoning, onWait, signal, toolChoice, logCtx, measuredPrompt, reserveTokens, modelParams, settings }) {
|
|
102
286
|
const systemMessages = messages.filter((m) => m.role === "system")
|
|
103
287
|
const contents = convertMessages(messages)
|
|
104
288
|
// §2.2 发送面:只读 maxTokens(输出合同)——请求体与发送前净判共用这一个对象,不各算一套。
|
|
105
|
-
const budget = requestBudget(provider)
|
|
289
|
+
const budget = requestBudget(provider, undefined, reserveTokens, settings)
|
|
290
|
+
|
|
291
|
+
// off 形只在调用方**显式要求关思考**时发(`thinking.type === "disabled"`);形态与「该族到底有没有
|
|
292
|
+
// 有效 off 路径」一律引核单源(`googleThinkingOff` / `specForModel` 系——本档零副本,`MODEL-SPECS.md` §4)。
|
|
293
|
+
const offCfg = modelParams?.thinking?.type === "disabled" ? googleThinkingOff(providerSpec(provider, settings)) : null
|
|
106
294
|
|
|
107
295
|
const body = {
|
|
108
296
|
contents,
|
|
109
297
|
generationConfig: {
|
|
110
|
-
...(
|
|
111
|
-
// §
|
|
298
|
+
...(modelParams?.temperature != null ? { temperature: modelParams?.temperature } : {}),
|
|
299
|
+
// §2.2 发送面同源:maxTokens = reserve(**恒有值**——输出预留三档都发它;用户侧已无渠道级覆盖可设)
|
|
112
300
|
...(budget.maxTokens !== undefined ? { maxOutputTokens: budget.maxTokens } : {}),
|
|
113
|
-
//
|
|
114
|
-
//
|
|
115
|
-
|
|
301
|
+
// off 形:只有规格**未**声明 `thinkAlwaysOn === true` 的族才发,且发上游合法形 `thinkingBudget: 0`。
|
|
302
|
+
// 2026-12-01 真实上游实测:`thinkingLevel:"none"` ⇒ 400 INVALID_ARGUMENT(枚举无 none,全部受测模型同判);
|
|
303
|
+
// `"minimal"` ⇒ 400 该模型不支持;`low`/`high` 合法;`thinkingBudget:0` ⇒ 200 但**不关闭**(仍花 thought token,
|
|
304
|
+
// 开 includeThoughts 还回思考正文)⇒ 服务端强制族零发:关闭是 no-op,与 `thinkOffPath` 不给 UI 假 off 同源。
|
|
305
|
+
...(offCfg ? { thinkingConfig: offCfg } : {}),
|
|
116
306
|
},
|
|
117
307
|
safetySettings: [
|
|
118
308
|
{ category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE" },
|
|
@@ -126,11 +316,14 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
126
316
|
parts: [{ text: systemMessages.map((m) => m.content).join("\n\n") }],
|
|
127
317
|
}
|
|
128
318
|
}
|
|
129
|
-
|
|
319
|
+
// 接地(`providers[].grounding`)与工具声明同发时需要 `includeServerSideToolInvocations`
|
|
320
|
+
// (见 GOOGLE_SEARCH_TOOL 注释里的实测报错);两段合成全走导出的纯函数。
|
|
321
|
+
const grounding = provider.grounding === true
|
|
322
|
+
const toolList = buildToolList(tools, grounding)
|
|
323
|
+
if (toolList) body.tools = toolList
|
|
130
324
|
// 2026-08-31:tool_choice 能力层 → Gemini toolConfig.functionCallingConfig
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
}
|
|
325
|
+
const toolConfig = buildToolConfig(toolChoice, grounding)
|
|
326
|
+
if (toolConfig) body.toolConfig = toolConfig
|
|
134
327
|
|
|
135
328
|
// Gemini uses API key as query parameter
|
|
136
329
|
const url = `${provider.baseURL}/models/${provider.model}:streamGenerateContent?alt=sse&key=${encodeURIComponent(provider.apiKey)}`
|
|
@@ -142,7 +335,8 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
142
335
|
// §6.17 发送面净判:估准面补 `tools`(原只投影 messages);body 用 `maxOutputTokens`、无 `max_tokens` 键 ⇒ 减项恒 0
|
|
143
336
|
const estimated = estimateRequestTokens({ messages, tools })
|
|
144
337
|
const estPrompt = estimated - (body.max_tokens ?? 0)
|
|
145
|
-
|
|
338
|
+
// 预算面 = 体那一处已算好的同一个对象(§2.2);判据优先取整量实测(§2.5)——不另算第二份。
|
|
339
|
+
assertPromptFits(provider, estPrompt, logCtx, budget, measuredPrompt)
|
|
146
340
|
await rateGate(provider, estimated, onWait, signal)
|
|
147
341
|
|
|
148
342
|
// 2026-08-31:5xx/网络与 OpenAI 格式统一退避重试链(原完全无重试——Gemini 高峰
|
|
@@ -163,23 +357,19 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
163
357
|
const result = await parseGeminiStream(response, { onToken, onReasoning, signal, idleMs: effectiveBodyIdleMs(provider), firstChunkMs: effectiveFetchTimeoutMs(provider) })
|
|
164
358
|
recordRate(provider, estimated, result.usage)
|
|
165
359
|
|
|
360
|
+
// 返回面保留 transport 标记(`partial` ∥ `networkError` ∥ `interrupted`):原实现用字面量重建,
|
|
361
|
+
// 把这些标记静默吞掉——idle ∥ 网络断流且已有内容的轮会被当成完整响应(2026-12-01 评审 #3)。
|
|
362
|
+
const out = { ...result, finishReason: result.finishReason ?? null, estimated: estPrompt }
|
|
166
363
|
const usage = result.usage
|
|
167
364
|
if (usage) {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
usage: {
|
|
174
|
-
prompt_tokens: usage.prompt_tokens ?? 0,
|
|
175
|
-
completion_tokens: usage.completion_tokens ?? 0,
|
|
176
|
-
total_tokens: usage.total_tokens ?? 0,
|
|
177
|
-
},
|
|
178
|
-
toolCalls: result.toolCalls,
|
|
365
|
+
// §6.31.7 F-DA5:usage 归一为核统一三字段(与另三条 transport 同形)。
|
|
366
|
+
out.usage = {
|
|
367
|
+
prompt_tokens: usage.prompt_tokens ?? 0,
|
|
368
|
+
completion_tokens: usage.completion_tokens ?? 0,
|
|
369
|
+
total_tokens: usage.total_tokens ?? 0,
|
|
179
370
|
}
|
|
180
371
|
}
|
|
181
|
-
|
|
182
|
-
return { content: result.content, reasoning: result.reasoning, finishReason: result.finishReason ?? null, estimated: estPrompt, toolCalls: result.toolCalls }
|
|
372
|
+
return out
|
|
183
373
|
}
|
|
184
374
|
|
|
185
375
|
/** Gemini `finishReason` ⇒ 核统一 `finishReason`(§6.31.7 F-DA5——归一只喂既有分类;
|
|
@@ -195,7 +385,7 @@ function mapGeminiFinishReason(reason) {
|
|
|
195
385
|
* Format: data: {...}\n\n (each line is a complete JSON object)
|
|
196
386
|
*/
|
|
197
387
|
export async function parseGeminiStream(response, { onToken, onReasoning, signal, idleMs = DEFAULT_BODY_IDLE_MS, firstChunkMs }) {
|
|
198
|
-
const result = { content: "", reasoning: null, toolCalls: [], usage: null, finishReason: null }
|
|
388
|
+
const result = { content: "", reasoning: null, toolCalls: [], usage: null, finishReason: null, grounding: null }
|
|
199
389
|
const decoder = new TextDecoder()
|
|
200
390
|
let buffer = ""
|
|
201
391
|
|
|
@@ -214,6 +404,27 @@ export async function parseGeminiStream(response, { onToken, onReasoning, signal
|
|
|
214
404
|
|
|
215
405
|
const candidate = json.candidates?.[0]
|
|
216
406
|
if (!candidate) return
|
|
407
|
+
// 接地来源(`providers[].grounding`):`groundingMetadata` 按流分块到达,按 URL 去重累积。
|
|
408
|
+
// 三段各有用处:`webSearchQueries` = 模型实际发出去的查询(计费按条数),`groundingChunks[].web` =
|
|
409
|
+
// 来源(uri + title),`groundingSupports` = 哪段话由哪几条来源支持(segment 位置在本轮 text 里)。
|
|
410
|
+
if (candidate.groundingMetadata) {
|
|
411
|
+
const gm = candidate.groundingMetadata
|
|
412
|
+
result.grounding ??= { queries: [], sources: [], supports: [] }
|
|
413
|
+
for (const q of gm.webSearchQueries ?? []) {
|
|
414
|
+
if (typeof q === "string" && q && !result.grounding.queries.includes(q)) result.grounding.queries.push(q)
|
|
415
|
+
}
|
|
416
|
+
for (const chunk of gm.groundingChunks ?? []) {
|
|
417
|
+
const web = chunk?.web
|
|
418
|
+
if (!web?.uri) continue
|
|
419
|
+
if (result.grounding.sources.some((s) => s.uri === web.uri)) continue
|
|
420
|
+
result.grounding.sources.push({ uri: web.uri, title: typeof web.title === "string" ? web.title : "" })
|
|
421
|
+
}
|
|
422
|
+
for (const sup of gm.groundingSupports ?? []) {
|
|
423
|
+
const seg = sup?.segment
|
|
424
|
+
if (typeof seg?.text !== "string") continue
|
|
425
|
+
result.grounding.supports.push({ text: seg.text, startIndex: seg.startIndex ?? null, endIndex: seg.endIndex ?? null, chunkIndices: sup.groundingChunkIndices ?? [] })
|
|
426
|
+
}
|
|
427
|
+
}
|
|
217
428
|
// §6.31.7 F-DA5(#929 · 批 digest-accounting):`candidate.finishReason` 捕获——缺席 ⇒ 留 null(窄口)
|
|
218
429
|
if (candidate.finishReason) result.finishReason = mapGeminiFinishReason(candidate.finishReason)
|
|
219
430
|
|
|
@@ -292,11 +503,7 @@ export async function parseGeminiStream(response, { onToken, onReasoning, signal
|
|
|
292
503
|
}
|
|
293
504
|
} catch (e) {
|
|
294
505
|
if (idleTimer) clearTimeout(idleTimer)
|
|
295
|
-
if (
|
|
296
|
-
result.interrupted = true
|
|
297
|
-
result.interruptMessage = signal.reason.message
|
|
298
|
-
return result
|
|
299
|
-
}
|
|
506
|
+
if (isUserInterrupt(signal)) return markInterrupted(result, signal)
|
|
300
507
|
// #878:看门狗终结两径归一(idleFired)——无内容 ⇒ idle 超时错误;有内容 ⇒ partial
|
|
301
508
|
//(已流出内容保留,不整轮报废)。非 idle 错误照旧走下方 hasPartial 径(原语义零变)。
|
|
302
509
|
if (idleError) {
|
package/provider/list-models.mjs
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
* URL 组合 = `{baseURL}` + 相对路径,与 chat 各 transport 同构——baseURL 自带版本段
|
|
11
11
|
* (claude 预设 `…/v1` → `…/v1/models`;gemini 预设 `…/v1beta` → `…/v1beta/models`)。
|
|
12
12
|
* 超时制度沿用原实现(整体 15s + header 15s + body idle 15s;翻页时逐页各自计时;调用方可传
|
|
13
|
-
* `signal` 短路)。HTTP 非 2xx /
|
|
14
|
-
*
|
|
13
|
+
* `signal` 短路)。HTTP 非 2xx / 网络失败 / **载荷形状读不出**一律**抛出**(需求 §2:明确报错,不返回伪空清单)。
|
|
14
|
+
* 解析保持防御性(数组内字段缺失即跳过该项;形状读不出是另一回事,判在 `requireRows`)。候选不过滤非对话模型(embedding 等——§16.6 #14)。
|
|
15
15
|
*/
|
|
16
16
|
import { proxyFetch } from "../proxy.mjs"
|
|
17
17
|
import { withUserAgent } from "../client-identity.mjs"
|
|
@@ -19,12 +19,14 @@ import { resolveProviderSecrets } from "../env-ref.mjs"
|
|
|
19
19
|
import { positiveInt, recordListedContext } from "../model-context.mjs"
|
|
20
20
|
|
|
21
21
|
const LIST_TIMEOUT_MS = 15_000
|
|
22
|
-
/** 翻页上限(cursor loop 防死循环——任一分页失败即整体抛出,不部分返回)。
|
|
22
|
+
/** 翻页上限(cursor loop 防死循环——任一分页失败即整体抛出,不部分返回)。
|
|
23
|
+
* 打到上限而 `has_more` / `nextPageToken` 仍真时,**归 ``return out`` 返回已收集**(截断,不报错)——两件事分开判。 */
|
|
23
24
|
const MAX_PAGES = 10
|
|
24
25
|
const ANTHROPIC_VERSION = "2023-06-01"
|
|
25
26
|
|
|
26
27
|
/** 单页 GET + JSON 解析(非 2xx → throw;非 JSON 响应 → throw——§2.5 #115 并入 VSC 明确报错)。
|
|
27
|
-
* 载荷读取失败(断流 ∥ idle 超时 ∥ 网络)⇒ 原错误直抛(#1068——不吞根因;`non-JSON` 文案只给真非 JSON)。
|
|
28
|
+
* 载荷读取失败(断流 ∥ idle 超时 ∥ 网络)⇒ 原错误直抛(#1068——不吞根因;`non-JSON` 文案只给真非 JSON)。
|
|
29
|
+
* **载荷形状**(`data[]` / `models[]` 是否数组)判在调用方 `requireRows`,不在本函数:这里是「拿到了什么字节」。 */
|
|
28
30
|
async function fetchJson(provider, url, headers, signal) {
|
|
29
31
|
const opts = {
|
|
30
32
|
headers,
|
|
@@ -48,9 +50,17 @@ async function fetchJson(provider, url, headers, signal) {
|
|
|
48
50
|
}
|
|
49
51
|
}
|
|
50
52
|
|
|
51
|
-
/**
|
|
53
|
+
/** 载荷形状门(需求 §2 逐字:「list-models 网络/HTTP/解析失败明确报错,不返回伪空清单」):
|
|
54
|
+
* 形状读得出来(数组)才收集;读不出 ⇒ **明确抛出**,绝不降级成零模型清单。
|
|
55
|
+
* 「渠道如实报零个模型」(数组、空)是合法事实,与「载荷读不出」是两件事,不得同判。
|
|
56
|
+
* 抛出的错误走既有失败面:`channelUnavailableMessage` 出「该渠道不提供模型列表」,`classifyProbeFailure` 落 `malformed`。 */
|
|
57
|
+
function requireRows(rows, shape) {
|
|
58
|
+
if (!Array.isArray(rows)) throw new Error(`unexpected payload shape (${shape})`)
|
|
59
|
+
return rows
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 防御性收集(射程 = 数组内部):字段缺失/非字符串项跳过。**形状**不在这里判,那是 `requireRows` 的门。 */
|
|
52
63
|
function collect(rows, pick) {
|
|
53
|
-
if (!Array.isArray(rows)) return []
|
|
54
64
|
const out = []
|
|
55
65
|
for (const row of rows) {
|
|
56
66
|
const v = pick(row)
|
|
@@ -91,14 +101,15 @@ function listedOutputOf(row) {
|
|
|
91
101
|
async function listOpenai(provider, signal) {
|
|
92
102
|
const url = `${provider.baseURL}/models`
|
|
93
103
|
const data = await fetchJson(provider, url, { ...withUserAgent(provider.headers), Authorization: `Bearer ${provider.apiKey ?? ""}` }, signal)
|
|
104
|
+
// 形状门(需求 §2 逐字):`data[]` 读得出来才建表;读不出 ⇒ 明确抛出
|
|
105
|
+
//(不返回伪空清单,也不静默清空上次成功值)。
|
|
106
|
+
const rows = requireRows(data?.data, "data[]")
|
|
94
107
|
// L3 写面的收集段(PROVIDER.md §6.15):解析 `data[]` 时顺带收 `id → 窗口`——三字段按序取
|
|
95
108
|
// 第一个**合法**值(R25 ∥ R26),非法相当于该字段缺席;三字段都不可得 = 该模型列表未报(不进表)。
|
|
96
109
|
const ids = []
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const outputs = Array.isArray(data?.data) ? new Map() : null
|
|
101
|
-
for (const m of Array.isArray(data?.data) ? data.data : []) {
|
|
110
|
+
const windows = new Map()
|
|
111
|
+
const outputs = new Map()
|
|
112
|
+
for (const m of rows) {
|
|
102
113
|
const id = m?.id
|
|
103
114
|
if (typeof id !== "string" || !id) continue
|
|
104
115
|
ids.push(id)
|
|
@@ -118,7 +129,8 @@ async function listAnthropic(provider, signal) {
|
|
|
118
129
|
for (let page = 0; page < MAX_PAGES; page++) {
|
|
119
130
|
const url = afterId ? `${base}&after_id=${encodeURIComponent(afterId)}` : base
|
|
120
131
|
const data = await fetchJson(provider, url, headers, signal)
|
|
121
|
-
|
|
132
|
+
// 形状门(每页各判):`data[]` 读不出 ⇒ 明确抛出,不把「读不到」拼成翻页结束。
|
|
133
|
+
out.push(...collect(requireRows(data?.data, "data[]"), (m) => m?.id))
|
|
122
134
|
if (!data?.has_more) return out
|
|
123
135
|
afterId = typeof data?.last_id === "string" && data.last_id ? data.last_id : null
|
|
124
136
|
if (!afterId) return out // has_more 但无游标——无法继续,避免死循环
|
|
@@ -134,7 +146,8 @@ async function listGoogle(provider, signal) {
|
|
|
134
146
|
for (let page = 0; page < MAX_PAGES; page++) {
|
|
135
147
|
const url = pageToken ? `${base}&pageToken=${encodeURIComponent(pageToken)}` : base
|
|
136
148
|
const data = await fetchJson(provider, url, headers, signal)
|
|
137
|
-
|
|
149
|
+
// 形状门(每页各判):`models[]` 读不出 ⇒ 明确抛出。
|
|
150
|
+
out.push(...collect(requireRows(data?.models, "models[]"), (m) => (typeof m?.name === "string" ? m.name.replace(/^models\//, "") : null)))
|
|
138
151
|
if (typeof data?.nextPageToken !== "string" || !data.nextPageToken) return out
|
|
139
152
|
pageToken = data.nextPageToken
|
|
140
153
|
}
|
|
@@ -143,7 +156,8 @@ async function listGoogle(provider, signal) {
|
|
|
143
156
|
|
|
144
157
|
/** List available model IDs from the provider's /models endpoint (format 分派——M1)。
|
|
145
158
|
* 返回形态仍是 `string[]`(六个消费面只吃 id——零改);`openai` 分支在返回前把
|
|
146
|
-
* `id → 自报窗口` 写进核缓存(L3 写面——零新增请求)。
|
|
159
|
+
* `id → 自报窗口` 写进核缓存(L3 写面——零新增请求)。
|
|
160
|
+
* 形状读不出(载荷不是数组)⇒ **明确抛出**(需求 §2 逐字),不返回伪空清单。 */
|
|
147
161
|
export async function listModels(provider, { signal } = {}) {
|
|
148
162
|
// #57(provider-config-family 批):清单拉取入口凭据值位解析(CONFIG.md §6.3)——三 format 分支共享。
|
|
149
163
|
provider = resolveProviderSecrets(provider)
|
|
@@ -153,9 +153,15 @@ export function normalizeUsage(usage) {
|
|
|
153
153
|
|
|
154
154
|
/**
|
|
155
155
|
* 组装请求体 + 链状态机决策。
|
|
156
|
-
*
|
|
156
|
+
* `opts.reserveTokens` = 本次调用的显式输出预留(`chat()` 的参数,不是 provider 字段)——
|
|
157
|
+
* 预算只在本函数算一次,随 `budget` 回传给调用方,体与守卫共用同一个对象(§2.2)。
|
|
158
|
+
* `opts.modelParams` = 本次调用的模型语义参数(`{ temperature, thinking, reasoningEffort }`,`chat()` 的参数,
|
|
159
|
+
* 不是 provider 字段)——模型参数不再是渠道属性(用户裁定「不应该有任何 provider 级别的模型参数」)。
|
|
160
|
+
* `opts.settings` = 整份 config(会话源,读 `modelContext` ∥ `agent.contextCaps`)——2026-12-03 批:窗口声明与档位上限不挂 provider。
|
|
161
|
+
* @returns {{ body, previousResponseId, warnings, newChain: {id,key}|null, budget }}
|
|
157
162
|
*/
|
|
158
163
|
export function buildBody(provider, messages, tools, opts = {}) {
|
|
164
|
+
const { modelParams } = opts
|
|
159
165
|
const { instructions: extracted, items } = toItems(messages)
|
|
160
166
|
const toolsFlat = tools?.length ? toTools(tools) : undefined
|
|
161
167
|
const spec = specForModel(provider.model)
|
|
@@ -186,6 +192,7 @@ export function buildBody(provider, messages, tools, opts = {}) {
|
|
|
186
192
|
warnings.push({ name: "responses-store-retention", message: "链生效需要 store:true——对话将在云端留存 7 天(provider.stateful=false 可退出)" })
|
|
187
193
|
}
|
|
188
194
|
|
|
195
|
+
const budget = requestBudget(provider, undefined, opts.reserveTokens, opts.settings)
|
|
189
196
|
const body = {
|
|
190
197
|
model: provider.model,
|
|
191
198
|
input: items, // 占位:chain 有效时下方替换为增量
|
|
@@ -196,23 +203,22 @@ export function buildBody(provider, messages, tools, opts = {}) {
|
|
|
196
203
|
store: wantStateful && hostStateful && isStoreRequiredHost(provider.baseURL),
|
|
197
204
|
...(extracted ? { instructions: extracted } : {}),
|
|
198
205
|
...(toolsFlat ? { tools: toolsFlat } : {}),
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
...(requestBudget(provider).maxTokens !== undefined ? { max_output_tokens: requestBudget(provider).maxTokens } : {}),
|
|
206
|
+
// §2.2 发送面同源:max_output_tokens = reserve(**恒有值**——输出预留三档都发它;用户侧已无渠道级
|
|
207
|
+
// 历史上「显式才发」(#907-D5)已不成立;这里也只用上面那一个 `budget`(原来调了两次,一次还在条件里)。
|
|
208
|
+
...(budget.maxTokens !== undefined ? { max_output_tokens: budget.maxTokens } : {}),
|
|
203
209
|
}
|
|
204
210
|
// 内置工具声明追加(2026-08-31 用户拍板):web_search 与本地 function 工具共存
|
|
205
211
|
const builtin = builtinToolsFor(provider.baseURL, provider.builtinTools)
|
|
206
212
|
if (builtin.length) body.tools = [...(toolsFlat ?? []), ...builtin]
|
|
207
|
-
if (
|
|
208
|
-
let t =
|
|
213
|
+
if (modelParams?.temperature != null) {
|
|
214
|
+
let t = modelParams?.temperature
|
|
209
215
|
if (spec.tempRange) {
|
|
210
216
|
t = Math.min(spec.tempRange[1], Math.max(spec.tempRange[0], t))
|
|
211
217
|
t = Math.round(t * 100) / 100 // 与 core.mjs 同语义(round3 #7)
|
|
212
218
|
}
|
|
213
219
|
body.temperature = t
|
|
214
220
|
}
|
|
215
|
-
if (
|
|
221
|
+
if (modelParams?.reasoningEffort) body.reasoning = { effort: modelParams?.reasoningEffort }
|
|
216
222
|
if (opts.toolChoice !== undefined) body.tool_choice = opts.toolChoice
|
|
217
223
|
|
|
218
224
|
// 链模式:turn 内增量 = 上一链轮未发送的 function_call_output(工具结果)。
|
|
@@ -236,5 +242,5 @@ export function buildBody(provider, messages, tools, opts = {}) {
|
|
|
236
242
|
? { ...chain, key, outputSent: outputs.length }
|
|
237
243
|
: (wantStateful && (hostStateful || opts.forceStateful) ? { id: null, key, outputSent: outputs.length } : null)
|
|
238
244
|
|
|
239
|
-
return { body, previousResponseId, warnings, newChain }
|
|
245
|
+
return { body, previousResponseId, warnings, newChain, budget }
|
|
240
246
|
}
|
package/provider/responses.mjs
CHANGED
|
@@ -16,12 +16,13 @@ import { proxyFetch } from "../proxy.mjs"
|
|
|
16
16
|
import { withUserAgent } from "../client-identity.mjs"
|
|
17
17
|
import { requestWithRetry } from "./retry.mjs"
|
|
18
18
|
import { rateGate, recordRate, estimateRequestTokens } from "./rate.mjs"
|
|
19
|
+
import { isUserInterrupt, markInterrupted } from "../abort-provenance.mjs"
|
|
19
20
|
// 推理回声的可空表示与累加(设计 = `docs/core/design/AGENT-LOOP.md` §5.4)——四条 transport 同一口径。
|
|
20
21
|
import { appendReasoning } from "./reasoning-echo.mjs"
|
|
21
22
|
import { buildBody, normalizeUsage } from "./responses-request.mjs"
|
|
22
23
|
import { classifyResponsesErrorCode, assertPromptFits } from "./errors.mjs"
|
|
23
24
|
// §2.2 发送面:只读 maxTokens(输出合同)——发送前净判共用同一个预算对象
|
|
24
|
-
import { requestBudget } from "../config.mjs"
|
|
25
|
+
import { requestBudget, policyBudget } from "../config.mjs"
|
|
25
26
|
// 同名 re-export(2026-09-29 structure-split-2 · 台账 #620——缝 = 同名再出口):请求构造面出档 `provider/responses-request.mjs`;
|
|
26
27
|
// `buildBody` / `isStoreRequiredHost` / `builtinToolsFor` 三名既有导出经本档转口——消费者 import 面零改。
|
|
27
28
|
export { buildBody, isStoreRequiredHost, builtinToolsFor } from "./responses-request.mjs"
|
|
@@ -107,9 +108,9 @@ export async function parseStream(response, { onToken, onReasoning, signal }) {
|
|
|
107
108
|
} catch (e) {
|
|
108
109
|
// 用户 Ctrl+I 中断:与 core 同构——提交已生成部分(agent 层 interrupted 分支消费)——
|
|
109
110
|
// 不丢已流出的 token;超时/网络错误仍照常抛(不应伪装成 interrupted)
|
|
110
|
-
if (
|
|
111
|
+
if (isUserInterrupt(signal)) {
|
|
111
112
|
seal(null)
|
|
112
|
-
return { ...result
|
|
113
|
+
return markInterrupted({ ...result }, signal)
|
|
113
114
|
}
|
|
114
115
|
// #907-D9:error 帧双支——有流出(content ∥ toolCalls)⇒ partial 抢救返回;无流出 ⇒ 转抛(上抛为主)。
|
|
115
116
|
if (e?.responsesErrFrame) {
|
|
@@ -228,15 +229,16 @@ function handleEvent(ev, h) {
|
|
|
228
229
|
}
|
|
229
230
|
|
|
230
231
|
/** 主入口:请求 + 链状态推进(与 core.mjs 的 chat 同形返回)。 */
|
|
231
|
-
export async function chat(provider, { messages, tools, onToken, onReasoning, onWait, signal, toolChoice, stateful, logCtx }) {
|
|
232
|
-
const { body: reqBody, previousResponseId, warnings, newChain } = buildBody(provider, messages, tools, { toolChoice, stateful })
|
|
232
|
+
export async function chat(provider, { messages, tools, onToken, onReasoning, onWait, signal, toolChoice, stateful, logCtx, measuredPrompt, reserveTokens, modelParams, settings }) {
|
|
233
|
+
const { body: reqBody, previousResponseId, warnings, newChain, budget } = buildBody(provider, messages, tools, { toolChoice, stateful, reserveTokens, modelParams, settings })
|
|
233
234
|
const body = { ...reqBody, ...(previousResponseId ? { previous_response_id: previousResponseId } : {}) }
|
|
234
235
|
|
|
235
236
|
// rateGate/recordRate 对齐 core(responses body 无 messages 键——按本地全量 messages 估算)
|
|
236
237
|
// §6.17 发送面净判:估准面补 `tools`(原只投影 messages);body 用 `max_output_tokens`、无 `max_tokens` 键 ⇒ 减项恒 0
|
|
237
238
|
const estimated = estimateRequestTokens({ messages, tools })
|
|
238
239
|
const estPrompt = estimated - (body.max_tokens ?? 0)
|
|
239
|
-
|
|
240
|
+
// 预算面 = `buildBody` 已算好的同一个对象(§2.2);判据优先取整量实测(§2.5)——不另算第二份。
|
|
241
|
+
assertPromptFits(provider, estPrompt, logCtx, budget, measuredPrompt)
|
|
240
242
|
await rateGate(provider, estimated, onWait, signal)
|
|
241
243
|
// 定制头 + 产品标识头(UA 不可被渠道覆盖——PROVIDER.md §6.17):定制头在前、内置头在后——同名内置头胜出(三处 fetch 共用)
|
|
242
244
|
const headers = { ...withUserAgent(provider.headers), "Content-Type": "application/json", Authorization: `Bearer ${provider.apiKey}` }
|
|
@@ -263,7 +265,7 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
263
265
|
// 不清链会走 buildBody 的增量分支(`responses-request.mjs` 的 `buildBody`):body.input = 裸 function_call_output 且
|
|
264
266
|
// previousResponseId 未随 fullBody 带走 → 服务端 call_id 无归属 → 二次 400(2026-08-31 评审 #1)
|
|
265
267
|
provider._responsesChain = null
|
|
266
|
-
const fresh = buildBody(provider, messages, tools, { toolChoice, stateful, forceStateful: true })
|
|
268
|
+
const fresh = buildBody(provider, messages, tools, { toolChoice, stateful, forceStateful: true, modelParams, settings })
|
|
267
269
|
const fullBody = { ...fresh.body }
|
|
268
270
|
response = await requestWithRetry(
|
|
269
271
|
() => proxyFetch(`${provider.baseURL}/responses`, {
|
|
@@ -282,7 +284,7 @@ export async function chat(provider, { messages, tools, onToken, onReasoning, on
|
|
|
282
284
|
// ——本分支不可达(retry 语义回归时才会走到)。仅作防御:与 catch 分支同处置——
|
|
283
285
|
// 清链后重发 body 仍带旧 previous_response_id(412 注入)是错的——重建全量。
|
|
284
286
|
provider._responsesChain = null
|
|
285
|
-
const fresh2 = buildBody(provider, messages, tools, { toolChoice, stateful, forceStateful: true })
|
|
287
|
+
const fresh2 = buildBody(provider, messages, tools, { toolChoice, stateful, forceStateful: true, modelParams })
|
|
286
288
|
response = await requestWithRetry(
|
|
287
289
|
() => proxyFetch(`${provider.baseURL}/responses`, {
|
|
288
290
|
method: "POST",
|