dsh-open-model 1.0.0 → 1.1.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/index.js DELETED
@@ -1,96 +0,0 @@
1
- import manifest from './package.json' with { type: 'json' };
2
- import { createKiloCatalog, isCatalogConnectionError, KiloCatalogError, KILO_PROVIDER } from './catalog.js';
3
- import { createModelVisibility, registerModelManagement } from './model-management.js';
4
- import { DEFAULT_MAX_TOKENS, maxTokensParameter, streamKilo } from './stream.js';
5
- import { mountUpdates } from './updates.js';
6
-
7
- export const name = KILO_PROVIDER;
8
- export const inject = ['llm'];
9
-
10
- function requestKilo(url, options) {
11
- const headers = new Headers(options.headers);
12
- headers.set('user-agent', `dsh-open-model/${manifest.version} (+https://github.com/deepseek-ai/deepseek-harness)`);
13
- return fetch(url, { ...options, headers });
14
- }
15
-
16
- function resolvedInfo(model) {
17
- const { provider, id, name, description, inputModalities, context, maxCompletionTokens, supportedParameters } = model;
18
- return {
19
- provider, id, name, description, inputModalities, context,
20
- ...(maxTokensParameter(supportedParameters)
21
- ? { defaultMaxTokens: Math.min(DEFAULT_MAX_TOKENS, maxCompletionTokens ?? DEFAULT_MAX_TOKENS) }
22
- : {}),
23
- };
24
- }
25
-
26
- export function createKiloAdapter({
27
- fetch: fetchImpl = requestKilo,
28
- catalog = createKiloCatalog({ fetch: fetchImpl }),
29
- visibility,
30
- } = {}) {
31
- async function requireModel(id, signal) {
32
- const model = await catalog.getModel(id, signal);
33
- if (model) return model;
34
- throw new KiloCatalogError('该模型当前不在 Kilo 免费目录中。请在模型选择器里重新选择。', {
35
- code: 'NO_MODEL',
36
- });
37
- }
38
-
39
- return {
40
- providerInfo(provider) {
41
- return { id: provider, name: '免费模型' };
42
- },
43
-
44
- providerRetryPolicy() {
45
- return undefined;
46
- },
47
-
48
- imageRequestPricing() {
49
- return undefined;
50
- },
51
-
52
- imageRequestTarget(_provider, _model, image) {
53
- return { width: image.width, height: image.height, maxBytes: image.bytes };
54
- },
55
-
56
- async listModels() {
57
- const directory = catalog.listModels().catch(error => {
58
- if (!isCatalogConnectionError(error)) throw error;
59
- return [];
60
- });
61
- const [models, isDisabled] = await Promise.all([directory, visibility?.readDisabled()]);
62
- return models.filter(model => !isDisabled?.(model.id)).map(resolvedInfo);
63
- },
64
-
65
- async resolveModel(_provider, id, signal) {
66
- return resolvedInfo(await requireModel(id, signal));
67
- },
68
-
69
- async prepareCall(_provider, id, signal) {
70
- const model = await requireModel(id, signal);
71
- return {
72
- model: resolvedInfo(model),
73
- stream: options => streamKilo(options, model, fetchImpl),
74
- };
75
- },
76
-
77
- async *stream(options) {
78
- const model = await requireModel(options.model, options.signal);
79
- yield* streamKilo(options, model, fetchImpl);
80
- },
81
- };
82
- }
83
-
84
- export function apply(ctx) {
85
- const catalog = createKiloCatalog({ fetch: requestKilo });
86
- const visibility = createModelVisibility(ctx.get('profileContext')?.dir);
87
- const adapter = createKiloAdapter({ catalog, visibility });
88
- const registration = ctx.llm.registerAdapter([KILO_PROVIDER], adapter);
89
- ctx.inject(['connection'], scope => {
90
- registerModelManagement(scope, {
91
- catalog, visibility, fetch: requestKilo,
92
- onChange: () => registration.replace([KILO_PROVIDER]),
93
- });
94
- mountUpdates(scope);
95
- });
96
- }
@@ -1,99 +0,0 @@
1
- import { maxTokensParameter } from './stream.js';
2
-
3
- const CONCURRENCY = 3;
4
- const PROBE_TIMEOUT_MS = 18_000;
5
- const BATCH_COOLDOWN_MS = 45_000;
6
- const PROBE_MAX_TOKENS = 512;
7
-
8
- async function probeModel(stream, model, lifetime) {
9
- const timeout = AbortSignal.timeout(PROBE_TIMEOUT_MS);
10
- const signal = AbortSignal.any([lifetime, timeout]);
11
- try {
12
- const options = {
13
- provider: model.provider,
14
- model: model.id,
15
- messages: [{ role: 'user', content: [{ type: 'text', text: 'Reply only with OK.' }] }],
16
- signal,
17
- ...(maxTokensParameter(model.supportedParameters) ? { maxTokens: PROBE_MAX_TOKENS } : {}),
18
- };
19
- let hasText = false;
20
- for await (const chunk of stream(options, model)) {
21
- if (chunk.type === 'text-delta' && chunk.text.trim()) hasText = true;
22
- if (chunk.type !== 'finish') continue;
23
- const { kind, failure } = chunk.reason;
24
- if (timeout.aborted) return { status: 'unavailable', reason: 'TIMEOUT' };
25
- if (hasText && (kind === 'stop' || kind === 'max-tokens')) return { status: 'available' };
26
- return { status: 'unavailable', reason: failure?.code ?? 'EMPTY_RESPONSE', retryAfterMs: failure?.providerRetryAfterMs };
27
- }
28
- } catch {
29
- // An exception before a finish is equivalent to a broken stream for the probe.
30
- }
31
- return { status: 'unavailable', reason: timeout.aborted ? 'TIMEOUT' : 'TRANSPORT' };
32
- }
33
-
34
- export function createModelAvailability({ stream, signal, now = Date.now }) {
35
- let results = new Map();
36
- let checking = false;
37
- let retryAt = 0;
38
-
39
- function snapshot() {
40
- return {
41
- checking,
42
- ...(retryAt > now() ? { retryAt } : {}),
43
- models: [...results.values()].map(({ blockedUntil, ...result }) => result),
44
- };
45
- }
46
-
47
- async function run(queue) {
48
- let next = 0;
49
- async function worker() {
50
- while (next < queue.length && !signal.aborted) {
51
- const model = queue[next++];
52
- const startedAt = performance.now();
53
- const { retryAfterMs, ...result } = await probeModel(stream, model, signal);
54
- const elapsedMs = Math.round(performance.now() - startedAt);
55
- const checkedAt = now();
56
- if (signal.aborted) return;
57
- const blockedUntil = result.reason === 'RATE_LIMIT' && retryAfterMs > 0 ? checkedAt + retryAfterMs : 0;
58
- results.set(model.id, { id: model.id, ...result, elapsedMs, checkedAt, blockedUntil });
59
- }
60
- }
61
-
62
- try {
63
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
64
- } finally {
65
- checking = false;
66
- retryAt = now() + BATCH_COOLDOWN_MS;
67
- if (signal.aborted) results.clear();
68
- }
69
- }
70
-
71
- function start(models) {
72
- const startedAt = now();
73
- if (checking || retryAt > startedAt || signal.aborted) return snapshot();
74
-
75
- const nextResults = new Map();
76
- const queue = [];
77
- for (const model of models) {
78
- if (nextResults.has(model.id)) continue;
79
- const previous = results.get(model.id);
80
- if (previous?.blockedUntil > startedAt) {
81
- nextResults.set(model.id, previous);
82
- } else {
83
- nextResults.set(model.id, { id: model.id, status: 'checking' });
84
- queue.push(model);
85
- }
86
- }
87
- results = nextResults;
88
- if (!queue.length) {
89
- retryAt = results.size ? Math.min(...[...results.values()].map(result => result.blockedUntil)) : 0;
90
- return snapshot();
91
- }
92
-
93
- checking = true;
94
- void run(queue);
95
- return snapshot();
96
- }
97
-
98
- return { snapshot, start };
99
- }
@@ -1,111 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { mkdir, readdir, rm, writeFile } from 'node:fs/promises';
3
- import { homedir } from 'node:os';
4
- import { join, resolve } from 'node:path';
5
- import { KiloCatalogError } from './catalog.js';
6
- import { createModelAvailability } from './model-availability.js';
7
- import { streamKilo } from './stream.js';
8
-
9
- function harnessHome() {
10
- const home = process.env.DSH_HOME?.trim();
11
- if (!home) return join(homedir(), '.dsh');
12
- if (home === '~') return homedir();
13
- return /^~[/\\]/.test(home) ? resolve(homedir(), home.slice(2)) : resolve(home);
14
- }
15
-
16
- function modelKey(id) {
17
- return createHash('sha256').update(id).digest('hex');
18
- }
19
-
20
- export function createModelVisibility(profileDir = harnessHome()) {
21
- const directory = join(profileDir, 'dsh-free-model', 'disabled-models');
22
- return {
23
- async readDisabled() {
24
- const entries = await readdir(directory).catch(error => {
25
- if (error.code === 'ENOENT') return [];
26
- throw error;
27
- });
28
- const keys = new Set(entries);
29
- return id => keys.has(modelKey(id));
30
- },
31
-
32
- async setEnabled(id, enabled) {
33
- // A file per model lets concurrent saves update different switches independently.
34
- const marker = join(directory, modelKey(id));
35
- if (enabled) {
36
- await rm(marker, { force: true });
37
- } else {
38
- await mkdir(directory, { recursive: true, mode: 0o700 });
39
- await writeFile(marker, '', { flag: 'wx', mode: 0o600 }).catch(error => {
40
- if (error.code !== 'EEXIST') throw error;
41
- });
42
- }
43
- },
44
- };
45
- }
46
-
47
- function json(body, status = 200) {
48
- return Response.json(body, { status, headers: { 'cache-control': 'no-store' } });
49
- }
50
-
51
- export function registerModelManagement(ctx, { catalog, visibility, fetch, onChange }) {
52
- const lifetime = new AbortController();
53
- ctx.effect(() => () => lifetime.abort(), 'dsh-free-model: management lifetime');
54
- const availability = createModelAvailability({
55
- signal: lifetime.signal,
56
- stream: (options, model) => streamKilo(options, model, fetch),
57
- });
58
- ctx.connection.fetch.register({
59
- path: '/api/dsh-free-model/models',
60
- methods: ['GET', 'POST'],
61
- requestBody: 'buffered',
62
- async fetch(request) {
63
- const signal = AbortSignal.any([request.signal, lifetime.signal]);
64
- try {
65
- if (request.method === 'GET') {
66
- const refresh = new URL(request.url).searchParams.get('refresh') === '1';
67
- const [models, isDisabled] = await Promise.all([catalog.listModels(signal, { refresh }), visibility.readDisabled()]);
68
- if (refresh && !lifetime.signal.aborted) onChange();
69
- return json({
70
- models: models.map(({ id, name }) => ({ id, name, enabled: !isDisabled(id) })),
71
- availability: availability.snapshot(),
72
- });
73
- }
74
-
75
- const input = await request.json().catch(() => undefined);
76
- if (typeof input?.id !== 'string' || !input.id.trim() || typeof input.enabled !== 'boolean') {
77
- return json({ error: '请提供有效的模型和开关状态。' }, 400);
78
- }
79
- const { id, enabled } = input;
80
- if (!await catalog.getModel(id, signal)) {
81
- return json({ error: '模型已不在 Kilo 免费目录中,请刷新列表。' }, 404);
82
- }
83
- signal.throwIfAborted();
84
- await visibility.setEnabled(id, enabled);
85
- if (!lifetime.signal.aborted) onChange();
86
- return json({ id, enabled });
87
- } catch (error) {
88
- if (error instanceof KiloCatalogError) return json({ error: error.message }, 502);
89
- return json({ error: request.method === 'GET' ? '无法读取模型开关。' : '无法保存模型开关,请重试。' }, 500);
90
- }
91
- },
92
- });
93
- ctx.connection.fetch.register({
94
- path: '/api/dsh-free-model/models/availability',
95
- methods: ['GET', 'POST'],
96
- requestBody: 'buffered',
97
- async fetch(request) {
98
- const current = availability.snapshot();
99
- if (request.method === 'GET' || current.checking || current.retryAt > Date.now()) return json(current);
100
-
101
- try {
102
- const signal = AbortSignal.any([request.signal, lifetime.signal]);
103
- const models = await catalog.listModels(signal);
104
- signal.throwIfAborted();
105
- return json(availability.start(models), 202);
106
- } catch (error) {
107
- return json({ error: error instanceof KiloCatalogError ? error.message : '无法启动模型检测,请重试。' }, 502);
108
- }
109
- },
110
- });
111
- }
package/stream.js DELETED
@@ -1,382 +0,0 @@
1
- import { KILO_BASE_URL } from './catalog.js';
2
-
3
- const GENERATION_TIMEOUT_MS = 120_000;
4
- export const DEFAULT_MAX_TOKENS = 8_192;
5
- const MAX_EVENT_CHARS = 1024 * 1024;
6
- const MAX_RESPONSE_CHARS = 4 * 1024 * 1024;
7
-
8
- class StreamFailure extends Error {
9
- constructor(code, message, details = {}) {
10
- super(message);
11
- this.failure = { code, message, ...details };
12
- }
13
- }
14
-
15
- function retryAfterMs(value) {
16
- if (!value) return undefined;
17
- const delay = /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1000 : Date.parse(value) - Date.now();
18
- return Number.isSafeInteger(delay) && delay > 0 ? delay : undefined;
19
- }
20
-
21
- function upstreamFailure(code, retryAfter) {
22
- const status = /^\d{3}$/.test(String(code)) ? Number(code) : undefined;
23
- const detail = status === undefined ? {} : { status };
24
-
25
- switch (status) {
26
- case 401:
27
- case 403:
28
- return new StreamFailure('AUTH', '这个模型当前不接受 Kilo 匿名访问。', detail);
29
- case 402:
30
- return new StreamFailure('QUOTA', 'Kilo 当前没有可用于此请求的免费额度。', detail);
31
- case 404:
32
- return new StreamFailure('MODEL_UNAVAILABLE', 'Kilo 当前无法提供这个模型。', detail);
33
- case 408:
34
- case 504:
35
- return new StreamFailure('TIMEOUT', 'Kilo 响应超时,请稍后再试。', detail);
36
- case 429: {
37
- const delay = retryAfterMs(retryAfter);
38
- return new StreamFailure('RATE_LIMIT', 'Kilo 免费模型暂时限流,请稍后再试。', {
39
- ...detail,
40
- ...(delay === undefined ? {} : { providerRetryAfterMs: delay }),
41
- });
42
- }
43
- default:
44
- if (status >= 400 && status < 500) {
45
- return new StreamFailure('INVALID_REQUEST', 'Kilo 拒绝了这次请求。', detail);
46
- }
47
- if (code === 'context_length_exceeded') {
48
- return new StreamFailure('CONTEXT_WINDOW_EXCEEDED', '这次对话内容超过了模型的上下文限制。');
49
- }
50
- return new StreamFailure('SERVER', 'Kilo 当前无法完成这次请求。', detail);
51
- }
52
- }
53
-
54
- function messageText(message) {
55
- const parts = [];
56
- for (const block of message.content) {
57
- if (block.type === 'text') parts.push(block.text);
58
- else if (block.type === 'image') {
59
- if (!block.offloaded) {
60
- throw new StreamFailure('UNSUPPORTED_CONTENT', '这个 Kilo 免费模型当前只接收文本。');
61
- }
62
- parts.push('[该图片已从模型上下文移出]');
63
- } else if (block.type === 'file') {
64
- throw new StreamFailure('UNSUPPORTED_CONTENT', '这个 Kilo 免费模型当前只接收文本。');
65
- }
66
- }
67
- return parts.join('\n');
68
- }
69
-
70
- function convertMessages(options) {
71
- const messages = options.system ? [{ role: 'system', content: options.system }] : [];
72
- const answered = new Set(options.messages.filter(message => message.role === 'tool')
73
- .map(message => message.toolCallId));
74
- const sent = new Set();
75
-
76
- for (const message of options.messages) {
77
- const content = messageText(message);
78
- if (message.role === 'assistant') {
79
- const calls = message.content.filter(block => block.type === 'tool-call' && answered.has(block.id));
80
- const tool_calls = calls.map(block => {
81
- sent.add(block.id);
82
- return { id: block.id, type: 'function', function: { name: block.name, arguments: block.arguments } };
83
- });
84
- if (content || tool_calls.length) {
85
- messages.push({ role: 'assistant', content: content || null, ...(tool_calls.length ? { tool_calls } : {}) });
86
- }
87
- } else if (message.role === 'tool') {
88
- if (sent.delete(message.toolCallId)) {
89
- messages.push({ role: 'tool', content, tool_call_id: message.toolCallId });
90
- }
91
- } else if (content) {
92
- messages.push({ role: message.role === 'developer' ? 'system' : message.role, content });
93
- }
94
- }
95
- return messages;
96
- }
97
-
98
- export function maxTokensParameter(supportedParameters) {
99
- if (supportedParameters.includes('max_tokens')) return 'max_tokens';
100
- if (supportedParameters.includes('max_completion_tokens')) return 'max_completion_tokens';
101
- return undefined;
102
- }
103
-
104
- function requestBody(options, model) {
105
- const supported = model.supportedParameters;
106
- const tools = options.tools ?? [];
107
- if (tools.length && !supported.includes('tools')) {
108
- throw new StreamFailure('INVALID_REQUEST', '这个 Kilo 免费模型不支持工具调用。');
109
- }
110
- if (options.temperature !== undefined && !supported.includes('temperature')) {
111
- throw new StreamFailure('INVALID_REQUEST', '这个 Kilo 免费模型不支持自定义采样温度。');
112
- }
113
- if (options.stop?.length && !supported.includes('stop')) {
114
- throw new StreamFailure('INVALID_REQUEST', '这个 Kilo 免费模型不支持自定义停止词。');
115
- }
116
-
117
- const messages = convertMessages(options);
118
- if (!messages.length) throw new StreamFailure('INVALID_REQUEST', '请先输入一条消息。');
119
- const body = { model: model.id, messages, stream: true };
120
- const tokenParameter = maxTokensParameter(supported);
121
- if (tokenParameter) {
122
- body[tokenParameter] = Math.min(options.maxTokens ?? DEFAULT_MAX_TOKENS, model.maxCompletionTokens ?? Infinity);
123
- } else if (options.maxTokens !== undefined) {
124
- throw new StreamFailure('INVALID_REQUEST', '这个 Kilo 免费模型不支持设置最大输出长度。');
125
- }
126
- if (options.temperature !== undefined) body.temperature = options.temperature;
127
- if (options.stop?.length) body.stop = options.stop;
128
- if (tools.length) {
129
- body.tools = tools.map(({ name, description, parameters }) => ({
130
- type: 'function', function: { name, description, parameters },
131
- }));
132
- }
133
- if (options.reasoningEffort !== undefined) {
134
- if (!supported.includes('reasoning')) {
135
- throw new StreamFailure('INVALID_REQUEST', '这个 Kilo 免费模型不支持自定义推理强度。');
136
- }
137
- body.reasoning = { effort: options.reasoningEffort === 'off' ? 'none' : options.reasoningEffort };
138
- }
139
- return body;
140
- }
141
-
142
- /** Parse incremental SSE data records, including records split across network reads. */
143
- async function* eventData(body) {
144
- const decoder = new TextDecoder();
145
- let buffer = '';
146
- let data = [];
147
- let eventChars = 0;
148
- for await (const chunk of body) {
149
- buffer += decoder.decode(chunk, { stream: true });
150
- const lines = buffer.split('\n');
151
- buffer = lines.pop();
152
- for (const rawLine of lines) {
153
- const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
154
- if (line === '') {
155
- if (data.length) yield data.join('\n');
156
- data = [];
157
- eventChars = 0;
158
- } else if (line.startsWith('data:')) {
159
- const value = line.slice(line[5] === ' ' ? 6 : 5);
160
- eventChars += value.length + 1;
161
- if (eventChars > MAX_EVENT_CHARS) {
162
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回的数据帧过大。');
163
- }
164
- data.push(value);
165
- }
166
- }
167
- if (buffer.length > MAX_EVENT_CHARS) {
168
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回的数据帧过大。');
169
- }
170
- }
171
- }
172
-
173
- function parseEvent(data) {
174
- try {
175
- const event = JSON.parse(data);
176
- if (event && typeof event === 'object' && !Array.isArray(event)) return event;
177
- } catch {
178
- // Never include upstream data in error messages.
179
- }
180
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回了无法识别的数据帧。');
181
- }
182
-
183
- function isTokenCount(value) {
184
- return Number.isSafeInteger(value) && value >= 0;
185
- }
186
-
187
- function mapUsage(raw) {
188
- const { prompt_tokens: prompt, completion_tokens: completion } = raw ?? {};
189
- if (!isTokenCount(prompt) || !isTokenCount(completion)) return undefined;
190
-
191
- const cached = raw.prompt_tokens_details?.cached_tokens;
192
- const reasoning = raw.completion_tokens_details?.reasoning_tokens;
193
- const total = prompt + completion;
194
- const cacheRead = isTokenCount(cached) && cached <= prompt ? cached : 0;
195
- return {
196
- inputTokens: prompt - cacheRead,
197
- outputTokens: completion,
198
- ...(Number.isSafeInteger(total) ? { totalTokens: total } : {}),
199
- ...(cacheRead ? { cacheReadTokens: cacheRead } : {}),
200
- ...(isTokenCount(reasoning) && reasoning <= completion ? { reasoningTokens: reasoning } : {}),
201
- };
202
- }
203
-
204
- function toolBlock(block) {
205
- if (!block.id || !block.name) {
206
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回了身份不完整的工具调用。');
207
- }
208
- try {
209
- const parsed = JSON.parse(block.arguments);
210
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
211
- return { type: 'tool-call', id: block.id, name: block.name, arguments: block.arguments };
212
- }
213
- } catch {
214
- // Incomplete and invalid JSON tool calls must never be completed synthetically.
215
- }
216
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回了不完整的工具参数。');
217
- }
218
-
219
- function mapFinishReason(reason, blocks, usage, contextWindow) {
220
- switch (reason) {
221
- case 'stop':
222
- if (!blocks.length) throw new StreamFailure('EMPTY_RESPONSE', 'Kilo 没有返回文本。');
223
- return { kind: 'stop' };
224
- case 'length':
225
- if (contextWindow && usage?.totalTokens >= contextWindow && usage.outputTokens === 0) {
226
- throw new StreamFailure('CONTEXT_WINDOW_EXCEEDED', '这次对话内容超过了模型的上下文限制。');
227
- }
228
- return { kind: 'max-tokens' };
229
- case 'tool_calls':
230
- if (!blocks.some(block => block.type === 'tool-call')) {
231
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 没有返回完整的工具调用。');
232
- }
233
- return { kind: 'tool-calls' };
234
- case 'content_filter':
235
- throw new StreamFailure('INVALID_REQUEST', 'Kilo 的内容过滤终止了这次回复。');
236
- default:
237
- if (reason) throw new StreamFailure('SERVER', 'Kilo 提前终止了这次回复。');
238
- throw new StreamFailure('TRANSPORT', 'Kilo 的连接在回复完成前断开。');
239
- }
240
- }
241
-
242
- async function* translate(body, model, signal, retryAfter) {
243
- const blocks = [];
244
- const tools = new Map();
245
- let text;
246
- let reasoning;
247
- let responseChars = 0;
248
- let usage;
249
- let finishReason;
250
-
251
- function open(content) {
252
- const block = { ...content, index: blocks.length };
253
- blocks.push(block);
254
- return block;
255
- }
256
-
257
- function count(value) {
258
- responseChars += value.length;
259
- if (responseChars > MAX_RESPONSE_CHARS) {
260
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回的内容过大。');
261
- }
262
- }
263
-
264
- for await (const data of eventData(body)) {
265
- signal.throwIfAborted();
266
- if (data.trim() === '[DONE]') break;
267
- if (!data.trim()) continue;
268
-
269
- const event = parseEvent(data);
270
- if (event.error) throw upstreamFailure(event.error.code, retryAfter);
271
- if (event.usage) usage = mapUsage(event.usage) ?? usage;
272
- const choice = event.choices?.[0];
273
- if (!choice) continue;
274
- const delta = choice.delta ?? {};
275
-
276
- const thought = delta.reasoning ?? delta.reasoning_content;
277
- if (typeof thought === 'string' && thought) {
278
- if (!reasoning) {
279
- reasoning = open({ type: 'reasoning', text: '' });
280
- yield { type: 'block-start', index: reasoning.index, blockType: 'reasoning' };
281
- }
282
- count(thought);
283
- reasoning.text += thought;
284
- yield { type: 'reasoning-delta', index: reasoning.index, text: thought };
285
- }
286
- if (typeof delta.content === 'string' && delta.content) {
287
- if (!text) {
288
- text = open({ type: 'text', text: '' });
289
- yield { type: 'block-start', index: text.index, blockType: 'text' };
290
- }
291
- count(delta.content);
292
- text.text += delta.content;
293
- yield { type: 'text-delta', index: text.index, text: delta.content };
294
- }
295
-
296
- const toolCalls = delta.tool_calls ?? [];
297
- if (!Array.isArray(toolCalls)) {
298
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回了无效的工具调用。');
299
- }
300
- for (const call of toolCalls) {
301
- if (!Number.isSafeInteger(call?.index) || call.index < 0 || call.index > 128) {
302
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回了无效的工具调用。');
303
- }
304
- let block = tools.get(call.index);
305
- if (!block) {
306
- block = open({ type: 'tool-call', id: '', name: '', arguments: '' });
307
- tools.set(call.index, block);
308
- yield { type: 'block-start', index: block.index, blockType: 'tool-call' };
309
- }
310
- if (typeof call.id === 'string' && call.id) block.id ||= call.id;
311
- if (typeof call.function?.name === 'string' && call.function.name) block.name ||= call.function.name;
312
- const fragment = call.function?.arguments ?? '';
313
- if (typeof fragment !== 'string') {
314
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 返回了无效的工具参数。');
315
- }
316
- count(fragment);
317
- block.arguments += fragment;
318
- yield {
319
- type: 'tool-call-delta',
320
- index: block.index,
321
- id: block.id,
322
- ...(block.name ? { name: block.name } : {}),
323
- argumentsDelta: fragment,
324
- };
325
- }
326
- if (typeof choice.finish_reason === 'string') finishReason = choice.finish_reason;
327
- }
328
-
329
- signal.throwIfAborted();
330
- const reason = mapFinishReason(finishReason, blocks, usage, model.context?.contextWindow);
331
- if (tools.size && reason.kind === 'stop') {
332
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 未确认工具调用已完成。');
333
- }
334
- const completed = blocks.flatMap(block => {
335
- // On length truncation, leave unconfirmed tool calls open so the host can drop them.
336
- if (block.type === 'tool-call' && reason.kind !== 'tool-calls') return [];
337
- const content = block.type === 'tool-call' ? toolBlock(block) : { type: block.type, text: block.text };
338
- return [{ type: 'block-end', index: block.index, block: content }];
339
- });
340
- yield* completed;
341
- if (usage) yield { type: 'usage', usage };
342
- yield { type: 'finish', reason };
343
- }
344
-
345
- /** Translate one authenticated-free Kilo streaming request into DeepSeek Harness chunks. */
346
- export async function* streamKilo(options, model, fetchImpl = fetch, attribution = {}) {
347
- const timeout = AbortSignal.timeout(GENERATION_TIMEOUT_MS);
348
- const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
349
- try {
350
- signal.throwIfAborted();
351
- const response = await fetchImpl(`${KILO_BASE_URL}/chat/completions`, {
352
- method: 'POST',
353
- headers: {
354
- 'content-type': 'application/json',
355
- accept: 'text/event-stream',
356
- 'user-agent': attribution['user-agent'] ?? 'dsh-open-model',
357
- },
358
- body: JSON.stringify(requestBody(options, model)),
359
- redirect: 'error',
360
- signal,
361
- });
362
- const retryAfter = response.headers.get('retry-after');
363
- if (!response.ok) {
364
- await response.body?.cancel().catch(() => {});
365
- throw upstreamFailure(response.status, retryAfter);
366
- }
367
- if (!response.body || !response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream')) {
368
- await response.body?.cancel().catch(() => {});
369
- throw new StreamFailure('MALFORMED_RESPONSE', 'Kilo 没有返回预期的流式回复。');
370
- }
371
- yield* translate(response.body, model, signal, retryAfter);
372
- } catch (error) {
373
- if (options.signal?.aborted) {
374
- yield { type: 'finish', reason: { kind: 'aborted', failure: { code: 'ABORTED', message: '已取消 Kilo 请求。' } } };
375
- return;
376
- }
377
- const failure = error instanceof StreamFailure ? error.failure : timeout.aborted
378
- ? { code: 'TIMEOUT', message: 'Kilo 响应超时,请稍后再试。' }
379
- : { code: 'TRANSPORT', message: '暂时无法连接 Kilo,请检查网络后重试。' };
380
- yield { type: 'finish', reason: { kind: 'error', failure } };
381
- }
382
- }