import assert from 'node:assert/strict';
import {spawn} from 'node:child_process';
import {createServer} from 'node:http';
import {once} from 'node:events';
import {mkdir, readFile, writeFile} from 'node:fs/promises';
import {join, resolve} from 'node:path';
import {pathToFileURL} from 'node:url';
const [, , cliPath, isolatedDirectory] = process.argv;
if (!cliPath || !isolatedDirectory) throw new Error('请提供 Pi CLI 和一个空临时目录');
const cli = resolve(cliPath);
const root = resolve(isolatedDirectory);
const config = join(root, 'agent');
await mkdir(config);
const cliPackage = resolve(cli, '../../..');
const fileUrl = (...segments) => pathToFileURL(join(...segments)).href;
const {findEnvKeys} = await import(fileUrl(cliPackage, '../pi-ai/dist/env-api-keys.js'));
const {isCommandConfigValue, resolveConfigValue} = await import(fileUrl(cliPackage, 'dist/core/resolve-config-value.js'));
const cases = [];
function check(name, input, expected, actual) {
assert.deepStrictEqual(actual, expected, name);
cases.push({name, input, expected, actual, passed: true});
}
const providerEnvironments = {
anthropic: 'ANTHROPIC_API_KEY', openai: 'OPENAI_API_KEY', google: 'GEMINI_API_KEY',
deepseek: 'DEEPSEEK_API_KEY', groq: 'GROQ_API_KEY', mistral: 'MISTRAL_API_KEY',
xai: 'XAI_API_KEY', openrouter: 'OPENROUTER_API_KEY',
};
const exampleEnv = Object.fromEntries(Object.values(providerEnvironments).map(key => [key, 'local-fixture']));
for (const [provider, variable] of Object.entries(providerEnvironments)) {
check('environment_' + provider, {provider, variable}, [variable], findEnvKeys(provider, exampleEnv));
}
check('env_interpolation', {form: '$COURSE_DUMMY'}, true,
resolveConfigValue('$COURSE_DUMMY', {COURSE_DUMMY: 'local-config-fixture'}) === 'local-config-fixture');
check('env_interpolation_absent', {form: '$COURSE_DUMMY', defined: false}, null,
resolveConfigValue('$COURSE_DUMMY', {}) ?? null);
check('command_form_detected', {form: '!<本地已审核命令>'}, true, isCommandConfigValue('!<本地已审核命令>'));
const file = join(config, 'auth.json');
const received = [];
const fakeValues = {
override: 'course-local-override', stored: 'course-local-stored',
explicit: 'course-local-explicit', ambient: 'course-local-ambient',
};
const respText = '课程配置已送到本地回环端点';
const model = 'course-fixture-model';
const server = createServer(async (req, res) => {
if (req.method !== 'POST' || req.url !== '/v1/chat/completions') {
res.writeHead(404).end();
return;
}
let raw = '';
for await (const data of req) raw += data;
const body = JSON.parse(raw);
const source = Object.keys(fakeValues).find(name => 'Bearer ' + fakeValues[name] === req.headers.authorization);
received.push({
source: source ?? 'unknown', model: body.model,
thinking: body.thinking?.type ?? null, effort: body.reasoning_effort ?? null,
});
const chunk = (delta, reason = null) => ({
id: 'course-auth-fixture', object: 'chat.completion.chunk', created: 1, model,
choices: [{index: 0, delta, finish_reason: reason}],
});
res.writeHead(200, {'Content-Type': 'text/event-stream'});
res.write('data: ' + JSON.stringify(chunk({role: 'assistant', content: respText})) + '\n\n');
res.end('data: ' + JSON.stringify(chunk({}, 'stop')) + '\n\ndata: [DONE]\n\n');
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const env = Object.fromEntries(
['PATH', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'USERPROFILE', 'LOCALAPPDATA', 'APPDATA', 'COMSPEC']
.filter(key => process.env[key]).map(key => [key, process.env[key]]),
);
Object.assign(env, {
PI_CODING_AGENT_DIR: config, PI_OFFLINE: '1', PI_SKIP_VERSION_CHECK: '1', PI_TELEMETRY: '0',
DEEPSEEK_API_KEY: fakeValues.ambient, COURSE_DUMMY: fakeValues.explicit,
});
const flags = ['--no-session', '--no-tools', '--no-extensions', '--no-mcp', '--no-context-files',
'--no-skills', '--no-prompt-templates', '--no-themes', '--print'];
const baseUrl = 'http://127.0.0.1:' + server.address().port + '/v1';
async function configure(hasExplicitKey, stored) {
const provider = {
baseUrl, api: 'openai-completions',
models: [{id: model, baseUrl, reasoning: true, contextWindow: 32000, maxTokens: 512,
input: ['text'], cost: {input: 0, output: 0, cacheRead: 0, cacheWrite: 0},
compat: {thinkingFormat: 'deepseek', requiresReasoningContentOnAssistantMessages: true},
thinkingLevelMap: {minimal: 'low', low: 'low', medium: 'high', high: 'high', xhigh: 'high', max: 'max'}}],
};
if (hasExplicitKey) provider.apiKey = '$COURSE_DUMMY';
await writeFile(join(config, 'models.json'), JSON.stringify({providers: {deepseek: provider}}));
const record = stored ? {deepseek: {type: 'api_key', key: '$COURSE_STORED_FIXTURE'}} : {};
await writeFile(file, JSON.stringify(record), {mode: 0o600});
env.COURSE_STORED_FIXTURE = fakeValues.stored;
}
async function run(flagsForModel) {
const child = spawn(process.execPath, [cli, ...flags, ...flagsForModel, '核对本地课程配置'], {
cwd: root, env, windowsHide: true,
});
let stdout = '', stderr = '';
child.stdout.setEncoding('utf8').on('data', data => { stdout += data; });
child.stderr.setEncoding('utf8').on('data', data => { stderr += data; });
child.stdin.end();
const timer = setTimeout(() => child.kill(), 15000);
try {
const [code] = await once(child, 'close');
assert.equal(code, 0, stderr);
assert.equal(stdout.trim(), respText);
return received.at(-1);
} finally {
clearTimeout(timer);
}
}
try {
await configure(true, true);
const original = await readFile(file, 'utf8');
const one = await run(['--provider', 'deepseek', '--model', model, '--api-key', fakeValues.override, '--thinking', 'off']);
check('one_call_override', {stored: true, explicit: true, ambient: true, thinking: 'off'},
{source: 'override', model, thinking: 'disabled', effort: null}, one);
check('override_does_not_persist', {explicitCli: true}, true, original === await readFile(file, 'utf8'));
const two = await run(['--model', 'deepseek/' + model + ':high']);
check('stored_dominates', {stored: true, explicit: true, ambient: true, selector: 'provider/model:high'},
{source: 'stored', model, thinking: 'enabled', effort: 'high'}, two);
await configure(true, false);
const three = await run(['--model', 'deepseek/' + model + ':xhigh']);
check('explicit_provider_key_dominates_ambient', {stored: false, explicit: true, ambient: true, thinking: 'xhigh'},
{source: 'explicit', model, thinking: 'enabled', effort: 'high'}, three);
await configure(false, false);
const four = await run(['--provider', 'deepseek', '--model', model, '--thinking', 'max']);
check('ambient_key_is_used_without_overrides', {stored: false, explicit: false, ambient: true, thinking: 'max'},
{source: 'ambient', model, thinking: 'enabled', effort: 'max'}, four);
check('exact_local_requests', {processes: 4, allowed: '127.0.0.1'}, 4, received.length);
process.stdout.write(JSON.stringify({version: process.version, cases}) + '\n');
} finally {
server.closeAllConnections();
await new Promise(close => server.close(close));
}
本例需在 Node.js 24.22.3、Pi CLI 1.5.0、临时配置与本机回环固定应答。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Node.js 24.22.3、Pi CLI 1.5.0、临时配置与本机回环固定应答。
入口文件:projects/pi-agent-auth-lab/loopback-auth.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
loopback-auth.mjs,或下载右侧课程工程包。 - 确认本地已准备 Node.js 24.22.3、Pi CLI 1.5.0、临时配置与本机回环固定应答。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a266.zip