蓝色天空.知识 · 实践 · 创造
我的收藏
DeepSeek Harness 教程目录 33章
课程介绍
DeepSeek Harness / LEARN BY DOING

DeepSeek Harness 的能力定义、提供方和消费方

定位 ctx.shell 的三个角色,用两套配置观察执行规格的解析和替换前提。

学完这一章,你能够

  • 定位 ctx.shell 的三个角色,用两套配置观察执行规格的解析和替换前提。

把能力拆成三个角色

能力接缝连接服务约定、提供方和消费方。定义给出可依赖的服务名、类型与行为约定,提供方负责履行约定,调用方通过服务取得能力。一个包可以承担多个角色,也可以只承担其中一个。

拆包适合需要独立替换或维护的角色。定义可以提供抽象类,提供方实现接口并补上运行细节,消费方可以是模型工具,也可以是宿主、钩子或另一个服务。

依赖方向与替换前提

提供方和消费方都依赖共同定义。在接口相容、插件配置和依赖服务齐全时,可以替换注册到同一服务键的实现。调用方通常无需引用具体实现。固定版本的 bash-sandbox 继承本地执行器,并另外注入 sandbox 和 sandboxPolicy。配置切换需要同时满足这些前提。

接口的参数和行为语义会影响全部参与者。提供方可以调整内部实现、资源管理和运行环境,消费方可以调整公开参数、结果呈现和调用入口。更换环境前要检查默认工作目录、超时和支持的功能。

以 ctx.shell 为例

dsh-shell 声明 ShellExecRequest、ShellExecSpec、ShellRunResult 和 ShellExecutor。bash-local、bash-sandbox 和 pwsh-local 是目录中的实现。tool-bash、tool-pwsh 以及两个钩子桥接都消费 ctx.shell。

固定版本中,tool-bash 注入 shell 等服务,先调用 resolve(request) 补默认值并检查上限,随后交给 execute(spec)。前台分支从返回句柄调用 result()。旧讲解中的 run(...) 可按此调用链迁移。

ShellExecRequest 可省略 workdir 和 timeoutMs。解析后工作目录、超时、到期策略和 stdout 捕获预算已有明确值,而信号等字段仍可选。实验只调用 resolve。两组配置的默认超时都是 700 毫秒,9000 毫秒的请求被限制为 2000 毫秒,0 被拒绝。沙箱提供方会写入测试策略,实际约束要在子进程运行阶段另验。

用服务清单练习识别角色

先定位服务键,沿清单找到定义包,再查提供方和直接消费方。接着核对它们的注入声明与调用点。消费方清单可能远大于模型工具清单。

以 ctx.llm 为例,固定版本的定义是 llm,提供方含 llm-deepseek、llm-pi-ai 和 llm-replay。agent-loop 与 compaction-basic 是直接消费方。

以 ctx.fs 为例,固定版本列出 fs-local、fs-sandbox、fs-ssh,tool-fs 消费该接口。旧讲解中的 fs-e2b 与当前清单有差异,应按所用版本确认。两项练习基于目录与源码核对。

职责

角色约定或行为本章对应
定义服务名及请求、已解析规格和结果类型dsh-shell,ctx.shell
提供方履行契约并负责运行环境bash-local、bash-sandbox、pwsh-local
消费方通过服务约定调用能力tool-bash 或钩子桥接

ctx.shell 归属

服务键分类定义提供方直接消费方
ctx.shell可替换能力接缝shellbash-local、bash-sandbox、pwsh-localtool-bash、tool-pwsh、hooks-claude-code、hooks-codex

可以独立变化的部分

角色改动与影响
定义修改接口或语义时应检查全部调用方与提供方。
提供方在契约范围内改进资源管理、执行性能和环境适配。
消费方调整调用入口、工具参数和结果展示。

按接口检查依赖方向

方向含义
提供方到定义实现服务约定。
消费方到定义通过服务键和声明调用。
提供方到消费方提供方无需导入调用它的工具。
消费方到提供方消费方依赖接口,部署配置选择实现。

用同一个消费函数读取两套执行配置

含完整源码 · 122 行
展开查看收起
javascript
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { createRequire, registerHooks } from 'node:module'
import { resolve, sep } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'

assert.equal(process.argv.length, 3, 'Usage: node resolve-providers.mjs <trusted pinned checkout>')
const repo = resolve(process.argv[2])
const base = pathToFileURL(repo + sep).href
const localRequire = createRequire(import.meta.url)
const ts = localRequire(resolve(repo, 'node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/typescript.js'))
const yaml = localRequire(resolve(repo, 'node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js'))
const aliases = {
  '@deepseek-ai/cordis': 'vendor/cordis/src/index.ts',
  '@deepseek-ai/cosmokit': 'vendor/cosmokit/src/index.ts',
  '@deepseek-ai/schemastery': 'vendor/schemastery/src/index.ts',
  '@deepseek-ai/dsh-shell': 'packages/shell/shell/src/index.ts',
  '@deepseek-ai/dsh-bash-local': 'packages/shell/bash-local/src/index.ts',
  '@deepseek-ai/dsh-bash-sandbox': 'packages/shell/bash-sandbox/src/index.ts',
  '@deepseek-ai/dsh-sandbox': 'packages/sandbox/sandbox/src/index.ts',
  '@deepseek-ai/dsh-llm': 'packages/llm/llm/src/error.ts',
  '@deepseek-ai/dsh-timeout': 'packages/util/timeout/src/index.ts',
  '@deepseek-ai/dsh-subprocess': 'packages/subprocess/subprocess/src/index.ts',
  '@deepseek-ai/dsh-util-values': 'packages/util/values/src/index.ts',
  '@deepseek-ai/dsh-error': 'packages/util/error/src/index.ts',
  '@deepseek-ai/dsh-http-proxy': 'packages/util/http-proxy/src/index.ts',
}
registerHooks({
  resolve(name, context, next) {
    return next(aliases[name] ? base + aliases[name] : name, context)
  },
  load(url, context, next) {
    if (!url.startsWith(base) || !url.endsWith('.ts')) return next(url, context)
    return {
      format: 'module', shortCircuit: true,
      source: ts.transpile(readFileSync(fileURLToPath(url),'utf8'), {
        compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },
      }),
    }
  },
})
const { Context, Service } = await import('@deepseek-ai/cordis')
const { ShellExecutor } = await import('@deepseek-ai/dsh-shell')
const { LocalBashExecutor } = await import('@deepseek-ai/dsh-bash-local')
const { SandboxBashExecutor } = await import('@deepseek-ai/dsh-bash-sandbox')
const { Loader } = await import(base + 'vendor/loader/src/index.ts')
const policy = Object.freeze({ mode: 'read-only', workspaceRoot: process.cwd() })
const fixtures = {
  subprocess: { spawn() { throw new Error('This lesson only observes resolve()') } },
  sandbox: { confine() { throw new Error('This lesson only observes resolve()') } },
  sandboxPolicy: { defaultMode: policy.mode, resolve: () => policy },
}
function inspectRequest(shell, request) {
  const spec = shell.resolve(request)
  return {
    command: spec.command, workdir: spec.workdir, timeoutMs: spec.timeoutMs,
    onExpiry: spec.onExpiry, stdoutMaxBytes: spec.stdoutMaxBytes,
    policy: spec.sandboxPolicy?.mode ?? null,
  }
}

const hash = value => createHash('sha256').update(value).digest('hex')
const cases = []
function check(name, input, expected, actual) {
  assert.deepEqual(actual, expected, name)
  cases.push({ name, input, expected, actual, passed: true })
}
const request = { command: 'printf sample' }
const config = { timeoutMs: 700, maxTimeoutMs: 2000, maxOutputBytes: 1024 }
const providers = [
  ['local.yml', 'lesson-local', LocalBashExecutor, null],
  ['sandbox.yml', 'lesson-sandbox', SandboxBashExecutor, 'read-only'],
]
const config_hashes = {}
for (const [file, providerName, expectedClass, expectedPolicy] of providers) {
  const bytes = readFileSync(new URL('./' + file, import.meta.url))
  config_hashes[file] = hash(bytes)
  const entries = yaml.parse(bytes.toString('utf8'))
  assert.deepEqual(entries, [{ id: 'shell-lesson', name: 'cordis:' + providerName, config }])
  const ctx = new Context()
  try {
    await ctx.plugin(scoped => {
      for (const [name, methods] of Object.entries(fixtures)) {
        Object.assign(new Service(scoped, name), methods)
      }
    })
    await ctx.plugin(Loader, {baseUrl: import.meta.url})
    ctx.loader.builtins['lesson-local'] = LocalBashExecutor
    ctx.loader.builtins['lesson-sandbox'] = SandboxBashExecutor
    for (const entry of entries) await ctx.loader.create(entry)
    await ctx.loader.await()
    const shell = ctx.shell
    const active = ctx.loader.resolve('shell-lesson').fiber.provisions.values().find(p => p.name === 'shell')
    check(providerName + ' satisfies the same definition', { file },
      { sameDefinition: true, selectedProvider: true },
      { sameDefinition: shell instanceof ShellExecutor, selectedProvider: active.value instanceof expectedClass })
    check(providerName + ' resolves omitted defaults', request,
      { ...request, workdir: process.cwd(), timeoutMs: 700, onExpiry: 'kill', stdoutMaxBytes: 1024,
        policy: expectedPolicy }, inspectRequest(shell, request))
    const overridden = { ...request, timeoutMs: 9000, workdir: process.cwd() }
    check(providerName + ' caps an explicit timeout', overridden,
      { ...overridden, timeoutMs: 2000, onExpiry: 'kill', stdoutMaxBytes: 1024, policy: expectedPolicy },
      inspectRequest(shell, overridden))
    let rejectsTimeout = false
    try { inspectRequest(shell, { ...request, timeoutMs: 0 }) } catch (error) {
      rejectsTimeout = error.message.includes('timeoutMs')
    }
    check(providerName + ' rejects zero timeout', { ...request, timeoutMs: 0 }, true, rejectsTimeout)
  } finally {
    await ctx.fiber.dispose()
  }
}
const files = [...Object.values(aliases), 'vendor/loader/src/index.ts', 'packages/shell/shell/src/types.ts']
console.log(JSON.stringify({
  cases, node: process.version, typescript: ts.version, config_hashes,
  code_sha256: hash(readFileSync(fileURLToPath(import.meta.url))),
  source_hashes: Object.fromEntries(files.map(name => [name, hash(readFileSync(resolve(repo, name)))])),
  fixture_dependencies: Object.keys(fixtures),
  command_executed: false, sandbox_enforcement_tested: false,
}, null, 2))
两套 YAML 选中不同提供方,使用共同 ShellExecutor 定义,复现 8 项真实解析观察。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地复跑

解压后按 README 提供固定版本源码的位置。

下载本章实验包 (mbskycom202612a131.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:DeepSeek Harness

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a131.zip

下载课程关联工程包:DeepSeek Harness

课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a128.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

保持服务接口与调用语义相容,并按实现准备其依赖服务和配置。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习