chore: establish YCode replication baseline and TODO

This commit is contained in:
xiaohan.yuan committed 2026-10-17 02:43:49 +08:00
commit 6dc59f89ba
1118 files changed
+196002

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
// Real filesystem + SDK MCP + production fallback Gateway/turn loop. All servers are local fixtures.
import fs from 'node:fs/promises'
import path from 'node:path'
import assert from 'node:assert/strict'
import { pathToFileURL } from 'node:url'
import { build } from 'esbuild'
import { createServer } from 'node:http'
const directory = await fs.mkdtemp(path.resolve('.tmp/capability-gateway-'))
const userData = path.join(directory, 'data'), cwd = path.join(directory, 'workspace'), source = path.join(directory, 'skill')
await Promise.all([userData, cwd, source].map(folder => fs.mkdir(folder)))
await fs.writeFile(path.join(source, 'SKILL.md'), '---\nname: gateway-proof\ndescription: Controlled gateway capability\n---\nGATEWAY_SKILL_PROOF\n')
await fs.writeFile(path.join(source, 'guide.txt'), 'GATEWAY_RESOURCE_PROOF')
await build({ stdin: { contents: `export * as skills from './src/main/capabilities/skills';export * as mcp from './src/main/capabilities/mcp';export {createCapabilitySnapshot} from './src/main/capabilities/runtime';export {runTurn} from './src/main/agent/loop';export {Gateway} from './src/main/gateway'`, resolveDir: process.cwd() }, outfile: path.join(directory, 'runtime.mjs'), bundle: true, platform: 'node', format: 'esm', packages: 'external', logLevel: 'warning', plugins: [{ name: 'isolated-path', setup(context) { context.onResolve({ filter: /^electron$/ }, () => ({ path: 'electron', namespace: 'qa' })); context.onLoad({ filter: /.*/, namespace: 'qa' }, () => ({ contents: `export const app={getPath:()=>${JSON.stringify(userData)}};export const safeStorage={isEncryptionAvailable:()=>false}` })) } }] })
const { skills, mcp, createCapabilitySnapshot, runTurn, Gateway } = await import(pathToFileURL(path.join(directory, 'runtime.mjs')).href)
const checks = [], events = [], requests = []
const check = (label, actual, expected = true) => { assert.deepEqual(actual, expected, label); checks.push(label) }
let server
try {
const skill = await skills.importSkill(source)
const saved = await mcp.saveMcpServer({ name: 'gateway-connector', transport: 'stdio', command: process.execPath, args: [path.resolve('scripts/test-mcp-server.mjs'), 'stdio', path.join(directory, 'mcp-events.jsonl')] })
await mcp.trustMcpServer(saved.id, saved.configHash); await mcp.setMcpEnabled(saved.id, true)
const snapshot = await createCapabilitySnapshot([skill.id], cwd)
check('resource URI uses source skill scheme', snapshot.references[0].uri, 'skill://gateway-proof')
check('manual skill body in actual turn context', snapshot.context.includes('GATEWAY_SKILL_PROOF'))
const mcpName = snapshot.specs.find(spec => spec.function.name.startsWith('mcp_echo_')).function.name
server = createServer(async (request, response) => {
let raw = ''; for await (const bytes of request) raw += bytes
const body = JSON.parse(raw), results = body.messages.filter(message => message.role === 'tool')
requests.push({ toolNames: body.tools.map(tool => tool.function.name), results: results.map(item => item.content), skillContext: JSON.stringify(body.messages).includes('GATEWAY_SKILL_PROOF') })
const calls = [{ name: 'ycode_load_skill', args: { id: skill.id } }, { name: 'ycode_read_skill_resource', args: { id: skill.id, path: 'guide.txt' } }, { name: mcpName, args: { text: 'GATEWAY_ECHO_PROOF' } }]
const call = calls[results.length], delta = call ? { tool_calls: [{ index: 0, id: 'call-' + results.length, type: 'function', function: { name: call.name, arguments: JSON.stringify(call.args) } }] } : { content: 'GATEWAY_CAPABILITIES_OK' }
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(`data: ${JSON.stringify({ id: 'qa', choices: [{ index: 0, delta, finish_reason: null }] })}\n\ndata: ${JSON.stringify({ id: 'qa', choices: [{ index: 0, delta: {}, finish_reason: call ? 'tool_calls' : 'stop' }] })}\n\ndata: [DONE]\n\n`)
})
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
const gateway = new Gateway({ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, apiKey: '', authMode: 'none', model: 'qa', temperature: 0, maxToolRounds: 6 })
const signal = new AbortController().signal
const result = await runTurn({ runId: 'gateway-capabilities', history: [], userText: 'Run capability proof\n' + snapshot.context, signal, emit: event => events.push(event), gateway, model: 'qa', maxToolRounds: 6, workspaceRoot: cwd, permissionMode: 'full-access', capabilityTools: snapshot })
check('production fallback returns final reply', result.content, 'GATEWAY_CAPABILITIES_OK')
check('three actual tool rounds succeeded', result.tools.map(tool => tool.status), ['ok', 'ok', 'ok'])
check('auto load returned actual installed bytes', result.tools[0].output.includes('GATEWAY_SKILL_PROOF'))
check('resource tool returned actual file bytes', result.tools[1].output, 'GATEWAY_RESOURCE_PROOF')
check('MCP returned SDK server result', result.tools[2].output, 'stdio:GATEWAY_ECHO_PROOF')
check('MCP display identity survives the fallback turn', [result.tools[2].metadata?.serverName, result.tools[2].metadata?.toolName], ['gateway-connector', 'echo'])
check('all dynamic tools reach actual HTTP upstream', requests.every(request => ['ycode_load_skill', 'ycode_read_skill_resource', mcpName].every(name => request.toolNames.includes(name))))
check('MCP result is fed back to upstream', requests.at(-1).results.includes('stdio:GATEWAY_ECHO_PROOF'))
check('tool completion events precede terminal', events.filter(event => ['tool_result', 'done'].includes(event.type)).map(event => event.type), ['tool_result', 'tool_result', 'tool_result', 'done'])
const ctx = { runId: 'qa', toolCallId: 'qa-tool', workspaceRoot: cwd, permissionMode: 'full-access', signal, emit() {} }
check('unknown skill ID cannot load', (await snapshot.execute('ycode_load_skill', { id: 'other-workspace' }, ctx)).ok, false)
await assert.rejects(snapshot.execute('ycode_read_skill_resource', { id: skill.id, path: '../outside' }, ctx)); checks.push('resource traversal rejected through turn dispatcher')
await mcp.setMcpToolEnabled(saved.id, 'echo', false)
check('disabled MCP tool rejects an older snapshot', (await snapshot.execute(mcpName, { text: 'NO_EXECUTE' }, ctx)).ok, false)
check('next turn omits disabled MCP tool', !(await createCapabilitySnapshot([], cwd)).specs.some(tool => tool.function.name === mcpName))
await skills.setSkillEnabled(skill.id, false)
await assert.rejects(createCapabilitySnapshot([skill.id], cwd)); checks.push('selected disabled skill rejects before a turn')
check('built-in expert manager remains available after user skill disabled', (await createCapabilitySnapshot([], cwd)).specs.some(tool => tool.function.name === 'ycode_load_skill'))
console.log(JSON.stringify({ result: 'PASS', checks: checks.length, directory }))
await fs.writeFile(path.join(directory, 'report.json'), JSON.stringify({ result: 'PASS', checks, requests }, null, 2))
} catch (error) { await fs.writeFile(path.join(directory, 'report.json'), JSON.stringify({ result: 'FAIL', checks, error: String(error) }, null, 2)); throw error }
finally { await mcp.disposeMcpServers(); if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)) } }