@armadra/agent 0.17.3 → 0.19.0
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 +50 -0
- package/CHANGELOG.zh-CN.md +50 -0
- package/README.md +4 -0
- package/README.zh-CN.md +4 -0
- package/THIRD_PARTY_NOTICES.md +6 -0
- package/assets/quickjs/LICENSE +57 -0
- package/assets/quickjs/README.md +14 -0
- package/assets/quickjs/quickjs.wasm +0 -0
- package/dist/agent/recovery-reminder.js +6 -1
- package/dist/agent/schema-coerce.d.ts +24 -0
- package/dist/agent/schema-coerce.js +157 -0
- package/dist/agent/schema.d.ts +1 -1
- package/dist/agent/schema.js +1 -1
- package/dist/agent/session-cache.js +12 -0
- package/dist/agent/tool-runner.js +57 -28
- package/dist/agent/types.d.ts +4 -0
- package/dist/ai/apis/anthropic-compat.d.ts +3 -1
- package/dist/ai/apis/anthropic-compat.js +8 -1
- package/dist/ai/apis/anthropic-messages.js +54 -2
- package/dist/ai/apis/anthropic-request.d.ts +3 -0
- package/dist/ai/apis/anthropic-request.js +7 -1
- package/dist/ai/apis/anthropic-threads.d.ts +64 -0
- package/dist/ai/apis/anthropic-threads.js +192 -0
- package/dist/ai/providers/catalog-data.js +5 -5
- package/dist/ai/providers/models-dev-data.js +22 -22
- package/dist/ai/types.d.ts +16 -0
- package/dist/bundle/ama-sandbox.cjs +96 -2
- package/dist/bundle/ama.cjs +29964 -27673
- package/dist/cli/bootstrap.js +32 -6
- package/dist/cli/compose-agents.js +2 -1
- package/dist/cli/compose-extensions-load.d.ts +20 -0
- package/dist/cli/compose-extensions-load.js +38 -0
- package/dist/cli/compose.js +1 -0
- package/dist/cli/deps.d.ts +11 -0
- package/dist/cli/runtime.d.ts +7 -0
- package/dist/cli/subcommands/config.d.ts +3 -0
- package/dist/cli/subcommands/config.js +22 -7
- package/dist/cli/subcommands/doctor.js +34 -0
- package/dist/cli/subcommands/models-discover.js +6 -2
- package/dist/codemode/capability.d.ts +14 -2
- package/dist/codemode/capability.js +19 -2
- package/dist/codemode/host-side.d.ts +14 -0
- package/dist/codemode/host-side.js +81 -10
- package/dist/codemode/inner-calls.d.ts +19 -0
- package/dist/codemode/inner-calls.js +24 -0
- package/dist/codemode/protocol.d.ts +14 -0
- package/dist/codemode/protocol.js +9 -1
- package/dist/codemode/quickjs/host.d.ts +15 -0
- package/dist/codemode/quickjs/host.js +243 -0
- package/dist/codemode/quickjs/wasm.d.ts +21 -0
- package/dist/codemode/quickjs/wasm.js +39 -0
- package/dist/codemode/quickjs/worker.d.ts +55 -0
- package/dist/codemode/quickjs/worker.js +457 -0
- package/dist/codemode/sandbox-entry.d.ts +4 -0
- package/dist/codemode/sandbox-entry.js +95 -3
- package/dist/codemode/script-images.d.ts +18 -0
- package/dist/codemode/script-images.js +38 -0
- package/dist/codemode/script-output.d.ts +19 -0
- package/dist/codemode/script-output.js +67 -0
- package/dist/codemode/search-tools.d.ts +27 -0
- package/dist/codemode/search-tools.js +83 -0
- package/dist/codemode/tool.d.ts +4 -0
- package/dist/codemode/tool.js +60 -9
- package/dist/codemode/worker-pool.d.ts +65 -0
- package/dist/codemode/worker-pool.js +131 -0
- package/dist/config/extension-tree-hash.d.ts +31 -0
- package/dist/config/extension-tree-hash.js +88 -0
- package/dist/config/extension-trust.d.ts +70 -0
- package/dist/config/extension-trust.js +112 -0
- package/dist/config/json-schema.js +3 -1
- package/dist/config/key-docs.js +7 -1
- package/dist/config/profile.d.ts +2 -0
- package/dist/config/profile.js +1 -0
- package/dist/config/schema-trust.d.ts +7 -0
- package/dist/config/schema-trust.js +46 -0
- package/dist/config/schema.d.ts +4 -5
- package/dist/config/schema.js +7 -27
- package/dist/config/settings-registry.js +2 -0
- package/dist/config/trust.d.ts +2 -0
- package/dist/config/trust.js +5 -1
- package/dist/config/types.d.ts +23 -0
- package/dist/config/types.js +1 -0
- package/dist/drivers/host-runners.d.ts +15 -4
- package/dist/drivers/host-runners.js +31 -17
- package/dist/errors.d.ts +1 -1
- package/dist/host/api-impl.d.ts +47 -4
- package/dist/host/api-impl.js +181 -20
- package/dist/host/commands.d.ts +23 -0
- package/dist/host/commands.js +76 -0
- package/dist/host/extensions.d.ts +43 -0
- package/dist/host/extensions.js +117 -0
- package/dist/host/resources.d.ts +2 -0
- package/dist/host/resources.js +5 -0
- package/dist/host/types.d.ts +41 -2
- package/dist/host/types.js +4 -2
- package/dist/i18n/catalog.d.ts +39 -0
- package/dist/i18n/messages/cli.d.ts +24 -0
- package/dist/i18n/messages/cli.js +24 -0
- package/dist/i18n/messages/config-keys.d.ts +4 -0
- package/dist/i18n/messages/config-keys.js +6 -2
- package/dist/i18n/messages/config.d.ts +4 -0
- package/dist/i18n/messages/drivers.d.ts +22 -0
- package/dist/i18n/messages/drivers.js +22 -0
- package/dist/i18n/messages/errors.d.ts +1 -1
- package/dist/i18n/messages/interactive-startup.d.ts +4 -0
- package/dist/i18n/messages/interactive-startup.js +4 -0
- package/dist/i18n/messages/interactive-view.d.ts +2 -0
- package/dist/i18n/messages/interactive-view.js +2 -0
- package/dist/i18n/messages/interactive.d.ts +6 -0
- package/dist/i18n/messages/report.d.ts +14 -0
- package/dist/i18n/messages/report.js +14 -0
- package/dist/i18n/messages/subcommands-config.d.ts +8 -0
- package/dist/i18n/messages/subcommands-config.js +8 -0
- package/dist/i18n/messages/subcommands.d.ts +8 -0
- package/dist/modes/acp/acp-config.d.ts +4 -2
- package/dist/modes/acp/acp-config.js +17 -3
- package/dist/modes/acp/acp-events.d.ts +2 -0
- package/dist/modes/acp/acp-events.js +4 -0
- package/dist/modes/acp/acp-server.js +6 -2
- package/dist/modes/acp/acp-sessions.d.ts +8 -1
- package/dist/modes/acp/acp-sessions.js +18 -0
- package/dist/modes/commands-core.d.ts +14 -1
- package/dist/modes/commands-core.js +34 -2
- package/dist/modes/interactive/startup-ui.js +21 -0
- package/dist/modes/interactive/status-area.js +1 -1
- package/dist/modes/interactive/tool-view.d.ts +8 -2
- package/dist/modes/interactive/tool-view.js +12 -5
- package/dist/modes/print/print-mode.d.ts +3 -0
- package/dist/modes/print/print-mode.js +35 -8
- package/dist/modes/rpc/commands.d.ts +2 -0
- package/dist/modes/rpc/commands.js +22 -7
- package/dist/modes/rpc/rpc-mode.js +3 -0
- package/dist/modes/startup-ui-text.js +11 -0
- package/dist/rpc.d.ts +2 -1
- package/dist/session/unclean-end.d.ts +8 -0
- package/dist/session/unclean-end.js +39 -7
- package/dist/tools/registry.d.ts +6 -0
- package/dist/tools/registry.js +13 -0
- package/dist/tools/types.d.ts +7 -0
- package/docs/README.md +1 -1
- package/docs/en/README.md +3 -3
- package/docs/en/guides/extensions.md +141 -0
- package/docs/en/guides/providers.md +27 -7
- package/docs/en/guides/tui.md +1 -1
- package/docs/en/reference/acp.md +1 -1
- package/docs/en/reference/host-api.md +55 -27
- package/docs/en/reference/rpc.md +12 -8
- package/docs/guides/codemode.md +52 -12
- package/docs/guides/extensions.md +136 -0
- package/docs/guides/providers.md +21 -1
- package/docs/guides/sandbox.md +2 -0
- package/docs/guides/tui.md +1 -1
- package/docs/reference/acp.md +1 -1
- package/docs/reference/host-api.md +55 -27
- package/docs/reference/rpc.md +12 -8
- package/docs/reference/session-format.md +10 -9
- package/package.json +5 -2
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
24
24
|
import { join } from "node:path";
|
|
25
25
|
import { REPEATED_TOOL_CALL, guardFor, loopReminderText, loopStopText, } from "./loop-guard.js";
|
|
26
|
+
import { coerceArguments } from "./schema-coerce.js";
|
|
26
27
|
import { formatSchemaErrors, validateSchema } from "./schema.js";
|
|
27
28
|
import { CODEMODE_TOOL } from "../tools/presets.js";
|
|
28
29
|
import { executionModeOf } from "../tools/registry.js";
|
|
@@ -37,6 +38,9 @@ export const NESTED_MAX_RESULT_CHARS = 1024 * 1024;
|
|
|
37
38
|
const autoDecisions = new WeakMap();
|
|
38
39
|
/** 门禁拒绝(gate.block)而没有执行的调用:tool_execution_end 带 `denied`。 */
|
|
39
40
|
const deniedCalls = new WeakSet();
|
|
41
|
+
function isArgs(value) {
|
|
42
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
43
|
+
}
|
|
40
44
|
export function errorResult(text) {
|
|
41
45
|
return { content: text, isError: true };
|
|
42
46
|
}
|
|
@@ -66,6 +70,31 @@ function notFoundText(name, options) {
|
|
|
66
70
|
}
|
|
67
71
|
return toolUnavailableText(name);
|
|
68
72
|
}
|
|
73
|
+
/** 严格校验失败、宽松强转后通过时的参数;其余(本来就合法、强转后仍不合法)为 undefined。 */
|
|
74
|
+
function coercedArgumentsOf(tool, args) {
|
|
75
|
+
if (validateSchema(tool.parameters, args).length === 0)
|
|
76
|
+
return undefined;
|
|
77
|
+
const coerced = coerceArguments(tool.parameters, args);
|
|
78
|
+
if (!coerced.changed || validateSchema(tool.parameters, coerced.value).length > 0) {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
return isArgs(coerced.value) ? coerced.value : undefined;
|
|
82
|
+
}
|
|
83
|
+
/** `tool_execution_start`:带 `coercedArguments`(实际执行的参数)当且仅当强转改了模型的原始参数。 */
|
|
84
|
+
function startEvent(call, tool, parentToolCallId) {
|
|
85
|
+
const event = {
|
|
86
|
+
type: "tool_execution_start",
|
|
87
|
+
toolCallId: call.id,
|
|
88
|
+
toolName: call.name,
|
|
89
|
+
args: call.arguments,
|
|
90
|
+
};
|
|
91
|
+
const coerced = tool === undefined ? undefined : coercedArgumentsOf(tool, call.arguments);
|
|
92
|
+
if (coerced !== undefined)
|
|
93
|
+
event.coercedArguments = coerced;
|
|
94
|
+
if (parentToolCallId !== undefined)
|
|
95
|
+
event.parentToolCallId = parentToolCallId;
|
|
96
|
+
return event;
|
|
97
|
+
}
|
|
69
98
|
async function prepare(call, assistant, options, signal, parent) {
|
|
70
99
|
if (signal.aborted)
|
|
71
100
|
return { kind: "immediate", call, result: errorResult(ABORTED_TOOL_TEXT) };
|
|
@@ -75,23 +104,33 @@ async function prepare(call, assistant, options, signal, parent) {
|
|
|
75
104
|
if (tool === undefined) {
|
|
76
105
|
return { kind: "immediate", call, result: errorResult(notFoundText(call.name, options)) };
|
|
77
106
|
}
|
|
78
|
-
|
|
79
|
-
|
|
107
|
+
/** 严格校验;失败时按 schema 宽松强转一次再校验,仍失败则回报原始参数的错误。 */
|
|
108
|
+
const check = (args) => {
|
|
109
|
+
const errors = validateSchema(tool.parameters, args);
|
|
80
110
|
if (errors.length === 0)
|
|
81
|
-
return
|
|
111
|
+
return { input: args };
|
|
112
|
+
const coerced = coercedArgumentsOf(tool, args);
|
|
113
|
+
if (coerced !== undefined)
|
|
114
|
+
return { input: coerced };
|
|
82
115
|
return {
|
|
83
116
|
kind: "immediate",
|
|
84
117
|
call,
|
|
85
118
|
result: errorResult(`Invalid arguments for ${call.name}:\n${formatSchemaErrors(errors)}`),
|
|
86
119
|
};
|
|
87
120
|
};
|
|
88
|
-
const
|
|
89
|
-
if (
|
|
90
|
-
return
|
|
91
|
-
let input =
|
|
121
|
+
const first = check(call.arguments);
|
|
122
|
+
if ("kind" in first)
|
|
123
|
+
return first;
|
|
124
|
+
let input = first.input;
|
|
125
|
+
// 强转后的参数只给门禁、钩子与工具;助手消息里的原始调用不改(会话回放与提示前缀逐字节不变)
|
|
126
|
+
let used = call;
|
|
127
|
+
if (input !== call.arguments && isArgs(input)) {
|
|
128
|
+
const { rawArguments: _raw, ...rest } = call;
|
|
129
|
+
used = { ...rest, arguments: input };
|
|
130
|
+
}
|
|
92
131
|
try {
|
|
93
132
|
const gateContext = parent === undefined ? { signal, assistant, tool } : { signal, assistant, tool, parent };
|
|
94
|
-
const gate = await options.beforeToolCall(
|
|
133
|
+
const gate = await options.beforeToolCall(used, gateContext);
|
|
95
134
|
if (gate.autoDecision !== undefined)
|
|
96
135
|
autoDecisions.set(call, gate.autoDecision);
|
|
97
136
|
if (signal.aborted)
|
|
@@ -105,10 +144,10 @@ async function prepare(call, assistant, options, signal, parent) {
|
|
|
105
144
|
};
|
|
106
145
|
}
|
|
107
146
|
if (gate.input !== undefined) {
|
|
108
|
-
const recheck =
|
|
109
|
-
if (
|
|
147
|
+
const recheck = check(gate.input);
|
|
148
|
+
if ("kind" in recheck)
|
|
110
149
|
return recheck;
|
|
111
|
-
input =
|
|
150
|
+
input = recheck.input;
|
|
112
151
|
}
|
|
113
152
|
}
|
|
114
153
|
catch (error) {
|
|
@@ -118,7 +157,7 @@ async function prepare(call, assistant, options, signal, parent) {
|
|
|
118
157
|
result: errorResult(signal.aborted ? ABORTED_TOOL_TEXT : `Tool call rejected: ${String(error)}`),
|
|
119
158
|
};
|
|
120
159
|
}
|
|
121
|
-
return { kind: "prepared", call, tool, input };
|
|
160
|
+
return { kind: "prepared", call, used, tool, input };
|
|
122
161
|
}
|
|
123
162
|
function resultText(content) {
|
|
124
163
|
if (typeof content === "string")
|
|
@@ -158,7 +197,7 @@ function truncateResult(call, result, options, nested = false) {
|
|
|
158
197
|
};
|
|
159
198
|
}
|
|
160
199
|
async function execute(prepared, options, signal, emit, parent) {
|
|
161
|
-
const { call, tool, input } = prepared;
|
|
200
|
+
const { call, used, tool, input } = prepared;
|
|
162
201
|
if (signal.aborted)
|
|
163
202
|
return errorResult(ABORTED_TOOL_TEXT);
|
|
164
203
|
const updates = [];
|
|
@@ -179,7 +218,7 @@ async function execute(prepared, options, signal, emit, parent) {
|
|
|
179
218
|
});
|
|
180
219
|
let result;
|
|
181
220
|
try {
|
|
182
|
-
const created = options.createToolContext(
|
|
221
|
+
const created = options.createToolContext(used, signal, onUpdate);
|
|
183
222
|
// [ME-D] 工具按会话结果上限一次截到位(D11);宿主自己给了就不覆盖
|
|
184
223
|
const ctx = created.maxResultChars !== undefined
|
|
185
224
|
? created
|
|
@@ -206,8 +245,8 @@ async function execute(prepared, options, signal, emit, parent) {
|
|
|
206
245
|
try {
|
|
207
246
|
result =
|
|
208
247
|
parent === undefined
|
|
209
|
-
? await options.afterToolCall(
|
|
210
|
-
: await options.afterToolCall(
|
|
248
|
+
? await options.afterToolCall(used, result)
|
|
249
|
+
: await options.afterToolCall(used, result, { parent });
|
|
211
250
|
}
|
|
212
251
|
catch (error) {
|
|
213
252
|
result = errorResult(`PostToolUse failed: ${String(error)}`);
|
|
@@ -247,12 +286,7 @@ export async function runToolBatch(assistant, options, signal, emit) {
|
|
|
247
286
|
const verdicts = new Map();
|
|
248
287
|
let stop;
|
|
249
288
|
for (const call of calls) {
|
|
250
|
-
await emit(
|
|
251
|
-
type: "tool_execution_start",
|
|
252
|
-
toolCallId: call.id,
|
|
253
|
-
toolName: call.name,
|
|
254
|
-
args: call.arguments,
|
|
255
|
-
});
|
|
289
|
+
await emit(startEvent(call, options.getTool(call.name)));
|
|
256
290
|
const verdict = guard.observe(call, options.getTool(call.name));
|
|
257
291
|
verdicts.set(call, verdict);
|
|
258
292
|
if (verdict === "stop") {
|
|
@@ -370,12 +404,7 @@ export async function runSingleToolCall(call, assistant, options, signal, nested
|
|
|
370
404
|
event.type === "tool_execution_end"
|
|
371
405
|
? { ...event, parentToolCallId }
|
|
372
406
|
: event);
|
|
373
|
-
await emit(
|
|
374
|
-
type: "tool_execution_start",
|
|
375
|
-
toolCallId: call.id,
|
|
376
|
-
toolName: call.name,
|
|
377
|
-
args: call.arguments,
|
|
378
|
-
});
|
|
407
|
+
await emit(startEvent(call, options.getNestedTool?.(call.name) ?? options.getTool(call.name)));
|
|
379
408
|
const prepared = await prepare(call, assistant, options, signal, nested.parent);
|
|
380
409
|
const result = prepared.kind === "immediate"
|
|
381
410
|
? prepared.result
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -169,6 +169,10 @@ export type SessionEvent = {
|
|
|
169
169
|
toolCallId: string;
|
|
170
170
|
toolName: string;
|
|
171
171
|
args: unknown;
|
|
172
|
+
/**
|
|
173
|
+
* 宽松强转改了模型原始参数时,实际交给门禁与工具的参数(`args` 仍是模型原样);没强转不带。
|
|
174
|
+
*/
|
|
175
|
+
coercedArguments?: Record<string, unknown>;
|
|
172
176
|
parentToolCallId?: string;
|
|
173
177
|
} | {
|
|
174
178
|
type: "tool_execution_update";
|
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
* 未写明接受,不发未知 beta 头最稳);不在表里的主机(中转)只对 `claude*` 模型开——中转转发 Claude
|
|
10
10
|
* 时仍需要交错思考。
|
|
11
11
|
* - `sendCacheControl`:缺省开;DeepSeek 文档写明 `cache_control` 被忽略,关掉以减小请求体。
|
|
12
|
+
* - `messageThreads`:只有官方端点开;第三方与中转一律关(不认 `thread` 字段的网关会丢掉它,续接就变成
|
|
13
|
+
* 缺前文的请求),要开的中转显式写 `compat.messageThreads: true`。
|
|
12
14
|
* - `adaptiveThinking` 只由目录 / 配置给(官方模型逐条写在 catalog/anthropic.json),表里不推断。
|
|
13
15
|
* - 缓存保留层级(1h TTL)等缓存能力在 cache-params.ts 的 `HOST_CACHE_CAPABILITIES`,不在这里。
|
|
14
16
|
* - OpenRouter:流式 usage 只出现在 `message_delta`,`applyAnthropicUsage` 本就按非 null 字段合并,
|
|
@@ -18,7 +20,7 @@
|
|
|
18
20
|
*/
|
|
19
21
|
import type { AnthropicMessagesCompat, Model, ProviderData } from "../types.js";
|
|
20
22
|
export type ResolvedAnthropicCompat = Required<AnthropicMessagesCompat>;
|
|
21
|
-
export declare const ANTHROPIC_COMPAT_KEYS: readonly ["supportsCacheControlOnTools", "supportsTemperatureWithThinking", "adaptiveThinking", "maxCacheBreakpoints", "sendInterleavedThinkingBeta", "sendCacheControl"];
|
|
23
|
+
export declare const ANTHROPIC_COMPAT_KEYS: readonly ["supportsCacheControlOnTools", "supportsTemperatureWithThinking", "adaptiveThinking", "maxCacheBreakpoints", "sendInterleavedThinkingBeta", "sendCacheControl", "messageThreads"];
|
|
22
24
|
/** 未知主机的保守缺省(`sendInterleavedThinkingBeta` 另按模型 id 定,见 `hostDefaults`)。 */
|
|
23
25
|
export declare const DEFAULT_ANTHROPIC_COMPAT: Readonly<ResolvedAnthropicCompat>;
|
|
24
26
|
export interface AnthropicHostRule {
|
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
* 未写明接受,不发未知 beta 头最稳);不在表里的主机(中转)只对 `claude*` 模型开——中转转发 Claude
|
|
10
10
|
* 时仍需要交错思考。
|
|
11
11
|
* - `sendCacheControl`:缺省开;DeepSeek 文档写明 `cache_control` 被忽略,关掉以减小请求体。
|
|
12
|
+
* - `messageThreads`:只有官方端点开;第三方与中转一律关(不认 `thread` 字段的网关会丢掉它,续接就变成
|
|
13
|
+
* 缺前文的请求),要开的中转显式写 `compat.messageThreads: true`。
|
|
12
14
|
* - `adaptiveThinking` 只由目录 / 配置给(官方模型逐条写在 catalog/anthropic.json),表里不推断。
|
|
13
15
|
* - 缓存保留层级(1h TTL)等缓存能力在 cache-params.ts 的 `HOST_CACHE_CAPABILITIES`,不在这里。
|
|
14
16
|
* - OpenRouter:流式 usage 只出现在 `message_delta`,`applyAnthropicUsage` 本就按非 null 字段合并,
|
|
@@ -23,6 +25,7 @@ export const ANTHROPIC_COMPAT_KEYS = [
|
|
|
23
25
|
"maxCacheBreakpoints",
|
|
24
26
|
"sendInterleavedThinkingBeta",
|
|
25
27
|
"sendCacheControl",
|
|
28
|
+
"messageThreads",
|
|
26
29
|
];
|
|
27
30
|
/** 未知主机的保守缺省(`sendInterleavedThinkingBeta` 另按模型 id 定,见 `hostDefaults`)。 */
|
|
28
31
|
export const DEFAULT_ANTHROPIC_COMPAT = {
|
|
@@ -32,11 +35,15 @@ export const DEFAULT_ANTHROPIC_COMPAT = {
|
|
|
32
35
|
maxCacheBreakpoints: 4,
|
|
33
36
|
sendInterleavedThinkingBeta: false,
|
|
34
37
|
sendCacheControl: true,
|
|
38
|
+
messageThreads: false,
|
|
35
39
|
};
|
|
36
40
|
const THIRD_PARTY = { sendInterleavedThinkingBeta: false };
|
|
37
41
|
/** 主机表:先命中先用。 */
|
|
38
42
|
export const ANTHROPIC_HOST_RULES = [
|
|
39
|
-
{
|
|
43
|
+
{
|
|
44
|
+
host: "api.anthropic.com",
|
|
45
|
+
patch: { sendInterleavedThinkingBeta: true, messageThreads: true },
|
|
46
|
+
},
|
|
40
47
|
{
|
|
41
48
|
host: "api.deepseek.com",
|
|
42
49
|
patch: { sendCacheControl: false, sendInterleavedThinkingBeta: false, adaptiveThinking: false },
|
|
@@ -15,7 +15,8 @@ import { AssistantEventStreamImpl } from "../event-stream.js";
|
|
|
15
15
|
import { authHeaders, describeErrorJson, idleTimeoutOf, streamIdleTimeoutOf, mergeHeaders, USER_AGENT, } from "../http.js";
|
|
16
16
|
import { readSseEvents } from "../sse.js";
|
|
17
17
|
import { clampRequestMaxTokens, postWithMaxTokensFallback } from "./max-tokens.js";
|
|
18
|
-
import { ANTHROPIC_VERSION, anthropicMessagesUrl, buildAnthropicRequest, detectAnthropicCompat, } from "./anthropic-request.js";
|
|
18
|
+
import { ANTHROPIC_VERSION, anthropicMessagesUrl, buildAnthropicRequest, convertMessages, detectAnthropicCompat, MESSAGE_THREADS_BETA, } from "./anthropic-request.js";
|
|
19
|
+
import { prepareThread, recordThreadReply, sendThreadRequest, threadEndpointKey, threadsDisabled, } from "./anthropic-threads.js";
|
|
19
20
|
import { BlockTracker, STREAM_ENDED_MESSAGE, ProviderStopError, createOutput, finishDone, finishError, requireApiKey, } from "./shared.js";
|
|
20
21
|
function num(value) {
|
|
21
22
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
@@ -156,6 +157,14 @@ async function run(stream, model, context, options) {
|
|
|
156
157
|
const tracker = new BlockTracker(stream, createOutput(model));
|
|
157
158
|
try {
|
|
158
159
|
const request = buildAnthropicRequest(model, context, options);
|
|
160
|
+
const endpointBase = model.baseUrl ?? "https://api.anthropic.com";
|
|
161
|
+
const threadKey = options.threadKey ?? options.sessionId;
|
|
162
|
+
// 端点或会话已确认不支持线程:连 beta 头一起去掉(保温 / 摘要重放同样,头与真实回合一致)
|
|
163
|
+
if (request.threads &&
|
|
164
|
+
threadsDisabled(threadEndpointKey(model.provider, endpointBase, model.id), threadKey)) {
|
|
165
|
+
request.threads = false;
|
|
166
|
+
request.betas = request.betas.filter((beta) => beta !== MESSAGE_THREADS_BETA);
|
|
167
|
+
}
|
|
159
168
|
tracker.output.thinkingLevel = request.thinkingLevel;
|
|
160
169
|
if (request.providerThinkingLevel !== undefined) {
|
|
161
170
|
tracker.output.providerThinkingLevel = request.providerThinkingLevel;
|
|
@@ -175,7 +184,39 @@ async function run(stream, model, context, options) {
|
|
|
175
184
|
idleTimeoutMs: idleTimeoutOf(options),
|
|
176
185
|
onResponse: options.onResponse,
|
|
177
186
|
};
|
|
178
|
-
const
|
|
187
|
+
const send = (next, dropThreadBeta) => postWithMaxTokensFallback(model, url, {
|
|
188
|
+
...post,
|
|
189
|
+
body: next,
|
|
190
|
+
...(dropThreadBeta === true
|
|
191
|
+
? {
|
|
192
|
+
headers: buildHeaders(model, options, request.betas.filter((beta) => beta !== MESSAGE_THREADS_BETA)),
|
|
193
|
+
}
|
|
194
|
+
: {}),
|
|
195
|
+
}, "max_tokens");
|
|
196
|
+
// 线程续接:只对真实回合;重放 / 摘要 / 探测 / 分类请求不碰线程状态。onPayload 换成非对象体时不续接。
|
|
197
|
+
const threadCtx = {
|
|
198
|
+
provider: model.provider,
|
|
199
|
+
baseUrl,
|
|
200
|
+
betas: request.betas,
|
|
201
|
+
};
|
|
202
|
+
const fullBody = obj(body);
|
|
203
|
+
const prepared = request.threads &&
|
|
204
|
+
fullBody !== undefined &&
|
|
205
|
+
threadKey !== undefined &&
|
|
206
|
+
options.disableContinuation !== true &&
|
|
207
|
+
(options.purpose === undefined || options.purpose === "turn")
|
|
208
|
+
? prepareThread(threadCtx, threadKey, fullBody)
|
|
209
|
+
: undefined;
|
|
210
|
+
let response;
|
|
211
|
+
let thread;
|
|
212
|
+
if (prepared !== undefined && fullBody !== undefined) {
|
|
213
|
+
const sent = await sendThreadRequest(prepared, fullBody, send, options.signal);
|
|
214
|
+
response = sent.response;
|
|
215
|
+
thread = sent.thread;
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
response = await send(body);
|
|
219
|
+
}
|
|
179
220
|
stream.push({ type: "start", partial: tracker.output });
|
|
180
221
|
const state = { blocks: new Map(), stop: undefined, sawMessageStop: false };
|
|
181
222
|
for await (const sse of readSseEvents(response.body, options.signal, streamIdleTimeoutOf(options))) {
|
|
@@ -202,6 +243,17 @@ async function run(stream, model, context, options) {
|
|
|
202
243
|
if (stop.reason === "error")
|
|
203
244
|
throw new ProviderStopError(stop.message);
|
|
204
245
|
finishDone(stream, tracker, model, stop.reason);
|
|
246
|
+
// 干净回复才记续接点(须在块收尾之后转换);出错 / 中止的回合不记,取用时已删旧点,
|
|
247
|
+
// 下一次整请求新开线程
|
|
248
|
+
if (thread !== undefined && fullBody !== undefined) {
|
|
249
|
+
try {
|
|
250
|
+
const reply = convertMessages([tracker.output]);
|
|
251
|
+
recordThreadReply(threadCtx, thread, fullBody, tracker.output.responseId, reply);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
// 记不下续接点只是下一次发整请求
|
|
255
|
+
}
|
|
256
|
+
}
|
|
205
257
|
}
|
|
206
258
|
catch (error) {
|
|
207
259
|
finishError(stream, tracker, model, error, options.signal);
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
import type { AssistantMessage, Model, ModelThinkingLevel, StreamOptions, ToolResultMessage, TranscriptContext, UserMessage } from "../types.js";
|
|
20
20
|
export declare const ANTHROPIC_VERSION = "2023-06-01";
|
|
21
21
|
export declare const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
22
|
+
export { MESSAGE_THREADS_BETA } from "./anthropic-threads.js";
|
|
22
23
|
export { DEFAULT_ANTHROPIC_COMPAT, detectAnthropicCompat } from "./anthropic-compat.js";
|
|
23
24
|
type Json = Record<string, unknown>;
|
|
24
25
|
export interface AnthropicRequest {
|
|
@@ -26,6 +27,8 @@ export interface AnthropicRequest {
|
|
|
26
27
|
betas: string[];
|
|
27
28
|
thinkingLevel: ModelThinkingLevel;
|
|
28
29
|
providerThinkingLevel: string | undefined;
|
|
30
|
+
/** 请求属于线程会话(带线程 beta 头);是否真的续接另看 `disableContinuation` 与会话状态。 */
|
|
31
|
+
threads: boolean;
|
|
29
32
|
}
|
|
30
33
|
export declare function cacheControlFor(retention: StreamOptions["cacheRetention"]): {
|
|
31
34
|
type: "ephemeral";
|
|
@@ -20,9 +20,11 @@ import { contentText, normalizeContext, sanitizeText } from "../context.js";
|
|
|
20
20
|
import { largeString } from "../json-body.js";
|
|
21
21
|
import { budgetedMaxTokens, clampThinkingLevel, mappedThinkingValue, thinkingBudget, } from "../thinking.js";
|
|
22
22
|
import { detectAnthropicCompat } from "./anthropic-compat.js";
|
|
23
|
+
import { MESSAGE_THREADS_BETA } from "./anthropic-threads.js";
|
|
23
24
|
import { effectiveRetention, resolveCacheRetention, resolvePromptCacheCompat, } from "./cache-params.js";
|
|
24
25
|
export const ANTHROPIC_VERSION = "2023-06-01";
|
|
25
26
|
export const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
27
|
+
export { MESSAGE_THREADS_BETA } from "./anthropic-threads.js";
|
|
26
28
|
export { DEFAULT_ANTHROPIC_COMPAT, detectAnthropicCompat } from "./anthropic-compat.js";
|
|
27
29
|
export function cacheControlFor(retention) {
|
|
28
30
|
if (retention === "none")
|
|
@@ -271,5 +273,9 @@ export function buildAnthropicRequest(model, context, options) {
|
|
|
271
273
|
if (model.samplingParams)
|
|
272
274
|
Object.assign(body, model.samplingParams);
|
|
273
275
|
enforceCacheTtlOrder(body);
|
|
274
|
-
|
|
276
|
+
// 线程 beta 头只看会话与缓存开关,不看 disableContinuation:保温 / 摘要重放要与真实回合请求头一致
|
|
277
|
+
const threads = compat.messageThreads === true && options.sessionId !== undefined && retention !== "none";
|
|
278
|
+
if (threads)
|
|
279
|
+
betas.push(MESSAGE_THREADS_BETA);
|
|
280
|
+
return { body, betas, thinkingLevel: level, providerThinkingLevel: providerLevel, threads };
|
|
275
281
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic message threads(beta `message-threads-2026-08-12`,docs/guides/providers.md「消息线程」)。
|
|
3
|
+
*
|
|
4
|
+
* 服务端按线程保存对话:带稳定 `sessionId` 且开着提示缓存的请求,在上一条回复之后只需发新增消息。
|
|
5
|
+
* 线上形状:
|
|
6
|
+
* - 首条(或无法续接时)整请求发出,加 `thread: { type: "create" }`;
|
|
7
|
+
* - 续接:去掉 `system` / `tools`(服务端沿用线程里的),`messages` 只留新增部分,加
|
|
8
|
+
* `thread: { type: "continue", previous_message_id: <上一条回复的 message id> }`;
|
|
9
|
+
* - 拒收带 `error.details.error_code`:`thread_not_found` / `thread_already_continued` /
|
|
10
|
+
* `thread_continue_in_flight` / `thread_fingerprint_mismatch` → 整请求新开线程重发一次;
|
|
11
|
+
* `thread_unsupported_request`,或没有错误码但 400 文案点名 `thread`(端点不认该字段)→ 去掉
|
|
12
|
+
* `thread` 整请求重发一次,重发请求同时去掉线程 beta 头(端点可能连该头的值都拒收),并把该会话与
|
|
13
|
+
* 该端点 + 模型在本进程内关掉线程(之后的请求不再带头,也不再多吃一次 400)。其它错误与线程无关,原样抛出。
|
|
14
|
+
*
|
|
15
|
+
* 每个会话只记最近一次回复的续接点(一条回复只能续接一次):取用即删,并发请求只会各自新开线程。
|
|
16
|
+
* 续接点只在「线程内的前文与本次请求逐项一致」时使用:哈希覆盖端点、模型、system、tools、
|
|
17
|
+
* thinking、output_config、tool_choice、beta 与已有消息(忽略 cache_control 位置与字符串 / 文本块写法)。
|
|
18
|
+
* 压缩、回退 / 分支切换、改模型 / system / tools 都会让哈希不一致,改走整请求并新开线程。
|
|
19
|
+
* token 用量与缓存读写仍按整段对话报告,指纹与未命中检测只看转录,不受续接影响。
|
|
20
|
+
*/
|
|
21
|
+
type Json = Record<string, unknown>;
|
|
22
|
+
export declare const MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
|
|
23
|
+
/** 会话状态表容量;超出时丢最久未用的会话(它的线程多半已在服务端过期,丢了只是下次新开)。 */
|
|
24
|
+
export declare const MAX_THREAD_SESSIONS = 10000;
|
|
25
|
+
export declare function threadEndpointKey(provider: string, baseUrl: string, modelId: unknown): string;
|
|
26
|
+
/** 该端点 + 模型或该线程键已被关掉线程:请求既不带线程字段,也不带线程 beta 头。 */
|
|
27
|
+
export declare function threadsDisabled(endpoint: string, threadKey: string | undefined): boolean;
|
|
28
|
+
/** 忘掉一个会话的线程状态(会话结束时调用);不传清空全部。 */
|
|
29
|
+
export declare function forgetThreads(sessionId?: string): void;
|
|
30
|
+
/** 测试用:会话当前的状态。 */
|
|
31
|
+
export declare function threadStateOf(sessionId: string): "off" | "continuable" | undefined;
|
|
32
|
+
export interface ThreadContext {
|
|
33
|
+
provider: string;
|
|
34
|
+
baseUrl: string;
|
|
35
|
+
betas: readonly string[];
|
|
36
|
+
}
|
|
37
|
+
export interface ThreadRequest {
|
|
38
|
+
/** 线程键(缺省 sessionId;fork 会话用自己的 id)。 */
|
|
39
|
+
sessionId: string;
|
|
40
|
+
endpoint: string;
|
|
41
|
+
body: Json;
|
|
42
|
+
}
|
|
43
|
+
/** 本次请求的线程形态;会话已被关掉线程时返回 undefined(发普通请求)。 */
|
|
44
|
+
export declare function prepareThread(ctx: ThreadContext, sessionId: string, body: Json): ThreadRequest | undefined;
|
|
45
|
+
/** 拒收体里的 `error.details.error_code`。 */
|
|
46
|
+
export declare function threadErrorCode(error: unknown): string | undefined;
|
|
47
|
+
/** `new`:整请求新开线程重发;`unsupported`:去掉 thread 重发并关掉该会话;undefined:与线程无关。 */
|
|
48
|
+
export declare function classifyThreadError(error: unknown): "new" | "unsupported" | undefined;
|
|
49
|
+
export interface SentThread {
|
|
50
|
+
response: Response;
|
|
51
|
+
/** 产出该响应的线程请求;undefined = 最终发的是不带 thread 的普通请求。 */
|
|
52
|
+
thread: ThreadRequest | undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 发线程请求;被线程相关的 400 拒收(流未开始)时整请求重发一次。重发后的错误照常抛出。
|
|
56
|
+
* `full` 是未改动的整请求体。
|
|
57
|
+
*/
|
|
58
|
+
export declare function sendThreadRequest(thread: ThreadRequest, full: Json, send: (body: Json, dropThreadBeta?: boolean) => Promise<Response>, signal: AbortSignal): Promise<SentThread>;
|
|
59
|
+
/**
|
|
60
|
+
* 记下下一次请求的续接点:`reply` 是线程请求 `thread` 的干净回复(已转成请求消息形状),
|
|
61
|
+
* `full` 是该次的整请求体。
|
|
62
|
+
*/
|
|
63
|
+
export declare function recordThreadReply(ctx: ThreadContext, thread: ThreadRequest, full: Json, replyId: string | undefined, reply: readonly unknown[]): void;
|
|
64
|
+
export {};
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic message threads(beta `message-threads-2026-08-12`,docs/guides/providers.md「消息线程」)。
|
|
3
|
+
*
|
|
4
|
+
* 服务端按线程保存对话:带稳定 `sessionId` 且开着提示缓存的请求,在上一条回复之后只需发新增消息。
|
|
5
|
+
* 线上形状:
|
|
6
|
+
* - 首条(或无法续接时)整请求发出,加 `thread: { type: "create" }`;
|
|
7
|
+
* - 续接:去掉 `system` / `tools`(服务端沿用线程里的),`messages` 只留新增部分,加
|
|
8
|
+
* `thread: { type: "continue", previous_message_id: <上一条回复的 message id> }`;
|
|
9
|
+
* - 拒收带 `error.details.error_code`:`thread_not_found` / `thread_already_continued` /
|
|
10
|
+
* `thread_continue_in_flight` / `thread_fingerprint_mismatch` → 整请求新开线程重发一次;
|
|
11
|
+
* `thread_unsupported_request`,或没有错误码但 400 文案点名 `thread`(端点不认该字段)→ 去掉
|
|
12
|
+
* `thread` 整请求重发一次,重发请求同时去掉线程 beta 头(端点可能连该头的值都拒收),并把该会话与
|
|
13
|
+
* 该端点 + 模型在本进程内关掉线程(之后的请求不再带头,也不再多吃一次 400)。其它错误与线程无关,原样抛出。
|
|
14
|
+
*
|
|
15
|
+
* 每个会话只记最近一次回复的续接点(一条回复只能续接一次):取用即删,并发请求只会各自新开线程。
|
|
16
|
+
* 续接点只在「线程内的前文与本次请求逐项一致」时使用:哈希覆盖端点、模型、system、tools、
|
|
17
|
+
* thinking、output_config、tool_choice、beta 与已有消息(忽略 cache_control 位置与字符串 / 文本块写法)。
|
|
18
|
+
* 压缩、回退 / 分支切换、改模型 / system / tools 都会让哈希不一致,改走整请求并新开线程。
|
|
19
|
+
* token 用量与缓存读写仍按整段对话报告,指纹与未命中检测只看转录,不受续接影响。
|
|
20
|
+
*/
|
|
21
|
+
import { HttpError } from "../http.js";
|
|
22
|
+
import { hash16 } from "../cache/fingerprint.js";
|
|
23
|
+
export const MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
|
|
24
|
+
/** 会话状态表容量;超出时丢最久未用的会话(它的线程多半已在服务端过期,丢了只是下次新开)。 */
|
|
25
|
+
export const MAX_THREAD_SESSIONS = 10_000;
|
|
26
|
+
const threadState = new Map();
|
|
27
|
+
/** 已确认不支持线程的端点 + 模型(本进程内);容量有限,超出丢最旧的。 */
|
|
28
|
+
const offEndpoints = new Set();
|
|
29
|
+
const MAX_OFF_ENDPOINTS = 1000;
|
|
30
|
+
export function threadEndpointKey(provider, baseUrl, modelId) {
|
|
31
|
+
return JSON.stringify([provider, baseUrl, modelId]);
|
|
32
|
+
}
|
|
33
|
+
function markEndpointOff(endpoint) {
|
|
34
|
+
offEndpoints.delete(endpoint);
|
|
35
|
+
offEndpoints.add(endpoint);
|
|
36
|
+
if (offEndpoints.size > MAX_OFF_ENDPOINTS) {
|
|
37
|
+
const oldest = offEndpoints.values().next().value;
|
|
38
|
+
if (oldest !== undefined)
|
|
39
|
+
offEndpoints.delete(oldest);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** 该端点 + 模型或该线程键已被关掉线程:请求既不带线程字段,也不带线程 beta 头。 */
|
|
43
|
+
export function threadsDisabled(endpoint, threadKey) {
|
|
44
|
+
return (offEndpoints.has(endpoint) || (threadKey !== undefined && threadState.get(threadKey) === "off"));
|
|
45
|
+
}
|
|
46
|
+
function setState(sessionId, value) {
|
|
47
|
+
threadState.delete(sessionId);
|
|
48
|
+
threadState.set(sessionId, value);
|
|
49
|
+
if (threadState.size > MAX_THREAD_SESSIONS) {
|
|
50
|
+
const oldest = threadState.keys().next().value;
|
|
51
|
+
if (oldest !== undefined)
|
|
52
|
+
threadState.delete(oldest);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** 忘掉一个会话的线程状态(会话结束时调用);不传清空全部。 */
|
|
56
|
+
export function forgetThreads(sessionId) {
|
|
57
|
+
if (sessionId === undefined) {
|
|
58
|
+
threadState.clear();
|
|
59
|
+
offEndpoints.clear();
|
|
60
|
+
}
|
|
61
|
+
else
|
|
62
|
+
threadState.delete(sessionId);
|
|
63
|
+
}
|
|
64
|
+
/** 测试用:会话当前的状态。 */
|
|
65
|
+
export function threadStateOf(sessionId) {
|
|
66
|
+
const state = threadState.get(sessionId);
|
|
67
|
+
return state === undefined ? undefined : state === "off" ? "off" : "continuable";
|
|
68
|
+
}
|
|
69
|
+
/** 线程依赖的一切:固定字段(同线程内不可变)+ 已有消息(规整后)。 */
|
|
70
|
+
function hashPrefix(ctx, body, messages) {
|
|
71
|
+
const settings = JSON.stringify([
|
|
72
|
+
ctx.provider,
|
|
73
|
+
ctx.baseUrl,
|
|
74
|
+
body["model"],
|
|
75
|
+
body["system"],
|
|
76
|
+
body["tools"],
|
|
77
|
+
body["thinking"],
|
|
78
|
+
body["output_config"],
|
|
79
|
+
body["tool_choice"],
|
|
80
|
+
ctx.betas,
|
|
81
|
+
]);
|
|
82
|
+
// cache_control 会随「最新消息」移动;最新 user 消息的字符串内容为挂断点会写成单个文本块,
|
|
83
|
+
// 下一次请求又是字符串:两种写法含义相同,哈希前统一。
|
|
84
|
+
const conversation = JSON.stringify(messages, (key, value) => {
|
|
85
|
+
if (key === "cache_control")
|
|
86
|
+
return undefined;
|
|
87
|
+
if (key === "content" && typeof value === "string")
|
|
88
|
+
return [{ type: "text", text: value }];
|
|
89
|
+
return value;
|
|
90
|
+
});
|
|
91
|
+
return hash16(settings + conversation);
|
|
92
|
+
}
|
|
93
|
+
function createRequest(sessionId, endpoint, body) {
|
|
94
|
+
return { sessionId, endpoint, body: { ...body, thread: { type: "create" } } };
|
|
95
|
+
}
|
|
96
|
+
/** 本次请求的线程形态;会话已被关掉线程时返回 undefined(发普通请求)。 */
|
|
97
|
+
export function prepareThread(ctx, sessionId, body) {
|
|
98
|
+
const endpoint = threadEndpointKey(ctx.provider, ctx.baseUrl, body["model"]);
|
|
99
|
+
const state = threadState.get(sessionId);
|
|
100
|
+
if (state === "off" || offEndpoints.has(endpoint))
|
|
101
|
+
return undefined;
|
|
102
|
+
const messages = Array.isArray(body["messages"]) ? body["messages"] : [];
|
|
103
|
+
if (state !== undefined &&
|
|
104
|
+
messages.length > state.prefixCount &&
|
|
105
|
+
hashPrefix(ctx, body, messages.slice(0, state.prefixCount)) === state.prefixHash) {
|
|
106
|
+
// 取用即删:一条回复只能续接一次,也挡住并发请求重复续接。
|
|
107
|
+
threadState.delete(sessionId);
|
|
108
|
+
const { system: _system, tools: _tools, ...rest } = body;
|
|
109
|
+
return {
|
|
110
|
+
sessionId,
|
|
111
|
+
endpoint,
|
|
112
|
+
body: {
|
|
113
|
+
...rest,
|
|
114
|
+
messages: messages.slice(state.prefixCount),
|
|
115
|
+
thread: { type: "continue", previous_message_id: state.replyId },
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
threadState.delete(sessionId);
|
|
120
|
+
return createRequest(sessionId, endpoint, body);
|
|
121
|
+
}
|
|
122
|
+
const NEW_THREAD_CODES = new Set([
|
|
123
|
+
"thread_not_found",
|
|
124
|
+
"thread_already_continued",
|
|
125
|
+
"thread_continue_in_flight",
|
|
126
|
+
"thread_fingerprint_mismatch",
|
|
127
|
+
]);
|
|
128
|
+
/** 拒收体里的 `error.details.error_code`。 */
|
|
129
|
+
export function threadErrorCode(error) {
|
|
130
|
+
if (!(error instanceof HttpError))
|
|
131
|
+
return undefined;
|
|
132
|
+
try {
|
|
133
|
+
const parsed = JSON.parse(error.body);
|
|
134
|
+
const code = parsed.error?.details?.error_code;
|
|
135
|
+
return typeof code === "string" ? code : undefined;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/** `new`:整请求新开线程重发;`unsupported`:去掉 thread 重发并关掉该会话;undefined:与线程无关。 */
|
|
142
|
+
export function classifyThreadError(error) {
|
|
143
|
+
if (!(error instanceof HttpError))
|
|
144
|
+
return undefined;
|
|
145
|
+
const code = threadErrorCode(error);
|
|
146
|
+
if (code !== undefined && NEW_THREAD_CODES.has(code))
|
|
147
|
+
return "new";
|
|
148
|
+
if (code === "thread_unsupported_request")
|
|
149
|
+
return "unsupported";
|
|
150
|
+
// 端点不认 `thread` 字段(Extra inputs are not permitted)时没有错误码。
|
|
151
|
+
if (code === undefined && error.status === 400 && /thread/i.test(`${error.message}${error.body}`))
|
|
152
|
+
return "unsupported";
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* 发线程请求;被线程相关的 400 拒收(流未开始)时整请求重发一次。重发后的错误照常抛出。
|
|
157
|
+
* `full` 是未改动的整请求体。
|
|
158
|
+
*/
|
|
159
|
+
export async function sendThreadRequest(thread, full, send, signal) {
|
|
160
|
+
try {
|
|
161
|
+
return { response: await send(thread.body), thread };
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
const action = signal.aborted ? undefined : classifyThreadError(error);
|
|
165
|
+
if (action === undefined)
|
|
166
|
+
throw error;
|
|
167
|
+
if (action === "new") {
|
|
168
|
+
const created = createRequest(thread.sessionId, thread.endpoint, full);
|
|
169
|
+
return { response: await send(created.body), thread: created };
|
|
170
|
+
}
|
|
171
|
+
// 先关再发:重发也失败时,同会话的下一次请求不再重复尝试
|
|
172
|
+
setState(thread.sessionId, "off");
|
|
173
|
+
markEndpointOff(thread.endpoint);
|
|
174
|
+
const response = await send(full, true);
|
|
175
|
+
return { response, thread: undefined };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* 记下下一次请求的续接点:`reply` 是线程请求 `thread` 的干净回复(已转成请求消息形状),
|
|
180
|
+
* `full` 是该次的整请求体。
|
|
181
|
+
*/
|
|
182
|
+
export function recordThreadReply(ctx, thread, full, replyId, reply) {
|
|
183
|
+
if (replyId === undefined || replyId === "")
|
|
184
|
+
return;
|
|
185
|
+
const messages = Array.isArray(full["messages"]) ? full["messages"] : [];
|
|
186
|
+
const prefix = [...messages, ...reply];
|
|
187
|
+
setState(thread.sessionId, {
|
|
188
|
+
prefixCount: prefix.length,
|
|
189
|
+
prefixHash: hashPrefix(ctx, full, prefix),
|
|
190
|
+
replyId,
|
|
191
|
+
});
|
|
192
|
+
}
|