import assert from 'node:assert/strict';
import {spawn} from 'node:child_process';
import {cp, mkdir, mkdtemp, readFile, rm, unlink, 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 {fileURLToPath} 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 {version,bin} = JSON.parse(await readFile(join(pi,'package.json'),'utf8'));
const base = resolve(tmpdir());
const root = await mkdtemp(join(base,'mbsky-pi-extension-'));
assert.equal(dirname(resolve(root)),base);
assert.ok(basename(root).startsWith('mbsky-pi-extension-'));
const toText = value => Array.isArray(value) ? value.filter(x=>x.type==='text').map(x=>x.text).join('') : value;
const calls = [];
const cases = [];
function check(name,input,expected,actual) {
assert.deepStrictEqual(actual,expected,name);
cases.push({name,input,expected,actual,passed:true});
}
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));
calls.push(body);
const last=body.messages.at(-1);
const userText=toText(last.content);
const frame=(delta,finish)=>({id:'extension-lab',object:'chat.completion.chunk',created:1,model:body.model,
choices:[{index:0,delta,finish_reason:finish}]});
let frames;
if (last.role==='tool') {
frames=[frame({role:'assistant',content:'LABEL LAB COMPLETE'},null),frame({},'stop')];
} else {
const name=userText.includes('Long label')?'A name much longer than twenty chars':'Paper map';
const id='label_'+calls.length;
frames=[frame({role:'assistant',tool_calls:[{index:0,id,type:'function',function:{
name:'format_exhibit_label',arguments:JSON.stringify({name,style:'upper'}),
}}]},null),frame({},'tool_calls')];
}
res.writeHead(200,{'Content-Type':'text/event-stream'});
res.end(frames.map(row=>'data: '+JSON.stringify(row)+'\n\n').join('')+'data: [DONE]\n\n');
});
try {
const profile=join(root,'profile'), project=join(root,'work'), folder=join(root,'explicit-extension');
const envKeys=['PATH','SystemRoot','WINDIR','COMSPEC','PATHEXT','TEMP','TMP','USERPROFILE','LOCALAPPDATA','APPDATA'];
const env=Object.fromEntries(envKeys.filter(k=>k in process.env).map(k=>[k,process.env[k]]));
await mkdir(profile);
await mkdir(project);
await cp(fileURLToPath(new URL('./extension/',import.meta.url)),folder,{recursive:true});
const events=join(root,'events.txt');
Object.assign(env,{PI_CODING_AGENT_DIR:profile,PI_OFFLINE:'1',PI_SKIP_VERSION_CHECK:'1',
PI_TELEMETRY:'0',MBSKY_LABEL_LIFECYCLE:events});
await new Promise(done=>service.listen(0,'127.0.0.1',done));
await writeFile(join(profile,'models.json'),JSON.stringify({providers:{'owned-extension':{
baseUrl:'http://127.0.0.1:'+service.address().port+'/v1',api:'openai-completions',apiKey:'fixture-only',
models:[{id:'greeting-lab'}],
}}}));
const common=['--mode','rpc','--no-session','--no-mcp','--no-context-files','--no-skills',
'--no-themes','--no-prompt-templates','--no-builtin-tools',
'--provider','owned-extension','--model','greeting-lab'];
async function run(extra,action,approval='--no-approve') {
const child=spawn(process.execPath,[join(pi,bin.pi),...common,approval,...extra],
{cwd:project,env,windowsHide:true,stdio:['pipe','pipe','pipe']});
const closed=new Promise(done=>child.once('close',done));
let stderr='';
child.stderr.setEncoding('utf8').on('data',t=>{stderr+=t;});
child.stdin.on('error',()=>{});
const stream=createInterface({input:child.stdout});
const rows=stream[Symbol.asyncIterator]();
const deadline=setTimeout(()=>child.kill(),16000);
const send=(id,type,fields={})=>child.stdin.write(JSON.stringify({id,type,...fields})+'\n');
async function until(test) {
for (;;) {
const row=await rows.next();
if (row.done) throw new Error('RPC did not return expected evidence: '+stderr);
const value=JSON.parse(row.value);
if (value.type==='response') assert.equal(value.success,true,JSON.stringify(value));
if (test(value)) return value;
}
}
try { return await action(send,until); }
finally {
child.stdin.end();
await closed;
clearTimeout(deadline);
stream.close();
}
}
await run(['--no-extensions','-e',join(folder,'index.ts')],async(send,until)=>{
const init=await until(row=>row.type==='extension_ui_request'&&row.method==='notify');
check('session_start_notifies_after_async_factory',{explicitEntry:'index.ts'},
'LABEL EXTENSION READY',init.message);
send('commands','get_commands');
const commands=await until(row=>row.id==='commands');
check('explicit_extension_registers_user_command',{using:'-e no defaults'},
true,commands.data.commands.some(item=>item.name==='label-preview'&&item.source==='extension'));
send('preview','prompt',{message:'/label-preview Paper map'});
const note=await until(row=>row.type==='extension_ui_request'&&row.method==='notify');
check('local_command_notifies_without_model_call',{command:'/label-preview Paper map'},
['PREVIEW Exhibit: Paper map',0],[note.message,calls.length]);
for (const [id,value] of [['short','Short label'],['long','Long label']]) {
send(id,'prompt',{message:value});
await until(row=>row.type==='agent_end');
}
const schema=calls[0].tools.find(t=>t.function.name==='format_exhibit_label').function.parameters;
check('provider_receives_typed_registered_tool',{name:'format_exhibit_label'},
['string',['plain','upper']],[schema.properties.name.type,schema.properties.style.enum]);
const results=calls.flatMap(body=>body.messages.at(-1)?.role==='tool'?[toText(body.messages.at(-1).content)]:[]);
check('registered_tool_formats_short_input',{name:'Paper map',style:'upper'},'EXHIBIT: PAPER MAP',results[0]);
check('event_gate_blocks_long_owned_input',{maximum:20},true,
results[1]?.includes('Use a name no longer than 20 characters.'));
});
const lines=(await readFile(events,'utf8')).trim().split('\n');
check('factory_start_tool_and_shutdown_lifecycle', {explicitBranch:true},
['factory-ready','session-start','preview-command','format-tool','blocked-long-label','session-shutdown'],lines);
const trustedFolder=join(project,'.pi','extensions','project-labels');
await mkdir(dirname(trustedFolder),{recursive:true});
await cp(folder,trustedFolder,{recursive:true});
const observedTrust=[];
for (const flag of ['--no-approve','--approve']) {
await run([],async(send,until)=>{
send('project-commands','get_commands');
const row=await until(entry=>entry.id==='project-commands');
observedTrust.push(row.data.commands.some(command=>command.name==='label-preview'));
},flag);
}
check('project_directory_extension_requires_trust',
{entry:'.pi/extensions/project-labels/index.ts',flags:['--no-approve','--approve']},
[false,true],observedTrust);
const settingsPath=join(profile,'settings.json');
const standalone=join(root,'separate-command.ts');
await writeFile(standalone, "export default function (pi) { pi.registerCommand('separate-label', {handler:async()=>{}}); }\n");
await writeFile(settingsPath,JSON.stringify({extensions:[standalone,folder]}));
await run([],async(send,until)=>{
send('configured-commands','get_commands');
const row=await until(entry=>entry.id==='configured-commands');
const names=new Set(row.data.commands.map(command=>command.name));
check('settings_loads_explicit_file_and_directory',
{configured:['separate-command.ts','explicit-extension/']},[true,true],
[names.has('separate-label'),names.has('label-preview')]);
});
await unlink(settingsPath);
const discovered=join(profile,'extensions','label-collection');
await mkdir(dirname(discovered),{recursive:true});
await cp(folder,discovered,{recursive:true});
await run([],async(send,until)=>{
send('auto','get_commands');
const row=await until(r=>r.id==='auto');
check('auto_discovers_directory_index_entry',{path:'extensions/label-collection/index.ts'},true,
row.data.commands.some(c=>c.name==='label-preview'));
});
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});
}
本例需在 Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、自编扩展与本机回环服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、自编扩展与本机回环服务。
入口文件:projects/pi-agent-extensions-lab/extension-lifecycle.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
extension-lifecycle.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows、Node.js 24.22.3、Pi 1.5.0、TypeBox、自编扩展与本机回环服务。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a275.zip
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip