merge: update the MCP manager with master

This commit is contained in:
gengruilin committed 2026-10-20 15:45:33 +08:00
commit 4e796f736e
569 files changed
+13876 -2216

No files matched your search

@@ -0,0 +1,10 @@
/** Frame one text or tool response from the local Messages endpoint. */
export function messagesResponse(content: Record<string, unknown>, stopReason: 'end_turn' | 'max_tokens' | 'tool_use'): string {
return [
{ type: 'message_start', message: { id: 'sdk-smoke-response', model: 'deepseek-v4-pro', usage: { input_tokens: 3, output_tokens: 0 } } },
{ type: 'content_block_start', index: 0, content_block: content },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: stopReason }, usage: { output_tokens: 1 } },
{ type: 'message_stop' },
].map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join('')
}
@@ -0,0 +1,10 @@
/** Freeze only the isolated runtime's wall clock before reminder activation starts. */
export function apply(ctx) {
const original = Date.now
const now = Number(process.env.DSH_TEST_SCHEDULE_NOW)
ctx.effect(() => {
Date.now = () => now
return () => { Date.now = original }
})
ctx.provide('sdkTestClock', { ready: true })
}
@@ -10,6 +10,8 @@ import { execa } from 'execa'
import { describe, expect, it, onTestFinished } from 'vitest'
import { workspaceDependencyPaths, type PrimaryRuntimeManifest } from '@deepseek-ai/dsh-tool-workspace-dependencies'
import { messagesResponse } from './fixtures/messages-response.ts'
const repoRoot = fileURLToPath(new URL('../../../../../', import.meta.url))
const launch = resolveExampleLaunch({
srcBin: fileURLToPath(new URL('../../../src/bin.ts', import.meta.url)),
@@ -17,16 +19,6 @@ const launch = resolveExampleLaunch({
})
const decompress = promisify(zstdDecompress)
/** Frame one text or tool response from the local Messages endpoint. */
function messagesResponse(content: Record<string, unknown>, stopReason: 'end_turn' | 'max_tokens' | 'tool_use'): string {
return [
{ type: 'message_start', message: { id: 'sdk-smoke-response', model: 'deepseek-v4-pro', usage: { input_tokens: 3, output_tokens: 0 } } },
{ type: 'content_block_start', index: 0, content_block: content },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: stopReason }, usage: { output_tokens: 1 } },
{ type: 'message_stop' },
].map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join('')
}
function waitForLine(
lines: string[],
@@ -66,7 +58,11 @@ describe('Python SDK dsh profile keyless smoke', () => {
{ label: 'reports max-token turns with mapping enabled through env', envValue: 'true', editorEnabled: false },
{ label: 'reports max-token turns with mapping disabled through env', envValue: 'false', editorEnabled: false },
{ label: 'allows an explicit patch to enable str_replace_editor', envValue: undefined, editorEnabled: true },
])('$label', async ({ envValue, editorEnabled }) => {
{ label: 'uses desktop tools through the PTC environment switch', envValue: undefined, editorEnabled: false, ptc: true },
])('$label', async (scenario) => {
const { envValue, editorEnabled } = scenario
const ptc = 'ptc' in scenario && scenario.ptc
const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-runtime-smoke-'))
const editorPatch = join(root, 'editor.patch.yml')
if (editorEnabled) await writeFile(editorPatch, [
@@ -103,6 +99,7 @@ describe('Python SDK dsh profile keyless smoke', () => {
DSH_HOME: join(root, '.dsh'),
DSH_PERMISSION_MODE: 'danger-full-access',
DSH_TELEMETRY_DISABLED: '1',
DSH_TOOLS_MODE: ptc ? 'ptc' : 'native',
DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
...(envValue === undefined ? {} : { DSH_MAX_TOKENS_AS_SUCCESS: envValue }),
@@ -176,9 +173,23 @@ describe('Python SDK dsh profile keyless smoke', () => {
const toolNames = tools.map(tool => tool.name)
expect(modelRequests[0]?.output_config).toEqual({ effort: 'max' })
expect(modelRequests[0]?.max_tokens).toBe(1234)
expect(toolNames).toEqual(expect.arrayContaining(['read', 'write', 'edit', 'web_fetch', 'web_search']))
expect(toolNames.includes('str_replace_editor')).toBe(editorEnabled)
expect(toolNames).not.toContain('list_subagent_models')
const expectedTools = ['read', 'write', 'edit', 'web_fetch', 'web_search', 'subagent', 'subagent_fork',
'present', 'ask_user_question', 'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update']
const requestText = JSON.stringify(modelRequests[0])
if (ptc) {
expect(toolNames).toEqual(['run_code'])
for (const tool of expectedTools) expect(requestText.includes(`${tool}:`), tool).toBe(true)
} else {
expect(toolNames).toEqual(expect.arrayContaining(expectedTools))
expect(toolNames.includes('str_replace_editor')).toBe(editorEnabled)
expect(toolNames).not.toContain('list_subagent_models')
}
for (const text of ['Tokens prefixed with @', 'Prefer showing the primary results',
'Time sampled while preparing']) {
expect(requestText.includes(text), text).toBe(true)
}
expect(requestText).not.toContain('Current DeepSeek Harness implementation checkout:')
expect(requestText).not.toContain('Current DeepSeek Harness Web GUI URL:')
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 3, method: 'shutdown' })}\n`)
const shutdown = await waitForLine(lines, value => value.id === 3, () => stderr)
@@ -0,0 +1,72 @@
/** Reminder activation must share SDK ownership and initialized model limits after process restart. */
import { createServer } from 'node:http'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { DeepSeekHarness } from '@deepseek-ai/dsh-sdk-client'
import { clearAmbientProxyEnv } from '../../../../../scripts/test-proxy-environment.ts'
import { expect, it, onTestFinished, vi } from 'vitest'
import { messagesResponse } from './fixtures/messages-response.ts'
it('delivers an overdue reminder with the SDK route and lets the client resume that same Session', async () => {
const root = await mkdtemp(join(tmpdir(), 'sdk-schedule-resume-'))
const patch = join(root, 'clock.patch.yml')
const fixture = fileURLToPath(new URL('./fixtures/schedule-clock.mjs', import.meta.url))
await writeFile(patch, [
'- insert:', ' - id: sdk-test-clock', ` name: ${JSON.stringify(fixture)}`,
'- id: sdk-jsonrpc-server', ' inject: [sdkAppStartup, loader, sdkTestClock]', '',
].join('\n'))
const requests: Record<string, unknown>[] = []
const restored: Record<string, unknown>[] = []
let restarting = false
const server = createServer((incoming, response) => {
let body = ''
incoming.setEncoding('utf8')
incoming.on('data', (chunk: string) => { body += chunk })
incoming.on('end', () => {
const request = JSON.parse(body) as Record<string, unknown>
requests.push(request)
if (restarting) restored.push(request)
const content = requests.length === 1 ? {
type: 'tool_use', id: 'create-reminder', name: 'schedule_create',
input: { title: 'Check SDK', prompt: 'Report the SDK reminder', after_seconds: 86400 },
} : { type: 'text', text: 'ready' }
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(messagesResponse(content, requests.length === 1 ? 'tool_use' : 'end_turn'))
})
})
const clients: DeepSeekHarness[] = []
onTestFinished(async () => {
try { await Promise.all(clients.map(client => client.close())) } finally {
try {
await new Promise<void>((resolve, reject) => {
server.close((error) => { if (error === undefined) resolve(); else reject(error) })
})
} finally { await rm(root, { recursive: true, force: true }) }
}
})
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('model fixture has no port')
const env = { ...process.env, DSH_TOOLS_MODE: 'native', DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1',
DEEPSEEK_API_KEY: 'keyless-schedule-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${String(address.port)}` }
clearAmbientProxyEnv(env)
const first = new DeepSeekHarness({ cwd: root, dshHome: join(root, '.dsh'), patches: [patch],
model: 'deepseek-v4-pro', maxTokens: 5678, initializeTimeoutMs: 30_000,
env: { ...env, DSH_TEST_SCHEDULE_NOW: String(Date.parse('2030-01-01T00:00:00Z')) } })
clients.push(first)
expect((await first.session('saved').run('Set a reminder')).finalResponse).toBe('ready')
expect(requests).toHaveLength(2)
await first.close()
restarting = true
const second = new DeepSeekHarness({ cwd: root, dshHome: join(root, '.dsh'), patches: [patch],
model: 'deepseek-v4-flash', maxTokens: 1234, initializeTimeoutMs: 30_000,
env: { ...env, DSH_TEST_SCHEDULE_NOW: String(Date.parse('2030-01-03T00:00:00Z')) } })
clients.push(second)
await second.start()
await vi.waitFor(() => { expect(restored).toHaveLength(1) }, { timeout: 30_000 })
expect(restored[0]).toMatchObject({ model: 'deepseek-v4-flash', max_tokens: 1234 })
const session = await second.resumeSession('saved')
expect((await session.run('Continue after the reminder')).finalResponse).toBe('ready')
})
@@ -0,0 +1,84 @@
/** Keyless SDK questions through the shipped profile, native tools, and both tool-call modes. */
import { createServer } from 'node:http'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { DeepSeekHarness, type SdkUserQuestionRequest } from '@deepseek-ai/dsh-sdk-client'
import { clearAmbientProxyEnv } from '../../../../../scripts/test-proxy-environment.ts'
import { expect, it, onTestFinished } from 'vitest'
import { messagesResponse } from './fixtures/messages-response.ts'
it.each([
{ mode: 'native', cancel: false }, { mode: 'ptc', cancel: false }, { mode: 'native', cancel: true },
])('handles a built-in question through $mode (cancel: $cancel)', async ({ mode, cancel }) => {
const root = await mkdtemp(join(tmpdir(), 'sdk-question-profile-'))
const requests: Record<string, unknown>[] = []
const questions = [{ id: 'format', question: 'Which format?', options: [{ label: 'CSV' }, { label: 'JSON' }] }]
const server = createServer((incoming, response) => {
let body = ''
incoming.setEncoding('utf8')
incoming.on('data', (chunk: string) => { body += chunk })
incoming.on('end', () => {
requests.push(JSON.parse(body) as Record<string, unknown>)
const tool = mode === 'ptc' ? {
type: 'tool_use', id: 'question-call', name: 'run_code', input: {
code: `return await tools.ask_user_question(${JSON.stringify({ questions })});`, description: 'Ask which output format to use',
},
} : { type: 'tool_use', id: 'question-call', name: 'ask_user_question', input: { questions } }
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(messagesResponse(requests.length === 1 ? tool : { type: 'text', text: 'answer received' },
requests.length === 1 ? 'tool_use' : 'end_turn'))
})
})
const state: { harness?: DeepSeekHarness } = {}
onTestFinished(async () => {
try { await state.harness?.close() } finally {
try {
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error === undefined) resolve()
else reject(error)
})
})
}
finally { await rm(root, { recursive: true, force: true }) }
}
})
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('model fixture has no port')
const env = { ...process.env, DSH_TOOLS_MODE: mode, DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1',
DEEPSEEK_API_KEY: 'keyless-question-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${String(address.port)}` }
clearAmbientProxyEnv(env)
const seen: SdkUserQuestionRequest[] = []
const entered = Promise.withResolvers<AbortSignal>()
const harness = state.harness = new DeepSeekHarness({
cwd: root, dshHome: join(root, '.dsh'), env, model: 'deepseek-v4-pro', maxTokens: 1234, initializeTimeoutMs: 30_000,
onUserQuestion: async (request, { signal }) => {
expect(signal.aborted).toBe(false)
seen.push(request)
entered.resolve(signal)
if (cancel) return new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => { reject(new Error('question cancelled')) }, { once: true })
})
return { answers: [{ id: 'format', selected: ['CSV'] }] }
},
})
const pending = harness.session('question-session').run('Ask which output format to use')
if (cancel) {
const settled = pending.catch(() => undefined)
const signal = await entered.promise
await harness.close()
await settled
expect(signal.aborted).toBe(true)
expect(requests).toHaveLength(1)
return
}
const result = await pending
expect(seen).toEqual([{ requestId: expect.any(String) as string, sessionId: 'question-session', questions }])
expect(result.finalResponse).toBe('answer received')
expect(requests).toHaveLength(2)
expect(requests[1]?.max_tokens).toBe(1234)
expect(JSON.stringify(requests[1]?.messages)).toContain('CSV')
expect(result.events.some(event => event.type === 'tool/result' && event.data.error !== undefined)).toBe(false)
})