import assert from 'node:assert/strict';
import {spawn} from 'node:child_process';
import {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
import {createServer} from 'node:http';
import {tmpdir} from 'node:os';
import {basename, dirname, join, resolve} from 'node:path';
import {createInterface} from 'node:readline';
import {pathToFileURL} from 'node:url';
const modules = process.argv[2];
if (!modules) throw new Error('Supply the installed node_modules path.');
const pi = resolve(modules, '@earendil-works', 'pi-coding-agent');
const load = name => import(pathToFileURL(join(pi, 'dist', name)).href);
const {parseCommandArgs, substituteArgs, loadPromptTemplates, expandPromptTemplate} = await load('core/prompt-templates.js');
const {bin, version} = JSON.parse(await readFile(join(pi, 'package.json'), 'utf8'));
const cases = [];
function verify(name, input, expected, actual) {
assert.deepStrictEqual(actual, expected, name);
cases.push({name, input, expected, actual, passed: true});
}
const base = resolve(tmpdir());
const root = await mkdtemp(join(base, 'mbsky-pi-prompts-'));
assert.equal(dirname(resolve(root)), base);
assert.ok(basename(root).startsWith('mbsky-pi-prompts-'));
const requestBodies = [];
const service = createServer(async (req, res) => {
if (req.method !== 'POST' || req.url !== '/v1/chat/completions') {
res.writeHead(404).end();
return;
}
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const body = JSON.parse(Buffer.concat(chunks));
requestBodies.push(body.messages.filter(m => m.role === 'user').at(-1).content);
const frame = (delta, finish) => ({id: 'prompt-lab', model: body.model, object: 'chat.completion.chunk',
created: 1, choices: [{index: 0, delta, finish_reason: finish}]});
res.writeHead(200, {'Content-Type': 'text/event-stream'});
res.end([frame({role: 'assistant', content: 'OWN TEMPLATE RETURN'}, null), frame({}, 'stop')]
.map(row => 'data: ' + JSON.stringify(row) + '\n\n').join('') + 'data: [DONE]\n\n');
});
try {
const profile = join(root, 'profile');
const cwd = join(root, 'work');
const user = join(profile, 'prompts');
const project = join(cwd, '.pi', 'prompts');
const privateDir = join(user, 'nested');
for (const dir of [user, project, privateDir]) await mkdir(dir, {recursive: true});
const save = (file, text) => writeFile(file, text, 'utf8');
const main = join(user, 'museum-caption.md');
const template = ['---', 'description: Write a caption for an exhibit', 'argument-hint: "<object> [detail]"',
'---', 'Object: $1', 'Detail: ${2:-no detail}', ''].join('\n');
await save(main, template);
await save(join(user, 'plain.md'), '\n\nFallback line\nMore content\n');
await save(join(project, 'gallery-draft.md'), 'An optional local project draft.\n');
await save(join(privateDir, 'deep-label.md'), 'A nested prompt.\n');
const options = {cwd, agentDir: profile, promptPaths: [], includeDefaults: true};
const discovered = loadPromptTemplates(options).templates;
verify('filename_description_and_argument_hint', {file: basename(main)},
['museum-caption', 'Write a caption for an exhibit', '<object> [detail]'],
['name','description','argumentHint'].map(k => discovered.find(v => v.name === 'museum-caption')[k]));
verify('conventional_directory_skips_nested_and_uses_description_fallback', {location: 'prompts/nested'},
[['gallery-draft','museum-caption','plain'], 'Fallback line'],
[discovered.map(v => v.name).sort(), discovered.find(v => v.name === 'plain').description]);
verify('disabled_defaults_accept_explicit_nested_file', {optIn: 'deep-label.md'},
['deep-label'], loadPromptTemplates({...options, includeDefaults: false,
promptPaths: [join(privateDir, 'deep-label.md')]}).templates.map(v => v.name));
const quoted = parseCommandArgs('"glass star" "" ink "muted tones"');
verify('quoted_blank_and_whitespace_in_arguments', {tokens: 'quoted object, quoted empty, ink, quoted detail'},
['glass star','','ink','muted tones'], quoted);
verify('positional_default_join_and_slices', {quoted},
'glass star / default / glass star ink muted tones / ink muted tones / ink',
substituteArgs('$1 / ${2:-default} / $ARGUMENTS / ${@:2} / ${@:2:2}', quoted));
verify('no_recursive_placeholder_substitution', {argument: '$2'},
'[$2]-[paper]', substituteArgs('[$1]-[$2]', ['$2','paper']));
verify('expand_named_command_preserves_space_in_argument', {command: '/museum-caption "silver clock"'},
'Object: silver clock\nDetail: no detail', expandPromptTemplate('/museum-caption "silver clock"', discovered));
const teaching = [
['summary-card', 'Write ${1:-3} bullet points.', '/summary-card', 'Write 3 bullet points.'],
['summary-card', 'Write ${1:-3} bullet points.', '/summary-card 7', 'Write 7 bullet points.'],
['bilingual-tag', 'Translate label: $@', '/bilingual-tag "青瓷碗" 宋代', 'Translate label: 青瓷碗 宋代'],
['gallery-component', 'Describe $1 in $2 with ${@:3}', '/gallery-component Card Svelte "large text" "two columns"',
'Describe Card in Svelte with large text two columns'],
['commit-note', 'Suggest a local commit message for ${@:-current staged changes}; prefer docs(scope): summary.',
'/commit-note "manual label formatting"', 'Suggest a local commit message for manual label formatting; prefer docs(scope): summary.'],
['cleanup-draft', 'For $1, preserve behavior and list cleanup steps before edits.', '/cleanup-draft src/labels.js',
'For src/labels.js, preserve behavior and list cleanup steps before edits.'],
['trace-display', 'Describe expected and observed behavior for $1, then outline a regression check.',
'/trace-display "empty title appears in preview"',
'Describe expected and observed behavior for empty title appears in preview, then outline a regression check.'],
];
for (const [name, content, command, expected] of teaching) {
verify('teaching:' + command, {template: name}, expected, expandPromptTemplate(command, [{name, content}]));
}
await new Promise(done => service.listen(0, '127.0.0.1', done));
const baseUrl = 'http://127.0.0.1:' + service.address().port + '/v1';
await save(join(profile, 'models.json'), JSON.stringify({providers: {'own-prompt-lab': {
baseUrl, api: 'openai-completions', apiKey: 'fixture-only', models: [{id: 'card-writer'}],
}}}));
const allowed = ['PATH','SystemRoot','WINDIR','COMSPEC','PATHEXT','TEMP','TMP','USERPROFILE','LOCALAPPDATA','APPDATA'];
const env = Object.fromEntries(allowed.filter(k => k in process.env).map(k => [k,process.env[k]]));
Object.assign(env, {PI_CODING_AGENT_DIR: profile, PI_OFFLINE: '1', PI_SKIP_VERSION_CHECK: '1', PI_TELEMETRY: '0'});
const child = spawn(process.execPath, [join(pi, bin.pi), '--mode','rpc','--no-session',
'--no-tools','--no-context-files','--no-mcp','--no-extensions','--no-skills',
'--provider','own-prompt-lab','--model','card-writer','--no-approve'],
{cwd, env, windowsHide: true, stdio: ['pipe','pipe','pipe']});
const closed = new Promise(done => child.once('close', done));
let errors = '';
child.stderr.setEncoding('utf8').on('data', text => { errors += text; });
const rows = createInterface({input: child.stdout});
const end = setTimeout(() => child.kill(), 15000);
try {
const submitted = '/museum-caption "blue bowl" "from the 1950s"';
child.stdin.write(JSON.stringify({id: 'commands', type: 'get_commands'}) + '\n');
let completed = false;
for await (const line of rows) {
const item = JSON.parse(line);
if (item.type === 'response' && item.id === 'commands') {
const names = item.data.commands.filter(c => c.source === 'prompt').map(c => c.name).sort();
verify('rpc_projects_need_trust_and_global_templates_are_available',
{session: 'explicitly untrusted project'}, ['museum-caption', 'plain'], names);
child.stdin.write(JSON.stringify({id: 'sample', type: 'prompt', message: submitted}) + '\n');
}
if (item.type === 'response' && item.id === 'sample') assert.equal(item.success, true, JSON.stringify(item));
if (item.type === 'agent_end') {
completed = true;
verify('real_model_request_gets_expansion_without_slash_command', {submitted},
[{type: 'text', text: 'Object: blue bowl\nDetail: from the 1950s'}], requestBodies.at(-1));
break;
}
}
if (!completed) throw new Error('The local prompt run did not finish: ' + errors);
} finally {
child.stdin.end();
await closed;
clearTimeout(end);
rows.close();
}
process.stdout.write(JSON.stringify({nodeVersion: process.version, packageVersion: version, cases}) + '\n');
} finally {
if (service.listening) await new Promise(done => service.close(done));
await rm(root, {recursive: true, force: true});
}
本例需在 Node.js 24.22.3、Pi 1.5.0、独立临时目录和本机回环接口。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Node.js 24.22.3、Pi 1.5.0、独立临时目录和本机回环接口。
入口文件:projects/pi-agent-prompt-templates-lab/prompt-template-preflight.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
prompt-template-preflight.mjs,或下载右侧课程工程包。 - 确认本地已准备 Node.js 24.22.3、Pi 1.5.0、独立临时目录和本机回环接口。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a286.zip
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip