内网 使用deepseek harness注意事项

前提:

内网

1. Node版本大于22.18.0

2. 内部自签证书的模型提供商,需配置认证证书,即配置环境变量NODE_EXTRA_CA_CERTS,避免请求网络请求TLS(SELF_SIGNED_CERT_IN_CHAIN)

3. 在C盘用户文件夹,网页端,配置.dsh\profiles\web\cordis.patch.yml,桌面版,配置.dsh\profiles\desktop\cordis.patch.yml,用于自定义模型提供商,自定义请求头,指定模型,指定窗口大小 

# Your patch layer for this dsh profile, applied after every bundle layer:
# a top-level YAML array of loader patch entries (id-targeted config
# overrides, disables, and insert lists; `!!js` expressions allowed).

# Route the harness through the existing CUS OpenAI-compatible gateway.
- id: llm-pi-ai
  config:
    providers:
      cus:
        displayName: CUS DeepSeek
        api: openai-completions
        baseURL: https://xxxxxx:xxx/v1
        headers:
          Authorization: Bearer cus
          X-CusHeader: TESTSSSS
        compat:
          thinkingFormat: deepseek
          supportsDeveloperRole: false
          maxTokensField: max_completion_tokens
        models:
          - id: deepseek-v4.1-flash-1017
            name: DeepSeek V4.1 Flash 1017
            contextWindow: 350000
            maxTokens: 65536
            input:
              - text
            reasoningEfforts:
              off:
              low: low
              high: high
              max: max
        reasoning: high

# Make the CUS route the default for new sessions.
- id: agent-default-model
  config:
    provider: cus
    model: deepseek-v4.1-flash-1017
- id: ui-settings-general
  name: "@deepseek-ai/dsh-client-ui-settings-general"
  config:
    welcomeNoticeVersion: 2026-09-28.1

4. 自定义Skill如涉及到自定义环境变量,需提前配置,避免Skill调用时发现未配置所需环境变量

5. 部分设备可能存在异常,需手动解锁 : 

Unblock-File -Path D:\xxx\npx.ps1 

 临时运行:

npx @deepseek-ai/dsh web

使用桌面版,且仅使用内部模型提供商,跳过deepseekharness的默认登录即可

6. 如果使用语言转文字模型,且内网无法下载模型,可使用脚本,在外网下载所需模型(这里使用hf-mirror加速),然后复制到内网服务器中

download.ps1

$out = "$env:USERPROFILE\Desktop\sensevoice-model"
New-Item -ItemType Directory -Force $out | Out-Null
$base = 'https://hf-mirror.com/csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17/resolve/2365baeacb507f821a0c8120fcee3d484dba7a07'
curl.exe -L --fail --retry 3 "$base/model.int8.onnx" -o "$out\model.int8.onnx"
curl.exe -L --fail --retry 3 "$base/tokens.txt" -o "$out\tokens.txt"
curl.exe -L --fail --retry 3 "https://hf-mirror.com/csukuangfj/vad/resolve/fba88cd2e921609e7675c3aaf51e0b9b295da4bc/silero_vad.onnx" -o "$out\silero_vad.onnx"

# 校验大小
Get-ChildItem $out | Select-Object Name, Length
# 校验哈希
Get-FileHash "$out\model.int8.onnx" -Algorithm SHA256
Get-FileHash "$out\tokens.txt" -Algorithm SHA256
Get-FileHash "$out\silero_vad.onnx" -Algorithm SHA256

 在插件设定中,开启语音输入功能后,在 cordis.patch.yml 中指定模型相关设定

# 语音输入:使用 D 盘的离线 SenseVoice 模型(显式路径,不再联网下载)。
- id: speech-to-text-sensevoice
  config:
    dataRoot: D:/xxx/workspace/dsh-models
    modelDirectory: D:/xxx/workspace/dsh-models
    vadModelPath: D:/xxx/workspace/dsh-models/silero_vad.onnx

  

内网如果网络限制较严格,必须通过代理去访问外部网络,则需要自定义网络访问工具的插件,以及指定网络搜索的provider为内网地址(host级别,影响全局web服务)

注意:web_fetch工具,是Client直接访问url,所以需要走全局公网代理。模型对话与web_search工具,都使用AI 网关(内部的模型提供商)

.env文件配置内网访问公网的代理:

# DeepSeek Harness / Harness-home environment layer.
# Loaded at launch by dsh-app-boot's loadLayeredEnv() from $DSH_HOME/.env.
# Only the four proxy names may be set here; bootstrap names such as
# NODE_EXTRA_CA_CERTS are refused here and must stay exported in the user
# environment (they already are on this machine).
#
# Corporate egress: same endpoint the opencode wrapper exports.
HTTP_PROXY=http://xxxx:8080
HTTPS_PROXY=http://xxxx:8080
# .内网服务后缀 keeps internal gateways (e.g. 内网服务后缀:8080)
# on the direct route; loopback is always bypassed by the harness as well.
NO_PROXY=localhost,127.0.0.1,::1,.内网服务后缀,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16

如果内网的AI网关,与 DeepSeekHarness支持的协议、接口不一致,则需要进行调整,也就是前文所述的自定义网络搜索工具(主要是协议兼容,以及接口替换)不同的模型提供商,可能不同的地方不一样,需要针对性调整。插件文件需放到.dsh/plugins/路径

cus-web-search.mjs

// Local DeepSeek Harness web-search provider backed by the internal cus gateway's
// OpenAI Responses API (`/v1/responses` + hosted `web_search` tool).
//
// Mounted by the desktop profile patch (~/.dsh/profiles/desktop/cordis.patch.yml):
//   - insert:
//       - id: web-cus-search
//         name: 'file:///C:/Users/xxx/.dsh/plugins/cus-web-search.mjs'
//   - id: web
//     config: { searchProvider: cus-responses, fetchProvider: http }
//
// Transport note: the global fetch fails for this call inside the Electron main
// process, so requests go through node:https (the global dispatcher is bypassed
// on purpose).

import { request as httpsRequest } from 'node:https';

export const name = 'web-cus-search';
export const inject = ['web'];

const BASE_URL = (process.env.cus_BASE_URL ?? 'https://内网模型提供商地址:8080').replace(/\/+$/, '');
const MODEL = process.env.cus_SEARCH_MODEL ?? 'deepseek-v4.1-flash-1017';
const TOKEN = process.env.cus_TOKEN ?? 'cus';
const USER = process.env.cus_USER ?? '自定义请求头-用户识别信息';
const TIMEOUT_MS = Number(process.env.cus_SEARCH_TIMEOUT_MS ?? 90000);
const PROVIDER_ID = 'cus-responses';

function headers() {
  const out = { 'content-type': 'application/json', authorization: `Bearer ${TOKEN}` };
  if (USER.length > 0) out['x-username'] = USER;
  return out;
}

function describeError(error) {
  if (error === undefined || error === null) return 'unknown';
  const cause = error.cause;
  const parts = [error.name ?? 'Error', error.message ?? String(error)];
  if (cause !== undefined && cause !== null) {
    parts.push(`cause=${cause.code ?? ''}${cause.code !== undefined ? ' ' : ''}${cause.message ?? ''}`.trim());
  }
  return parts.join(': ');
}

/** POST JSON through node:https, ignoring any global fetch/dispatcher state. */
function httpsJson(path, payload, signal) {
  const url = new URL(path, `${BASE_URL}/`);
  const body = Buffer.from(JSON.stringify(payload), 'utf8');
  return new Promise((resolve, reject) => {
    const req = httpsRequest(
      {
        protocol: url.protocol,
        hostname: url.hostname,
        port: url.port.length > 0 ? Number(url.port) : 443,
        path: `${url.pathname}${url.search}`,
        method: 'POST',
        headers: { ...headers(), 'content-length': body.length },
        timeout: TIMEOUT_MS,
      },
      (res) => {
        const chunks = [];
        res.on('data', (chunk) => chunks.push(chunk));
        res.on('end', () => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }));
        res.on('error', reject);
      },
    );
    req.on('timeout', () => req.destroy(new Error(`node:https timeout after ${TIMEOUT_MS} ms`)));
    req.on('error', reject);
    if (signal !== undefined) {
      const onAbort = () => req.destroy(new Error('aborted'));
      if (signal.aborted) onAbort();
      else signal.addEventListener('abort', onAbort, { once: true });
    }
    req.end(body);
  });
}

function dedupeSources(sources) {
  const seen = new Set();
  const out = [];
  for (const source of sources) {
    if (typeof source?.url !== 'string' || source.url.length === 0) continue;
    if (seen.has(source.url)) continue;
    seen.add(source.url);
    const entry = { url: source.url };
    if (typeof source.title === 'string' && source.title.length > 0) entry.title = source.title;
    if (typeof source.snippet === 'string' && source.snippet.length > 0) entry.snippet = source.snippet;
    if (typeof source.publishedAt === 'string' && source.publishedAt.length > 0) entry.publishedAt = source.publishedAt;
    out.push(entry);
  }
  return out;
}

function parseResponse(json) {
  const sources = [];
  const texts = [];
  for (const item of Array.isArray(json?.output) ? json.output : []) {
    if (item?.type === 'web_search_call') {
      for (const source of Array.isArray(item.action?.sources) ? item.action.sources : []) {
        if (source?.type === 'url' || typeof source?.url === 'string') sources.push({ url: source.url });
      }
      continue;
    }
    if (item?.type === 'message') {
      for (const block of Array.isArray(item.content) ? item.content : []) {
        if (block?.type === 'output_text' && typeof block.text === 'string') texts.push(block.text);
        if (Array.isArray(block?.annotations)) {
          for (const annotation of block.annotations) {
            if (annotation?.type === 'url_citation' && typeof annotation.url === 'string') {
              sources.push({ url: annotation.url, title: annotation.title });
            }
          }
        }
      }
    }
  }
  return { content: texts.join('\n\n').trim(), sources: dedupeSources(sources) };
}

async function search(request, signal) {
  const query = String(request?.query ?? '').trim();
  if (query.length === 0) throw new Error('cus-responses search: empty query');

  const prompt =
    `Use the web_search tool to search for: ${query}\n` +
    'Then answer concisely using the search results, and list the source URLs you used.';
  const payload = { model: MODEL, input: prompt, tools: [{ type: 'web_search' }], max_output_tokens: 1200 };

  const diagnostics = [];

  // Attempt 1: global fetch (what the rest of the harness uses).
  let response;
  try {
    response = await fetch(`${BASE_URL}/v1/responses`, {
      method: 'POST',
      headers: headers(),
      body: JSON.stringify(payload),
      signal: AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)]),
    });
  } catch (error) {
    diagnostics.push(`global fetch -> ${describeError(error)}`);
  }

  // Attempt 2: node:https, bypassing any patched global dispatcher.
  if (response === undefined) {
    try {
      const result = await httpsJson('/v1/responses', payload, signal);
      if (result.status >= 200 && result.status < 300) {
        const parsed = parseResponse(JSON.parse(result.text));
        const maxResults = request?.maxResults;
        const capped = typeof maxResults === 'number' && maxResults >= 0 ? parsed.sources.slice(0, maxResults) : parsed.sources;
        return {
          ...(parsed.content.length > 0 ? { content: parsed.content } : {}),
          sources: capped,
          ...(capped.length < parsed.sources.length ? { truncated: true } : {}),
        };
      }
      diagnostics.push(`node:https -> HTTP ${result.status}: ${result.text.slice(0, 300)}`);
    } catch (error) {
      diagnostics.push(`node:https -> ${describeError(error)}`);
    }
    throw new Error(
      `cus-responses search failed (${BASE_URL}); ${diagnostics.join(' | ')}; ` +
        `NODE_EXTRA_CA_CERTS=${process.env.NODE_EXTRA_CA_CERTS ?? '(unset)'} electron=${process.versions.electron ?? '(none)'}`,
    );
  }

  if (!response.ok) {
    const body = await response.text().catch(() => '');
    throw new Error(`cus-responses search failed: HTTP ${response.status} from ${BASE_URL}/v1/responses: ${body.slice(0, 300)}`);
  }

  const json = await response.json();
  const { content, sources } = parseResponse(json);
  const maxResults = request?.maxResults;
  const capped = typeof maxResults === 'number' && maxResults >= 0 ? sources.slice(0, maxResults) : sources;
  return {
    ...(content.length > 0 ? { content } : {}),
    sources: capped,
    ...(capped.length < sources.length ? { truncated: true } : {}),
  };
}

export const provider = { id: PROVIDER_ID, available() { return true; }, search };

export function apply(ctx) {
  ctx.web.registerSearchProvider(provider);
}

同时,需在 cordis.patch.yml 中指定工具、以及provider

# Internal-only web search: mount the local CUS Responses search provider and select
# it. The official DeepSeek search endpoints (api.deepseek.com) are unreachable from
# this intranet; CUS's /v1/responses hosted web_search is reachable (verified).
- insert:
    - id: web-cus-search
      name: 'file:///C:/Users/xxx/.dsh/plugins/cus-web-search.mjs'
- id: web
  config:
    searchProvider: cus-responses
    fetchProvider: http

  

 

 

 

 

 

  

 

posted @ 2026-11-04 15:24  人间春风意  阅读(20)  评论(0)    收藏  举报