蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

装配并更换文本服务

JAVASCRIPTNode.js 24.22.3、TypeScript 6.0.3、YAML 2.9.0 与固定版本本地源码。load-capability.mjs
load-capability.mjs121 行
import { registerHooks, createRequire } from 'node:module'
import fs from 'node:fs'
import path from 'node:path'
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { pathToFileURL, fileURLToPath } from 'node:url'

const repo = path.resolve(process.argv[2])
const base = pathToFileURL(repo + '/').href
const req = createRequire(import.meta.url)
const ts = req(path.join(repo, 'node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/typescript.js'))
const spec = path.join(repo, 'node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/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-scope': 'packages/core/scope/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-llm': 'packages/llm/llm/src/error.ts',
}
registerHooks({
  resolve(s, c, n) {
    if (aliases[s]) return n(base + aliases[s], c)
    if (s === '@standard-schema/spec') return n(pathToFileURL(spec).href, c)
    return n(s, c)
  },
  load(u, c, n) {
    if (u.startsWith(base) && u.endsWith('.ts')) return { format: 'module', source: ts.transpile(fs.readFileSync(fileURLToPath(u), 'utf8'), { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }), shortCircuit: true }
    return n(u, c)
  },
})
const { Context, Service } = await import('@deepseek-ai/cordis')
const { ToolsService, defineTool } = await import(base + 'packages/core/tools/src/index.ts')

class TextTransform extends Service {
  constructor(ctx) { super(ctx, 'lessonText') }
}

class Uppercase extends TextTransform {
  async transform({ text }) { return { value: text.toUpperCase() } }
}

class Surround extends TextTransform {
  async transform({ text }) { return { value: '[' + text + ']' } }
}

class PromptFixture extends Service {
  constructor(ctx) { super(ctx, 'systemPrompt') }
  tools() { return () => {} }
}

let executions = 0
const consumer = Object.assign(ctx => {
  ctx.tools.register(defineTool({
    name: 'lesson_transform',
    description: 'Transform a supplied line of text.',
    parameters: { text: { type: 'string', required: true } },
    output: { schema: { type: 'string' }, render: (_args, value) => [{type:'text',text:value}] },
    async execute({ text }) {
      executions++
      return (await ctx.lessonText.transform({ text })).value
    },
  }))
}, { inject: ['tools', 'lessonText'] })

const { Loader } = await import(base + 'vendor/loader/src/index.ts')
const yaml = req(path.join(repo, 'node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js'))
function config(name) {
  const source = fs.readFileSync(new URL('./' + name, import.meta.url))
  return { source, items: yaml.parse(source.toString('utf8')) }
}
const cases = []
function check(name,input,expected,actual) {
  assert.deepEqual(actual,expected,name)
  cases.push({ name,input,expected,actual,passed:true })
}
for (const [Provider, output, file] of [[Uppercase,'STRASSE 你好','uppercase.yml'], [Surround,'[Straße 你好]','surround.yml']]) {
  const ctx = new Context()
  try {
    await ctx.plugin(PromptFixture)
    await ctx.plugin(ToolsService)
    await ctx.plugin(Loader, {baseUrl: import.meta.url})
    Object.assign(ctx.loader.builtins, {'lesson-upper': Uppercase, 'lesson-surround': Surround, 'lesson-consumer': consumer})
    const { items } = config(file)
    const registry = ctx.reflect.get('tools')
    assert.equal(items.length, 2)
    assert.equal(items[1].name, Provider === Uppercase ? 'cordis:lesson-upper' : 'cordis:lesson-surround')
    await ctx.loader.create(items[0])
    check(Provider.name + ' consumer waits for provider', file + ': consumer loaded first', false,
      Boolean(registry.get('lesson_transform')))
    await ctx.loader.create(items[1])
    await ctx.loader.await()
    const definition = registry.get('lesson_transform')
    const args = { text: 'Straße 你好' }
    const value = await definition.execute(args, {})
    check(Provider.name + ' direct tool result', args, output, value)
    check(Provider.name + ' explicit text renderer', args, [{type:'text',text:output}],
      definition.output.render(args,value))
    const before = executions
    let errorCode = null
    try { await definition.execute({ text: 2 }, {}) } catch (error) { errorCode = error.code }
    check(Provider.name + ' rejects invalid argument before execute', {text:2},
      {code:'INVALID_ARGS',calls:0},{code:errorCode,calls:executions-before})
    await ctx.loader.remove('transform-tool')
    check(Provider.name + ' unregisters on consumer disposal', 'dispose consumer',false,
      Boolean(registry.get('lesson_transform')))
  } finally {
    await ctx.fiber.dispose()
  }
}
const sha = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex')
const sources = [...Object.values(aliases), 'packages/core/tools/src/index.ts',
  'vendor/loader/src/index.ts', 'packages/core/tools/src/schema.ts', 'docs/user/develop/practice/index.zh.md']
console.log(JSON.stringify({
  node:process.version,typescript:ts.version,cases,
  code_sha256:sha(fileURLToPath(import.meta.url)),
  source_hashes:Object.fromEntries(sources.map(file=>[file,sha(path.join(repo,file))])),
  full_loader_yaml_tested:true, yaml:'2.9.0', config_sha256:Object.fromEntries(['uppercase.yml','surround.yml'].map(name=>[name,createHash('sha256').update(config(name).source).digest('hex')])),model_called:false,tool_pipeline_tested:false,
},null,2))
本例需在 Node.js 24.22.3、TypeScript 6.0.3、YAML 2.9.0 与固定版本本地源码。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Node.js 24.22.3、TypeScript 6.0.3、YAML 2.9.0 与固定版本本地源码。

入口文件:projects/deepseek-harness-build-capability/load-capability.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 load-capability.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Node.js 24.22.3、TypeScript 6.0.3、YAML 2.9.0 与固定版本本地源码。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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