@agimon-ai/doompi 0.0.1-alpha.10 → 0.0.1-alpha.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/extensionCompiler.cjs +2 -2
- package/dist/adapters/extensionCompiler.cjs.map +1 -1
- package/dist/adapters/extensionCompiler.mjs +2 -2
- package/dist/adapters/extensionCompiler.mjs.map +1 -1
- package/dist/entries/autoStop.cjs +1 -1
- package/dist/entries/autoStop.mjs +1 -1
- package/dist/entries/notifications.cjs +1 -1
- package/dist/entries/notifications.mjs +1 -1
- package/dist/extensions/entries/autoStop.cjs +1 -1
- package/dist/extensions/entries/autoStop.cjs.map +1 -1
- package/dist/extensions/entries/autoStop.d.cts.map +1 -1
- package/dist/extensions/entries/autoStop.d.mts.map +1 -1
- package/dist/extensions/entries/autoStop.mjs +1 -1
- package/dist/extensions/entries/autoStop.mjs.map +1 -1
- package/dist/extensions/entries/components/matrixPicker.cjs +1 -1
- package/dist/extensions/entries/components/matrixPicker.cjs.map +1 -1
- package/dist/extensions/entries/components/matrixPicker.d.cts.map +1 -1
- package/dist/extensions/entries/components/matrixPicker.d.mts.map +1 -1
- package/dist/extensions/entries/components/matrixPicker.mjs +1 -1
- package/dist/extensions/entries/components/matrixPicker.mjs.map +1 -1
- package/dist/extensions/entries/components/skillsOverlay.cjs +1 -1
- package/dist/extensions/entries/components/skillsOverlay.cjs.map +1 -1
- package/dist/extensions/entries/components/skillsOverlay.d.cts.map +1 -1
- package/dist/extensions/entries/components/skillsOverlay.d.mts.map +1 -1
- package/dist/extensions/entries/components/skillsOverlay.mjs +2 -2
- package/dist/extensions/entries/components/skillsOverlay.mjs.map +1 -1
- package/dist/extensions/entries/domains.cjs +1 -1
- package/dist/extensions/entries/domains.cjs.map +1 -1
- package/dist/extensions/entries/domains.mjs +1 -1
- package/dist/extensions/entries/domains.mjs.map +1 -1
- package/dist/extensions/entries/notifications.cjs +1 -1
- package/dist/extensions/entries/notifications.cjs.map +1 -1
- package/dist/extensions/entries/notifications.mjs +1 -1
- package/dist/extensions/entries/notifications.mjs.map +1 -1
- package/dist/services/extensionAssembler.cjs +1 -1
- package/dist/services/extensionAssembler.cjs.map +1 -1
- package/dist/services/extensionAssembler.d.cts +4 -1
- package/dist/services/extensionAssembler.d.cts.map +1 -1
- package/dist/services/extensionAssembler.d.mts +4 -1
- package/dist/services/extensionAssembler.d.mts.map +1 -1
- package/dist/services/extensionAssembler.mjs +1 -1
- package/dist/services/extensionAssembler.mjs.map +1 -1
- package/package.json +18 -18
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./modules/moduleResolution.cjs`);require(`../utils/index.cjs`);let n=require(`node:fs`);n=e.__toESM(n,1);let r=require(`node:url`),i=require(`node:path`);i=e.__toESM(i,1);let a=require(`node:module`),o=require(`node:crypto`);const s=[`.ts`,`.mts`,`.cts`],c=`.mjs`,l=`.json`,u=`\0doompi-extension-set`,d=`@agimon-ai/doompi-ui/extensionName`,f={"@mariozechner/pi-coding-agent":`@earendil-works/pi-coding-agent`,"@mariozechner/pi-tui":`@earendil-works/pi-tui`,"@mariozechner/pi-ai":`@earendil-works/pi-ai`,"@sinclair/typebox":`typebox`};function p(e){return s.some(t=>e.endsWith(t))}function m(e){for(let[t,n]of Object.entries(f)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}function h(e){let t=n.default.readFileSync(e);return(0,o.createHash)(`sha256`).update(`v4`).update(e).update(t).digest(`hex`).slice(0,16)}function g(e,t){let n=i.default.basename(e).replace(/\.[cm]?ts$/,``);return`${i.default.basename(i.default.dirname(e))}-${n}.${t}${c}`}const _=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function v(e){let n=t.optionalPackageEntry(`@earendil-works/pi-coding-agent`);if(n)try{return(0,a.createRequire)(n).resolve(e)}catch{return}}const y=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),b=new Set([`@agimon-ai/foundation-port-registry`,`@agimon-ai/foundation-process-registry`,`@agimon-ai/log-sink-mcp`,`@modelcontextprotocol/sdk`,`@narumitw/pi-tui-kit`,`@rmux/sdk`,`@tursodatabase/database`,`@tursodatabase/database-common`,`ajv`,`ajv-formats`,`gpt-tokenizer`,`highlight.js`,`hono`,`inversify`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),x=new Set(a.builtinModules.flatMap(e=>[e,`node:${e}`]));function S(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`doom-set`}function C(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function w(e){let t=e.split(i.default.sep).join(`/`),n=t.lastIndexOf(`/node_modules/`);if(n===-1)return;let r=t.slice(n+14).split(`/`),a=r.lastIndexOf(`node_modules`),o=a===-1?r:r.slice(a+1);return o[0]?.startsWith(`@`)?o.slice(0,2).join(`/`):o[0]}function T(){return{name:`doom-external-absolute`,async resolveId(e,n,r){if(e.startsWith(`.`)||i.default.isAbsolute(e)||e.startsWith(`node:`))return null;let a=m(e),o=C(a);if(o&&_.has(o)){let e=t.optionalPackageEntry(a);if(e)return{id:e,external:!0}}let s=await this.resolve(a,n,r);return!s||p(s.id)?null:{id:s.id,external:!0}}}}function E(e){try{let t=n.default.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function D(e,t,r){return e.version===t&&e.output===r&&n.default.existsSync(r)&&e.artifacts.every(e=>n.default.existsSync(e))}function O(e,t){return!D(e,`
|
|
2
|
-
`)}function R(e){return i.default.resolve(e).split(i.default.sep).join(`/`)}function z(e){return{name:`doom-set-external`,async resolveId(n,r,a){if(n===u)return null;if(x.has(n)||n.startsWith(`node:`))return{id:n,external:!0};if(i.default.isAbsolute(n)){let t=w(n);return t&&(_.has(t)||y.has(t)||b.has(t))?(e.add(n),{id:n,external:!0}):null}if(n.startsWith(`.`))return null;let o=m(n),s=C(o);if(s&&_.has(s)){let n=t.optionalPackageEntry(o);if(n)return e.add(n),{id:n,external:!0}}if(s===`typebox`){let t=v(o);if(t)return e.add(t),{id:t,external:!0}}if(s&&(y.has(s)||b.has(s))){let t=await this.resolve(o,r,a);if(t)return e.add(t.id),{id:t.id,external:!0}}return null}}}function B(e){return{name:`doom-set-inputs`,load(t){return i.default.isAbsolute(t)&&n.default.existsSync(t)&&e.add(t),null}}}function V(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e,t){if(Array.isArray(e)){for(let n of e)U(n,t);return}if(!H(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&H(n)&&n.type===`MetaProperty`&&H(n.meta)&&n.meta.name===`import`&&H(n.property)&&n.property.name===`meta`&&H(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))U(n,t)}function W(){return{name:`doom-original-import-meta-url`,transform(e,t){if(!i.default.isAbsolute(t)||!e.includes(`import.meta.url`))return null;let n=i.default.extname(t).toLowerCase(),a=n===`.tsx`?`tsx`:n===`.jsx`?`jsx`:p(t)?`ts`:`js`,o=[];if(U(this.parse(e,{lang:a}),o),o.length===0)return null;let s=JSON.stringify((0,r.pathToFileURL)(t).href),c=e;for(let e of o.sort((e,t)=>t.start-e.start))c=`${c.slice(0,e.start)}${s}${c.slice(e.end)}`;return c}}}async function G(e,t,r={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let a=e.map(e=>i.default.resolve(e)),s=i.default.join(t,`sets`);n.default.mkdirSync(s,{recursive:!0});let d=I(a),f=i.default.resolve(r.outputDirectory??s),p=S(r.outputName??`doom-set`);n.default.mkdirSync(f,{recursive:!0});let m=(0,o.createHash)(`sha256`).update(f).update(p).digest(`hex`).slice(0,16),h=i.default.join(s,`${d}.${m}${l}`),g=A(h);if(g&&O(g,a))return g.output;let _=new Set(a),v=L(a),{rolldown:y}=await import(`rolldown`),b=await y({input:u,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===u?e:null},load(e){return e===u?v:null}},z(_),W(),B(_)],onLog:V}),x;try{x=F(await b.generate(M(`${p}.[hash:16]${c}`)),f)}finally{await b.close()}let C=x.entry,w=[..._].map(E).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));return j(h,`${JSON.stringify({version:`
|
|
1
|
+
const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`./modules/moduleResolution.cjs`);require(`../utils/index.cjs`);let n=require(`node:fs`);n=e.__toESM(n,1);let r=require(`node:url`),i=require(`node:path`);i=e.__toESM(i,1);let a=require(`node:module`),o=require(`node:crypto`);const s=[`.ts`,`.mts`,`.cts`],c=`.mjs`,l=`.json`,u=`\0doompi-extension-set`,d=`@agimon-ai/doompi-ui/extensionName`,f={"@mariozechner/pi-coding-agent":`@earendil-works/pi-coding-agent`,"@mariozechner/pi-tui":`@earendil-works/pi-tui`,"@mariozechner/pi-ai":`@earendil-works/pi-ai`,"@sinclair/typebox":`typebox`};function p(e){return s.some(t=>e.endsWith(t))}function m(e){for(let[t,n]of Object.entries(f)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}function h(e){let t=n.default.readFileSync(e);return(0,o.createHash)(`sha256`).update(`v4`).update(e).update(t).digest(`hex`).slice(0,16)}function g(e,t){let n=i.default.basename(e).replace(/\.[cm]?ts$/,``);return`${i.default.basename(i.default.dirname(e))}-${n}.${t}${c}`}const _=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function v(e){let n=t.optionalPackageEntry(`@earendil-works/pi-coding-agent`);if(n)try{return(0,a.createRequire)(n).resolve(e)}catch{return}}const y=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),b=new Set([`@agimon-ai/foundation-port-registry`,`@agimon-ai/foundation-process-registry`,`@agimon-ai/log-sink-mcp`,`@modelcontextprotocol/sdk`,`@narumitw/pi-tui-kit`,`@rmux/sdk`,`@tursodatabase/database`,`@tursodatabase/database-common`,`ajv`,`ajv-formats`,`gpt-tokenizer`,`highlight.js`,`hono`,`inversify`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),x=new Set(a.builtinModules.flatMap(e=>[e,`node:${e}`]));function S(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`doom-set`}function C(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function w(e){let t=e.split(i.default.sep).join(`/`),n=t.lastIndexOf(`/node_modules/`);if(n===-1)return;let r=t.slice(n+14).split(`/`),a=r.lastIndexOf(`node_modules`),o=a===-1?r:r.slice(a+1);return o[0]?.startsWith(`@`)?o.slice(0,2).join(`/`):o[0]}function T(){return{name:`doom-external-absolute`,async resolveId(e,n,r){if(e.startsWith(`.`)||i.default.isAbsolute(e)||e.startsWith(`node:`))return null;let a=m(e),o=C(a);if(o&&_.has(o)){let e=t.optionalPackageEntry(a);if(e)return{id:e,external:!0}}let s=await this.resolve(a,n,r);return!s||p(s.id)?null:{id:s.id,external:!0}}}}function E(e){try{let t=n.default.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function D(e,t,r){return e.version===t&&e.output===r&&n.default.existsSync(r)&&e.artifacts.every(e=>n.default.existsSync(e))}function O(e,t){return!D(e,`v11`,e.output)||JSON.stringify(e.entries)!==JSON.stringify(t)?!1:e.inputs.every(e=>{let t=E(e.path);return t?.size===e.size&&t.mtimeMs===e.mtimeMs})}function k(e){try{let t=JSON.parse(n.default.readFileSync(e,`utf8`));return t&&typeof t.output==`string`&&Array.isArray(t.artifacts)?t:void 0}catch{return}}function A(e){let t=k(e);return t&&Array.isArray(t.entries)&&Array.isArray(t.inputs)?t:void 0}function j(e,t){n.default.mkdirSync(i.default.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;n.default.writeFileSync(r,t);try{n.default.renameSync(r,e)}catch(t){if(n.default.rmSync(r,{force:!0}),!n.default.existsSync(e))throw t}}function M(e){return{format:`esm`,sourcemap:!1,minify:!0,codeSplitting:!0,hashCharacters:`hex`,entryFileNames:e,chunkFileNames:`chunks/[name].[hash:16]${c}`,assetFileNames:`assets/[name].[hash:16][extname]`}}function N(e,t){let n=i.default.resolve(e,t.fileName),r=i.default.relative(e,n);if(r.startsWith(`..`)||i.default.isAbsolute(r))throw Error(`Rolldown emitted an artifact outside the output directory: ${t.fileName}`);return n}function P(e,t){try{let r=n.default.readFileSync(e),i=Buffer.from(t);return r.equals(i)}catch{return!1}}function F(e,t){let n=e.output.find(e=>e.type===`chunk`&&e.isEntry);if(!n||n.type!==`chunk`)throw Error(`Rolldown produced no extension entry`);let r=i.default.resolve(t),a=e.output.filter(e=>e!==n);for(let e of[...a,n]){let t=e.type===`chunk`?e.code:e.source,n=N(r,e);P(n,t)||j(n,t)}return{entry:N(r,n),artifacts:e.output.map(e=>N(r,e)).sort()}}function I(e){return(0,o.createHash)(`sha256`).update(`v11`).update(JSON.stringify(e.map(e=>i.default.resolve(e)))).digest(`hex`).slice(0,16)}function L(e){let n=t.optionalPackageEntry(d);if(!n)throw Error(`Cannot resolve ${d}`);let r=e.map(e=>`() => import(${JSON.stringify(R(e))})`),i=e.map(e=>JSON.stringify(e));return[`import { withExtensionSource } from ${JSON.stringify(R(n))};`,`const loaders = [${r.join(`,`)}];`,`const names = [${i.join(`,`)}];`,`function report(index, phase, startedAt, error) {`,` const elapsed = (performance.now() - startedAt).toFixed(1);`,` const detail = error instanceof Error ? ": " + error.message : error === undefined ? "" : ": " + String(error);`,` process.stderr.write("[doompi:timing] " + phase + " " + elapsed + "ms " + names[index] + detail + "\\n");`,`}`,`export default async function doompiExtensionSet(pi) {`,` const timings = process.env.DOOMPI_TIMING === "1" || process.env.PI_TIMING === "1";`,` const loaded = await Promise.all(loaders.map(async (load, index) => {`,` const startedAt = performance.now();`,` try {`,` const extension = await load();`,` if (timings) report(index, "import", startedAt);`,` return extension;`,` } catch (error) {`,` report(index, "import-error", startedAt, error);`,` return undefined;`,` }`,` }));`,` for (let index = 0; index < loaded.length; index += 1) {`,` const extension = loaded[index];`,` if (!extension) continue;`,` const startedAt = performance.now();`,` try {`,` const factory = extension.default;`,` if (typeof factory !== 'function') throw new Error('does not export an extension factory');`,` await factory(withExtensionSource(pi, names[index]));`,` if (timings) report(index, "factory", startedAt);`,` } catch (error) {`,` report(index, "factory-error", startedAt, error);`,` }`,` }`,`}`].join(`
|
|
2
|
+
`)}function R(e){return i.default.resolve(e).split(i.default.sep).join(`/`)}function z(e){return{name:`doom-set-external`,async resolveId(n,r,a){if(n===u)return null;if(x.has(n)||n.startsWith(`node:`))return{id:n,external:!0};if(i.default.isAbsolute(n)){let t=w(n);return t&&(_.has(t)||y.has(t)||b.has(t))?(e.add(n),{id:n,external:!0}):null}if(n.startsWith(`.`))return null;let o=m(n),s=C(o);if(s&&_.has(s)){let n=t.optionalPackageEntry(o);if(n)return e.add(n),{id:n,external:!0}}if(s===`typebox`){let t=v(o);if(t)return e.add(t),{id:t,external:!0}}if(s&&(y.has(s)||b.has(s))){let t=await this.resolve(o,r,a);if(t)return e.add(t.id),{id:t.id,external:!0}}return null}}}function B(e){return{name:`doom-set-inputs`,load(t){return i.default.isAbsolute(t)&&n.default.existsSync(t)&&e.add(t),null}}}function V(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e,t){if(Array.isArray(e)){for(let n of e)U(n,t);return}if(!H(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&H(n)&&n.type===`MetaProperty`&&H(n.meta)&&n.meta.name===`import`&&H(n.property)&&n.property.name===`meta`&&H(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))U(n,t)}function W(){return{name:`doom-original-import-meta-url`,transform(e,t){if(!i.default.isAbsolute(t)||!e.includes(`import.meta.url`))return null;let n=i.default.extname(t).toLowerCase(),a=n===`.tsx`?`tsx`:n===`.jsx`?`jsx`:p(t)?`ts`:`js`,o=[];if(U(this.parse(e,{lang:a}),o),o.length===0)return null;let s=JSON.stringify((0,r.pathToFileURL)(t).href),c=e;for(let e of o.sort((e,t)=>t.start-e.start))c=`${c.slice(0,e.start)}${s}${c.slice(e.end)}`;return c}}}async function G(e,t,r={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let a=e.map(e=>i.default.resolve(e)),s=i.default.join(t,`sets`);n.default.mkdirSync(s,{recursive:!0});let d=I(a),f=i.default.resolve(r.outputDirectory??s),p=S(r.outputName??`doom-set`);n.default.mkdirSync(f,{recursive:!0});let m=(0,o.createHash)(`sha256`).update(f).update(p).digest(`hex`).slice(0,16),h=i.default.join(s,`${d}.${m}${l}`),g=A(h);if(g&&O(g,a))return g.output;let _=new Set(a),v=L(a),{rolldown:y}=await import(`rolldown`),b=await y({input:u,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===u?e:null},load(e){return e===u?v:null}},z(_),W(),B(_)],onLog:V}),x;try{x=F(await b.generate(M(`${p}.[hash:16]${c}`)),f)}finally{await b.close()}let C=x.entry,w=[..._].map(E).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));return j(h,`${JSON.stringify({version:`v11`,entries:a,output:C,artifacts:x.artifacts,inputs:w},null,2)}\n`),C}async function K(e,t){if(!p(e))return e;n.default.mkdirSync(t,{recursive:!0});let r=g(e,h(e)),a=i.default.join(t,r),o=`${a}${l}`,s=k(o);if(s&&D(s,`v4`,a))return a;let{rolldown:c}=await import(`rolldown`),u=await c({input:e,platform:`node`,plugins:[T(),W()],onLog:V}),d;try{d=F(await u.generate(M(r)),t)}finally{await u.close()}return j(o,`${JSON.stringify({version:`v4`,output:a,artifacts:d.artifacts},null,2)}\n`),a}async function q(e,t){n.default.mkdirSync(t,{recursive:!0});let r={};for(let[n,i]of Object.entries(e))try{r[n]=await K(i,t)}catch{r[n]=i}return r}exports.compileExtensionSet=G,exports.compileResolvedEntries=q,exports.extensionSetKey=I;
|
|
3
3
|
//# sourceMappingURL=extensionCompiler.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extensionCompiler.cjs","names":["fs","path","optionalPackageEntry","builtinModules"],"sources":["../../src/adapters/extensionCompiler.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport { builtinModules, createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { LogLevel, LogOrStringHandler, OutputAsset, OutputChunk, RolldownLog, RolldownOutput } from 'rolldown';\nimport { optionalPackageEntry } from '../utils/index.ts';\n\n/**\n * Compiles TypeScript extensions into plain ESM ahead of the session.\n *\n * Pi loads extensions through jiti, which transpiles TypeScript at import time.\n * That works, but it costs a transform per module on a cold cache and makes Node\n * complain about type stripping under node_modules on every launch. Resolution\n * already knows the full extension list, so each TypeScript graph is compiled\n * to native ESM here and Pi imports it without a runtime transform. Lazy imports\n * remain separate content-addressed chunks so their evaluation semantics survive\n * compilation.\n *\n * Mode artifacts bundle their JavaScript dependencies. Node built-ins, native\n * packages, and Pi's shared runtime stay external; those imports are rewritten\n * to absolute paths so an artifact under `.pi/doom/dist` never relies on that\n * directory having its own `node_modules` tree.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst CACHE_VERSION = 'v4';\nconst SET_CACHE_VERSION = 'v10';\nconst HASH_LENGTH = 16;\nconst SET_DIRECTORY = 'sets';\nconst MANIFEST_SUFFIX = '.json';\nconst VIRTUAL_SET_ENTRY = '\\0doompi-extension-set';\nconst EXTENSION_SOURCE_HELPER = '@agimon-ai/doompi-ui/extensionName';\n\n/** Pi's former npm scope. The packages are the same, published under a new name. */\nconst PI_SCOPE_RENAMES: Readonly<Record<string, string>> = {\n '@mariozechner/pi-coding-agent': '@earendil-works/pi-coding-agent',\n '@mariozechner/pi-tui': '@earendil-works/pi-tui',\n '@mariozechner/pi-ai': '@earendil-works/pi-ai',\n '@sinclair/typebox': 'typebox',\n};\n\nexport function isTypeScriptEntry(entry: string): boolean {\n return TYPESCRIPT_SUFFIXES.some((suffix) => entry.endsWith(suffix));\n}\n\nfunction renameScope(specifier: string): string {\n for (const [before, after] of Object.entries(PI_SCOPE_RENAMES)) {\n if (specifier === before) return after;\n if (specifier.startsWith(`${before}/`)) return `${after}${specifier.slice(before.length)}`;\n }\n return specifier;\n}\n\n/**\n * Cache key for a compiled entry.\n *\n * The entry's own bytes are the only cheap signal that the extension changed; a\n * dependency edit is not visible without walking the graph, so an upgrade that\n * leaves the entry byte-identical is served from cache until the version below\n * is raised.\n */\nfunction cacheKey(entry: string): string {\n const source = fs.readFileSync(entry);\n return createHash('sha256').update(CACHE_VERSION).update(entry).update(source).digest('hex').slice(0, HASH_LENGTH);\n}\n\nfunction compiledName(entry: string, key: string): string {\n const base = path.basename(entry).replace(/\\.[cm]?ts$/, '');\n const parent = path.basename(path.dirname(entry));\n return `${parent}-${base}.${key}${COMPILED_SUFFIX}`;\n}\n\n/**\n * Packages that must resolve to the copy this harness runs, never to a second\n * one bundled into an extension. Pi owns the TUI and the session state, so a\n * duplicate renders into a different screen and mutates a different store.\n */\nconst HOSTED_PACKAGES = new Set(['@earendil-works/pi-coding-agent', '@earendil-works/pi-tui', '@earendil-works/pi-ai']);\n\n/**\n * Resolves packages Pi exposes to extensions as compatibility aliases.\n *\n * Extensions do not need to declare TypeBox themselves because Pi's loader\n * provides it as a virtual module. A dist bundle bypasses that loader, so it\n * resolves the same package against Pi's dependency tree and bundles it.\n */\nfunction piExtensionDependencyEntry(specifier: string): string | undefined {\n const piEntry = optionalPackageEntry('@earendil-works/pi-coding-agent');\n if (!piEntry) return undefined;\n try {\n return createRequire(piEntry).resolve(specifier);\n } catch {\n return undefined;\n }\n}\n\n/** Packages whose native binaries or runtime discovery cannot be rolled up. */\nconst NATIVE_PACKAGES = new Set([\n '@parcel/watcher',\n '@napi-rs/keyring',\n 'better-sqlite3',\n 'canvas',\n 'fsevents',\n 'isolated-vm',\n 'keytar',\n 'node-pty',\n 'onnxruntime-node',\n 'playwright',\n 'playwright-core',\n 'puppeteer',\n 'sharp',\n // TypeScript's Node system adapter reads CommonJS globals such as\n // __filename. Rolldown does not provide those globals when it folds the\n // adapter into the aggregate ESM extension, so keep the installed runtime\n // intact and import it by its resolved absolute path.\n 'typescript',\n]);\n\n/**\n * Dependency-heavy ESM runtimes that should retain their installed graph.\n *\n * Folding these packages into the aggregate creates dozens of generated chunks\n * that Node must parse and link before any extension factory can register. Node\n * can load the installed graph directly while still sharing its module cache.\n */\nconst STARTUP_EXTERNAL_PACKAGES = new Set([\n '@agimon-ai/foundation-port-registry',\n '@agimon-ai/foundation-process-registry',\n '@agimon-ai/log-sink-mcp',\n '@modelcontextprotocol/sdk',\n '@narumitw/pi-tui-kit',\n '@rmux/sdk',\n '@tursodatabase/database',\n '@tursodatabase/database-common',\n 'ajv',\n 'ajv-formats',\n 'gpt-tokenizer',\n 'highlight.js',\n 'hono',\n 'inversify',\n 'reflect-metadata',\n 'zod-to-json-schema',\n 'yaml',\n 'zod',\n]);\nconst NODE_BUILTINS = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));\n\ninterface InputFingerprint {\n path: string;\n size: number;\n mtimeMs: number;\n}\n\ninterface CompiledExtensionManifest {\n version: string;\n output: string;\n artifacts: string[];\n}\n\ninterface ExtensionSetManifest extends CompiledExtensionManifest {\n entries: string[];\n inputs: InputFingerprint[];\n}\n\nexport interface CompileExtensionSetOptions {\n /** Persistent artifact directory. Compiler manifests remain in cacheDirectory. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n}\n\nfunction safeOutputName(value: string): string {\n const normalized = value\n .trim()\n .replace(/[^a-zA-Z0-9._-]+/g, '-')\n .replace(/^[-.]+|[-.]+$/g, '');\n return normalized || 'doom-set';\n}\n\nfunction packageRootOf(specifier: string): string | undefined {\n const slash = specifier.startsWith('@') ? specifier.indexOf('/', specifier.indexOf('/') + 1) : specifier.indexOf('/');\n return slash === -1 ? specifier : specifier.slice(0, slash);\n}\n\nfunction packageRootFromPath(target: string): string | undefined {\n const normalized = target.split(path.sep).join('/');\n const marker = '/node_modules/';\n const offset = normalized.lastIndexOf(marker);\n if (offset === -1) return undefined;\n const parts = normalized.slice(offset + marker.length).split('/');\n // pnpm's first segment is a store key; the second node_modules marker names\n // the package that owns the file.\n const nested = parts.lastIndexOf('node_modules');\n const packageParts = nested === -1 ? parts : parts.slice(nested + 1);\n return packageParts[0]?.startsWith('@') ? packageParts.slice(0, 2).join('/') : packageParts[0];\n}\n\nfunction externalResolver() {\n return {\n name: 'doom-external-absolute',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier.startsWith('.') || path.isAbsolute(specifier) || specifier.startsWith('node:')) return null;\n const renamed = renameScope(specifier);\n\n // Host packages are resolved from this module, the way the rest of the\n // harness resolves them, because an extension written against Pi's former\n // scope does not have the current one in its own dependency tree.\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) return { id: hosted, external: true };\n }\n\n // Rolldown's resolver rather than `createRequire`, which cannot see an\n // ESM-only package that publishes no `require` condition and would send\n // Pi's own core into the bundle.\n const resolved = await this.resolve(renamed, importer, options);\n if (!resolved) return null;\n // A dependency that is itself TypeScript cannot be handed to Node either,\n // so it is bundled rather than externalised.\n if (isTypeScriptEntry(resolved.id)) return null;\n return { id: resolved.id, external: true };\n },\n };\n}\n\nfunction fingerprint(target: string): InputFingerprint | undefined {\n try {\n const stat = fs.statSync(target);\n if (!stat.isFile()) return undefined;\n return { path: target, size: stat.size, mtimeMs: stat.mtimeMs };\n } catch {\n return undefined;\n }\n}\n\nfunction artifactsAreFresh(manifest: CompiledExtensionManifest, version: string, output: string): boolean {\n return (\n manifest.version === version &&\n manifest.output === output &&\n fs.existsSync(output) &&\n manifest.artifacts.every((artifact) => fs.existsSync(artifact))\n );\n}\n\nfunction manifestIsFresh(manifest: ExtensionSetManifest, entries: string[]): boolean {\n if (!artifactsAreFresh(manifest, SET_CACHE_VERSION, manifest.output)) return false;\n if (JSON.stringify(manifest.entries) !== JSON.stringify(entries)) {\n return false;\n }\n return manifest.inputs.every((previous) => {\n const current = fingerprint(previous.path);\n return current?.size === previous.size && current.mtimeMs === previous.mtimeMs;\n });\n}\n\nfunction readCompiledExtensionManifest(manifestPath: string): CompiledExtensionManifest | undefined {\n try {\n const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as CompiledExtensionManifest;\n return parsed && typeof parsed.output === 'string' && Array.isArray(parsed.artifacts) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readSetManifest(manifestPath: string): ExtensionSetManifest | undefined {\n const parsed = readCompiledExtensionManifest(manifestPath) as ExtensionSetManifest | undefined;\n return parsed && Array.isArray(parsed.entries) && Array.isArray(parsed.inputs) ? parsed : undefined;\n}\n\nfunction writeAtomic(target: string, contents: string | Uint8Array): void {\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(temporary, contents);\n try {\n fs.renameSync(temporary, target);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n if (!fs.existsSync(target)) throw error;\n }\n}\n\ninterface CompiledGraph {\n entry: string;\n artifacts: string[];\n}\n\nfunction splitOutputOptions(entryFileNames: string) {\n return {\n format: 'esm' as const,\n sourcemap: false,\n minify: true,\n codeSplitting: true,\n hashCharacters: 'hex' as const,\n entryFileNames,\n chunkFileNames: `chunks/[name].[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`,\n assetFileNames: `assets/[name].[hash:${HASH_LENGTH}][extname]`,\n };\n}\n\nfunction artifactTarget(outputDirectory: string, artifact: OutputAsset | OutputChunk): string {\n const target = path.resolve(outputDirectory, artifact.fileName);\n const relative = path.relative(outputDirectory, target);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n throw new Error(`Rolldown emitted an artifact outside the output directory: ${artifact.fileName}`);\n }\n return target;\n}\n\nfunction artifactMatches(target: string, contents: string | Uint8Array): boolean {\n try {\n const current = fs.readFileSync(target);\n const generated = typeof contents === 'string' ? Buffer.from(contents) : Buffer.from(contents);\n return current.equals(generated);\n } catch {\n return false;\n }\n}\n\n/** Writes referenced chunks first so a visible entry always has a complete graph. */\nfunction writeCompiledGraph(generated: RolldownOutput, outputDirectory: string): CompiledGraph {\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry || entry.type !== 'chunk') throw new Error('Rolldown produced no extension entry');\n const root = path.resolve(outputDirectory);\n const remaining = generated.output.filter((artifact) => artifact !== entry);\n for (const artifact of [...remaining, entry]) {\n const contents = artifact.type === 'chunk' ? artifact.code : artifact.source;\n const target = artifactTarget(root, artifact);\n if (!artifactMatches(target, contents)) writeAtomic(target, contents);\n }\n return {\n entry: artifactTarget(root, entry),\n artifacts: generated.output.map((artifact) => artifactTarget(root, artifact)).sort(),\n };\n}\n\n/** Stable lookup key for one exact Pi load order. */\nexport function extensionSetKey(entries: readonly string[]): string {\n return createHash('sha256')\n .update(SET_CACHE_VERSION)\n .update(JSON.stringify(entries.map((entry) => path.resolve(entry))))\n .digest('hex')\n .slice(0, HASH_LENGTH);\n}\n\nfunction extensionSetSource(entries: readonly string[]): string {\n const helper = optionalPackageEntry(EXTENSION_SOURCE_HELPER);\n if (!helper) throw new Error(`Cannot resolve ${EXTENSION_SOURCE_HELPER}`);\n const loaders = entries.map((entry) => `() => import(${JSON.stringify(pathToImportSpecifier(entry))})`);\n const names = entries.map((entry) => JSON.stringify(entry));\n return [\n `import { withExtensionSource } from ${JSON.stringify(pathToImportSpecifier(helper))};`,\n `const loaders = [${loaders.join(',')}];`,\n `const names = [${names.join(',')}];`,\n 'function report(index, phase, startedAt, error) {',\n ' const elapsed = (performance.now() - startedAt).toFixed(1);',\n ' const detail = error instanceof Error ? \": \" + error.message : error === undefined ? \"\" : \": \" + String(error);',\n ' process.stderr.write(\"[doompi:timing] \" + phase + \" \" + elapsed + \"ms \" + names[index] + detail + \"\\\\n\");',\n '}',\n 'export default async function doompiExtensionSet(pi) {',\n ' const timings = process.env.DOOMPI_TIMING === \"1\" || process.env.PI_TIMING === \"1\";',\n ' const loaded = await Promise.all(loaders.map(async (load, index) => {',\n ' const startedAt = performance.now();',\n ' try {',\n ' const extension = await load();',\n ' if (timings) report(index, \"import\", startedAt);',\n ' return extension;',\n ' } catch (error) {',\n ' report(index, \"import-error\", startedAt, error);',\n ' return undefined;',\n ' }',\n ' }));',\n ' for (let index = 0; index < loaded.length; index += 1) {',\n ' const extension = loaded[index];',\n ' if (!extension) continue;',\n ' const startedAt = performance.now();',\n ' try {',\n ' const factory = extension.default ?? extension.notifications;',\n \" if (typeof factory !== 'function') throw new Error('does not export an extension factory');\",\n ' await factory(withExtensionSource(pi, names[index]));',\n ' if (timings) report(index, \"factory\", startedAt);',\n ' } catch (error) {',\n ' report(index, \"factory-error\", startedAt, error);',\n ' }',\n ' }',\n '}',\n ].join('\\n');\n}\n\nfunction pathToImportSpecifier(target: string): string {\n // Rolldown accepts absolute POSIX paths directly. Windows needs a file URL,\n // but replacing separators is enough for its platform-independent parser.\n return path.resolve(target).split(path.sep).join('/');\n}\n\nfunction setExternalResolver(inputs: Set<string>) {\n return {\n name: 'doom-set-external',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier === VIRTUAL_SET_ENTRY) return null;\n if (NODE_BUILTINS.has(specifier) || specifier.startsWith('node:')) {\n return { id: specifier, external: true };\n }\n\n if (path.isAbsolute(specifier)) {\n const root = packageRootFromPath(specifier);\n if (root && (HOSTED_PACKAGES.has(root) || NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n inputs.add(specifier);\n return { id: specifier, external: true };\n }\n return null;\n }\n if (specifier.startsWith('.')) return null;\n\n const renamed = renameScope(specifier);\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) {\n inputs.add(hosted);\n return { id: hosted, external: true };\n }\n }\n if (root === 'typebox') {\n const typebox = piExtensionDependencyEntry(renamed);\n if (typebox) {\n inputs.add(typebox);\n return { id: typebox, external: true };\n }\n }\n if (root && (NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n const resolved = await this.resolve(renamed, importer, options);\n if (resolved) {\n inputs.add(resolved.id);\n return { id: resolved.id, external: true };\n }\n }\n return null;\n },\n };\n}\n\nfunction inputCollector(inputs: Set<string>) {\n return {\n name: 'doom-set-inputs',\n load(id: string): null {\n if (path.isAbsolute(id) && fs.existsSync(id)) inputs.add(id);\n return null;\n },\n };\n}\n\n/** An unresolved bare import would otherwise become a broken dist external. */\nfunction failUnresolvedImport(_level: LogLevel, log: RolldownLog, handler: LogOrStringHandler): void {\n if (log.code === 'UNRESOLVED_IMPORT') handler('error', log);\n}\n\ninterface SourceRange {\n start: number;\n end: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction collectImportMetaUrlRanges(value: unknown, ranges: SourceRange[]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectImportMetaUrlRanges(item, ranges);\n return;\n }\n if (!isRecord(value)) return;\n\n const object = value.object;\n const property = value.property;\n if (\n value.type === 'MemberExpression' &&\n value.computed === false &&\n typeof value.start === 'number' &&\n typeof value.end === 'number' &&\n isRecord(object) &&\n object.type === 'MetaProperty' &&\n isRecord(object.meta) &&\n object.meta.name === 'import' &&\n isRecord(object.property) &&\n object.property.name === 'meta' &&\n isRecord(property) &&\n property.name === 'url'\n ) {\n ranges.push({ start: value.start, end: value.end });\n return;\n }\n\n for (const child of Object.values(value)) collectImportMetaUrlRanges(child, ranges);\n}\n\n/** Keeps package-owned resource lookup anchored to each original source file. */\nfunction preserveImportMetaUrl() {\n return {\n name: 'doom-original-import-meta-url',\n transform(\n this: {\n parse: (source: string, options?: { lang?: 'js' | 'jsx' | 'ts' | 'tsx' }) => unknown;\n },\n source: string,\n id: string,\n ): string | null {\n if (!path.isAbsolute(id) || !source.includes('import.meta.url')) return null;\n const extension = path.extname(id).toLowerCase();\n const lang = extension === '.tsx' ? 'tsx' : extension === '.jsx' ? 'jsx' : isTypeScriptEntry(id) ? 'ts' : 'js';\n const ranges: SourceRange[] = [];\n collectImportMetaUrlRanges(this.parse(source, { lang }), ranges);\n if (ranges.length === 0) return null;\n const replacement = JSON.stringify(pathToFileURL(id).href);\n let transformed = source;\n for (const range of ranges.sort((left, right) => right.start - left.start)) {\n transformed = `${transformed.slice(0, range.start)}${replacement}${transformed.slice(range.end)}`;\n }\n return transformed;\n },\n };\n}\n\n/**\n * Compiles an ordered extension set into one native ESM entry.\n *\n * The generated entry starts every module load together, then invokes factories\n * sequentially in activation order. Its manifest records every loaded module,\n * so a dependency edit invalidates the cache without running the compiler.\n */\nexport async function compileExtensionSet(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): Promise<string> {\n if (entries.length === 0) throw new Error('Cannot compile an empty extension set');\n const normalized = entries.map((entry) => path.resolve(entry));\n const setDirectory = path.join(cacheDirectory, SET_DIRECTORY);\n fs.mkdirSync(setDirectory, { recursive: true });\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? 'doom-set');\n fs.mkdirSync(outputDirectory, { recursive: true });\n // One graph can be emitted under several named mode artifacts. Keep their\n // cache records separate without changing extensionSetKey, which is the\n // runtime lookup key for an exact activation order.\n const outputKey = createHash('sha256').update(outputDirectory).update(outputName).digest('hex').slice(0, HASH_LENGTH);\n const manifestPath = path.join(setDirectory, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const inputs = new Set(normalized);\n const source = extensionSetSource(normalized);\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: VIRTUAL_SET_ENTRY,\n platform: 'node',\n plugins: [\n {\n name: 'doom-set-entry',\n resolveId(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? id : null;\n },\n load(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? source : null;\n },\n },\n setExternalResolver(inputs),\n preserveImportMetaUrl(),\n inputCollector(inputs),\n ],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`));\n compiled = writeCompiledGraph(generated, outputDirectory);\n } finally {\n await build.close();\n }\n\n const output = compiled.entry;\n const inputFingerprints = [...inputs]\n .map(fingerprint)\n .filter((value): value is InputFingerprint => value !== undefined)\n .sort((left, right) => left.path.localeCompare(right.path));\n writeAtomic(\n manifestPath,\n `${JSON.stringify(\n {\n version: SET_CACHE_VERSION,\n entries: normalized,\n output,\n artifacts: compiled.artifacts,\n inputs: inputFingerprints,\n },\n null,\n 2,\n )}\\n`,\n );\n return output;\n}\n\n/**\n * Bundles `entry` into `cacheDirectory` and returns the compiled path.\n *\n * Non-TypeScript entries are returned untouched. A cache hit skips the build.\n */\nexport async function compileExtension(entry: string, cacheDirectory: string): Promise<string> {\n if (!isTypeScriptEntry(entry)) return entry;\n\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const outputName = compiledName(entry, cacheKey(entry));\n const output = path.join(cacheDirectory, outputName);\n const manifestPath = `${output}${MANIFEST_SUFFIX}`;\n const previous = readCompiledExtensionManifest(manifestPath);\n if (previous && artifactsAreFresh(previous, CACHE_VERSION, output)) return output;\n\n // Rolldown loads a native module and a sizeable parser graph. Sync is the\n // only command that needs it, and a cache hit does not, so keep it off every\n // other CLI startup path.\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: entry,\n platform: 'node',\n plugins: [externalResolver(), preserveImportMetaUrl()],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(outputName));\n compiled = writeCompiledGraph(generated, cacheDirectory);\n } finally {\n await build.close();\n }\n writeAtomic(\n manifestPath,\n `${JSON.stringify({ version: CACHE_VERSION, output, artifacts: compiled.artifacts }, null, 2)}\\n`,\n );\n return output;\n}\n\n/**\n * Compiles every TypeScript entry in a resolution map, leaving the rest as-is.\n *\n * A failure is not fatal: the original path is kept so Pi falls back to loading\n * the TypeScript through jiti, which is what it did before this existed.\n */\nexport async function compileResolvedEntries(\n resolved: Record<string, string>,\n cacheDirectory: string,\n): Promise<Record<string, string>> {\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const compiled: Record<string, string> = {};\n for (const [key, target] of Object.entries(resolved)) {\n try {\n compiled[key] = await compileExtension(target, cacheDirectory);\n } catch {\n compiled[key] = target;\n }\n }\n return compiled;\n}\n"],"mappings":"iSAyBA,MAAM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AAE,QAAS,KAAe,SAAQ,UAAW,EAAS,UAAW,CAAE,KAAM,EAAE,CAAC,IAC/F,CACM,EAST,eAAsB,EACpB,EACA,EACiC,CACjC,EAAA,QAAG,UAAU,EAAgB,CAAE,UAAW,GAAM,CAAC,CACjD,IAAM,EAAmC,EAAE,CAC3C,IAAK,GAAM,CAAC,EAAK,KAAW,OAAO,QAAQ,EAAS,CAClD,GAAI,CACF,EAAS,GAAO,MAAM,EAAiB,EAAQ,EAAe,MACxD,CACN,EAAS,GAAO,EAGpB,OAAO"}
|
|
1
|
+
{"version":3,"file":"extensionCompiler.cjs","names":["fs","path","optionalPackageEntry","builtinModules"],"sources":["../../src/adapters/extensionCompiler.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport { builtinModules, createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { LogLevel, LogOrStringHandler, OutputAsset, OutputChunk, RolldownLog, RolldownOutput } from 'rolldown';\nimport { optionalPackageEntry } from '../utils/index.ts';\n\n/**\n * Compiles TypeScript extensions into plain ESM ahead of the session.\n *\n * Pi loads extensions through jiti, which transpiles TypeScript at import time.\n * That works, but it costs a transform per module on a cold cache and makes Node\n * complain about type stripping under node_modules on every launch. Resolution\n * already knows the full extension list, so each TypeScript graph is compiled\n * to native ESM here and Pi imports it without a runtime transform. Lazy imports\n * remain separate content-addressed chunks so their evaluation semantics survive\n * compilation.\n *\n * Mode artifacts bundle their JavaScript dependencies. Node built-ins, native\n * packages, and Pi's shared runtime stay external; those imports are rewritten\n * to absolute paths so an artifact under `.pi/doom/dist` never relies on that\n * directory having its own `node_modules` tree.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst CACHE_VERSION = 'v4';\nconst SET_CACHE_VERSION = 'v11';\nconst HASH_LENGTH = 16;\nconst SET_DIRECTORY = 'sets';\nconst MANIFEST_SUFFIX = '.json';\nconst VIRTUAL_SET_ENTRY = '\\0doompi-extension-set';\nconst EXTENSION_SOURCE_HELPER = '@agimon-ai/doompi-ui/extensionName';\n\n/** Pi's former npm scope. The packages are the same, published under a new name. */\nconst PI_SCOPE_RENAMES: Readonly<Record<string, string>> = {\n '@mariozechner/pi-coding-agent': '@earendil-works/pi-coding-agent',\n '@mariozechner/pi-tui': '@earendil-works/pi-tui',\n '@mariozechner/pi-ai': '@earendil-works/pi-ai',\n '@sinclair/typebox': 'typebox',\n};\n\nexport function isTypeScriptEntry(entry: string): boolean {\n return TYPESCRIPT_SUFFIXES.some((suffix) => entry.endsWith(suffix));\n}\n\nfunction renameScope(specifier: string): string {\n for (const [before, after] of Object.entries(PI_SCOPE_RENAMES)) {\n if (specifier === before) return after;\n if (specifier.startsWith(`${before}/`)) return `${after}${specifier.slice(before.length)}`;\n }\n return specifier;\n}\n\n/**\n * Cache key for a compiled entry.\n *\n * The entry's own bytes are the only cheap signal that the extension changed; a\n * dependency edit is not visible without walking the graph, so an upgrade that\n * leaves the entry byte-identical is served from cache until the version below\n * is raised.\n */\nfunction cacheKey(entry: string): string {\n const source = fs.readFileSync(entry);\n return createHash('sha256').update(CACHE_VERSION).update(entry).update(source).digest('hex').slice(0, HASH_LENGTH);\n}\n\nfunction compiledName(entry: string, key: string): string {\n const base = path.basename(entry).replace(/\\.[cm]?ts$/, '');\n const parent = path.basename(path.dirname(entry));\n return `${parent}-${base}.${key}${COMPILED_SUFFIX}`;\n}\n\n/**\n * Packages that must resolve to the copy this harness runs, never to a second\n * one bundled into an extension. Pi owns the TUI and the session state, so a\n * duplicate renders into a different screen and mutates a different store.\n */\nconst HOSTED_PACKAGES = new Set(['@earendil-works/pi-coding-agent', '@earendil-works/pi-tui', '@earendil-works/pi-ai']);\n\n/**\n * Resolves packages Pi exposes to extensions as compatibility aliases.\n *\n * Extensions do not need to declare TypeBox themselves because Pi's loader\n * provides it as a virtual module. A dist bundle bypasses that loader, so it\n * resolves the same package against Pi's dependency tree and bundles it.\n */\nfunction piExtensionDependencyEntry(specifier: string): string | undefined {\n const piEntry = optionalPackageEntry('@earendil-works/pi-coding-agent');\n if (!piEntry) return undefined;\n try {\n return createRequire(piEntry).resolve(specifier);\n } catch {\n return undefined;\n }\n}\n\n/** Packages whose native binaries or runtime discovery cannot be rolled up. */\nconst NATIVE_PACKAGES = new Set([\n '@parcel/watcher',\n '@napi-rs/keyring',\n 'better-sqlite3',\n 'canvas',\n 'fsevents',\n 'isolated-vm',\n 'keytar',\n 'node-pty',\n 'onnxruntime-node',\n 'playwright',\n 'playwright-core',\n 'puppeteer',\n 'sharp',\n // TypeScript's Node system adapter reads CommonJS globals such as\n // __filename. Rolldown does not provide those globals when it folds the\n // adapter into the aggregate ESM extension, so keep the installed runtime\n // intact and import it by its resolved absolute path.\n 'typescript',\n]);\n\n/**\n * Dependency-heavy ESM runtimes that should retain their installed graph.\n *\n * Folding these packages into the aggregate creates dozens of generated chunks\n * that Node must parse and link before any extension factory can register. Node\n * can load the installed graph directly while still sharing its module cache.\n */\nconst STARTUP_EXTERNAL_PACKAGES = new Set([\n '@agimon-ai/foundation-port-registry',\n '@agimon-ai/foundation-process-registry',\n '@agimon-ai/log-sink-mcp',\n '@modelcontextprotocol/sdk',\n '@narumitw/pi-tui-kit',\n '@rmux/sdk',\n '@tursodatabase/database',\n '@tursodatabase/database-common',\n 'ajv',\n 'ajv-formats',\n 'gpt-tokenizer',\n 'highlight.js',\n 'hono',\n 'inversify',\n 'reflect-metadata',\n 'zod-to-json-schema',\n 'yaml',\n 'zod',\n]);\nconst NODE_BUILTINS = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));\n\ninterface InputFingerprint {\n path: string;\n size: number;\n mtimeMs: number;\n}\n\ninterface CompiledExtensionManifest {\n version: string;\n output: string;\n artifacts: string[];\n}\n\ninterface ExtensionSetManifest extends CompiledExtensionManifest {\n entries: string[];\n inputs: InputFingerprint[];\n}\n\nexport interface CompileExtensionSetOptions {\n /** Persistent artifact directory. Compiler manifests remain in cacheDirectory. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n}\n\nfunction safeOutputName(value: string): string {\n const normalized = value\n .trim()\n .replace(/[^a-zA-Z0-9._-]+/g, '-')\n .replace(/^[-.]+|[-.]+$/g, '');\n return normalized || 'doom-set';\n}\n\nfunction packageRootOf(specifier: string): string | undefined {\n const slash = specifier.startsWith('@') ? specifier.indexOf('/', specifier.indexOf('/') + 1) : specifier.indexOf('/');\n return slash === -1 ? specifier : specifier.slice(0, slash);\n}\n\nfunction packageRootFromPath(target: string): string | undefined {\n const normalized = target.split(path.sep).join('/');\n const marker = '/node_modules/';\n const offset = normalized.lastIndexOf(marker);\n if (offset === -1) return undefined;\n const parts = normalized.slice(offset + marker.length).split('/');\n // pnpm's first segment is a store key; the second node_modules marker names\n // the package that owns the file.\n const nested = parts.lastIndexOf('node_modules');\n const packageParts = nested === -1 ? parts : parts.slice(nested + 1);\n return packageParts[0]?.startsWith('@') ? packageParts.slice(0, 2).join('/') : packageParts[0];\n}\n\nfunction externalResolver() {\n return {\n name: 'doom-external-absolute',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier.startsWith('.') || path.isAbsolute(specifier) || specifier.startsWith('node:')) return null;\n const renamed = renameScope(specifier);\n\n // Host packages are resolved from this module, the way the rest of the\n // harness resolves them, because an extension written against Pi's former\n // scope does not have the current one in its own dependency tree.\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) return { id: hosted, external: true };\n }\n\n // Rolldown's resolver rather than `createRequire`, which cannot see an\n // ESM-only package that publishes no `require` condition and would send\n // Pi's own core into the bundle.\n const resolved = await this.resolve(renamed, importer, options);\n if (!resolved) return null;\n // A dependency that is itself TypeScript cannot be handed to Node either,\n // so it is bundled rather than externalised.\n if (isTypeScriptEntry(resolved.id)) return null;\n return { id: resolved.id, external: true };\n },\n };\n}\n\nfunction fingerprint(target: string): InputFingerprint | undefined {\n try {\n const stat = fs.statSync(target);\n if (!stat.isFile()) return undefined;\n return { path: target, size: stat.size, mtimeMs: stat.mtimeMs };\n } catch {\n return undefined;\n }\n}\n\nfunction artifactsAreFresh(manifest: CompiledExtensionManifest, version: string, output: string): boolean {\n return (\n manifest.version === version &&\n manifest.output === output &&\n fs.existsSync(output) &&\n manifest.artifacts.every((artifact) => fs.existsSync(artifact))\n );\n}\n\nfunction manifestIsFresh(manifest: ExtensionSetManifest, entries: string[]): boolean {\n if (!artifactsAreFresh(manifest, SET_CACHE_VERSION, manifest.output)) return false;\n if (JSON.stringify(manifest.entries) !== JSON.stringify(entries)) {\n return false;\n }\n return manifest.inputs.every((previous) => {\n const current = fingerprint(previous.path);\n return current?.size === previous.size && current.mtimeMs === previous.mtimeMs;\n });\n}\n\nfunction readCompiledExtensionManifest(manifestPath: string): CompiledExtensionManifest | undefined {\n try {\n const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as CompiledExtensionManifest;\n return parsed && typeof parsed.output === 'string' && Array.isArray(parsed.artifacts) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readSetManifest(manifestPath: string): ExtensionSetManifest | undefined {\n const parsed = readCompiledExtensionManifest(manifestPath) as ExtensionSetManifest | undefined;\n return parsed && Array.isArray(parsed.entries) && Array.isArray(parsed.inputs) ? parsed : undefined;\n}\n\nfunction writeAtomic(target: string, contents: string | Uint8Array): void {\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(temporary, contents);\n try {\n fs.renameSync(temporary, target);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n if (!fs.existsSync(target)) throw error;\n }\n}\n\ninterface CompiledGraph {\n entry: string;\n artifacts: string[];\n}\n\nfunction splitOutputOptions(entryFileNames: string) {\n return {\n format: 'esm' as const,\n sourcemap: false,\n minify: true,\n codeSplitting: true,\n hashCharacters: 'hex' as const,\n entryFileNames,\n chunkFileNames: `chunks/[name].[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`,\n assetFileNames: `assets/[name].[hash:${HASH_LENGTH}][extname]`,\n };\n}\n\nfunction artifactTarget(outputDirectory: string, artifact: OutputAsset | OutputChunk): string {\n const target = path.resolve(outputDirectory, artifact.fileName);\n const relative = path.relative(outputDirectory, target);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n throw new Error(`Rolldown emitted an artifact outside the output directory: ${artifact.fileName}`);\n }\n return target;\n}\n\nfunction artifactMatches(target: string, contents: string | Uint8Array): boolean {\n try {\n const current = fs.readFileSync(target);\n const generated = typeof contents === 'string' ? Buffer.from(contents) : Buffer.from(contents);\n return current.equals(generated);\n } catch {\n return false;\n }\n}\n\n/** Writes referenced chunks first so a visible entry always has a complete graph. */\nfunction writeCompiledGraph(generated: RolldownOutput, outputDirectory: string): CompiledGraph {\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry || entry.type !== 'chunk') throw new Error('Rolldown produced no extension entry');\n const root = path.resolve(outputDirectory);\n const remaining = generated.output.filter((artifact) => artifact !== entry);\n for (const artifact of [...remaining, entry]) {\n const contents = artifact.type === 'chunk' ? artifact.code : artifact.source;\n const target = artifactTarget(root, artifact);\n if (!artifactMatches(target, contents)) writeAtomic(target, contents);\n }\n return {\n entry: artifactTarget(root, entry),\n artifacts: generated.output.map((artifact) => artifactTarget(root, artifact)).sort(),\n };\n}\n\n/** Stable lookup key for one exact Pi load order. */\nexport function extensionSetKey(entries: readonly string[]): string {\n return createHash('sha256')\n .update(SET_CACHE_VERSION)\n .update(JSON.stringify(entries.map((entry) => path.resolve(entry))))\n .digest('hex')\n .slice(0, HASH_LENGTH);\n}\n\nfunction extensionSetSource(entries: readonly string[]): string {\n const helper = optionalPackageEntry(EXTENSION_SOURCE_HELPER);\n if (!helper) throw new Error(`Cannot resolve ${EXTENSION_SOURCE_HELPER}`);\n const loaders = entries.map((entry) => `() => import(${JSON.stringify(pathToImportSpecifier(entry))})`);\n const names = entries.map((entry) => JSON.stringify(entry));\n return [\n `import { withExtensionSource } from ${JSON.stringify(pathToImportSpecifier(helper))};`,\n `const loaders = [${loaders.join(',')}];`,\n `const names = [${names.join(',')}];`,\n 'function report(index, phase, startedAt, error) {',\n ' const elapsed = (performance.now() - startedAt).toFixed(1);',\n ' const detail = error instanceof Error ? \": \" + error.message : error === undefined ? \"\" : \": \" + String(error);',\n ' process.stderr.write(\"[doompi:timing] \" + phase + \" \" + elapsed + \"ms \" + names[index] + detail + \"\\\\n\");',\n '}',\n 'export default async function doompiExtensionSet(pi) {',\n ' const timings = process.env.DOOMPI_TIMING === \"1\" || process.env.PI_TIMING === \"1\";',\n ' const loaded = await Promise.all(loaders.map(async (load, index) => {',\n ' const startedAt = performance.now();',\n ' try {',\n ' const extension = await load();',\n ' if (timings) report(index, \"import\", startedAt);',\n ' return extension;',\n ' } catch (error) {',\n ' report(index, \"import-error\", startedAt, error);',\n ' return undefined;',\n ' }',\n ' }));',\n ' for (let index = 0; index < loaded.length; index += 1) {',\n ' const extension = loaded[index];',\n ' if (!extension) continue;',\n ' const startedAt = performance.now();',\n ' try {',\n ' const factory = extension.default;',\n \" if (typeof factory !== 'function') throw new Error('does not export an extension factory');\",\n ' await factory(withExtensionSource(pi, names[index]));',\n ' if (timings) report(index, \"factory\", startedAt);',\n ' } catch (error) {',\n ' report(index, \"factory-error\", startedAt, error);',\n ' }',\n ' }',\n '}',\n ].join('\\n');\n}\n\nfunction pathToImportSpecifier(target: string): string {\n // Rolldown accepts absolute POSIX paths directly. Windows needs a file URL,\n // but replacing separators is enough for its platform-independent parser.\n return path.resolve(target).split(path.sep).join('/');\n}\n\nfunction setExternalResolver(inputs: Set<string>) {\n return {\n name: 'doom-set-external',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier === VIRTUAL_SET_ENTRY) return null;\n if (NODE_BUILTINS.has(specifier) || specifier.startsWith('node:')) {\n return { id: specifier, external: true };\n }\n\n if (path.isAbsolute(specifier)) {\n const root = packageRootFromPath(specifier);\n if (root && (HOSTED_PACKAGES.has(root) || NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n inputs.add(specifier);\n return { id: specifier, external: true };\n }\n return null;\n }\n if (specifier.startsWith('.')) return null;\n\n const renamed = renameScope(specifier);\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) {\n inputs.add(hosted);\n return { id: hosted, external: true };\n }\n }\n if (root === 'typebox') {\n const typebox = piExtensionDependencyEntry(renamed);\n if (typebox) {\n inputs.add(typebox);\n return { id: typebox, external: true };\n }\n }\n if (root && (NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n const resolved = await this.resolve(renamed, importer, options);\n if (resolved) {\n inputs.add(resolved.id);\n return { id: resolved.id, external: true };\n }\n }\n return null;\n },\n };\n}\n\nfunction inputCollector(inputs: Set<string>) {\n return {\n name: 'doom-set-inputs',\n load(id: string): null {\n if (path.isAbsolute(id) && fs.existsSync(id)) inputs.add(id);\n return null;\n },\n };\n}\n\n/** An unresolved bare import would otherwise become a broken dist external. */\nfunction failUnresolvedImport(_level: LogLevel, log: RolldownLog, handler: LogOrStringHandler): void {\n if (log.code === 'UNRESOLVED_IMPORT') handler('error', log);\n}\n\ninterface SourceRange {\n start: number;\n end: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction collectImportMetaUrlRanges(value: unknown, ranges: SourceRange[]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectImportMetaUrlRanges(item, ranges);\n return;\n }\n if (!isRecord(value)) return;\n\n const object = value.object;\n const property = value.property;\n if (\n value.type === 'MemberExpression' &&\n value.computed === false &&\n typeof value.start === 'number' &&\n typeof value.end === 'number' &&\n isRecord(object) &&\n object.type === 'MetaProperty' &&\n isRecord(object.meta) &&\n object.meta.name === 'import' &&\n isRecord(object.property) &&\n object.property.name === 'meta' &&\n isRecord(property) &&\n property.name === 'url'\n ) {\n ranges.push({ start: value.start, end: value.end });\n return;\n }\n\n for (const child of Object.values(value)) collectImportMetaUrlRanges(child, ranges);\n}\n\n/** Keeps package-owned resource lookup anchored to each original source file. */\nfunction preserveImportMetaUrl() {\n return {\n name: 'doom-original-import-meta-url',\n transform(\n this: {\n parse: (source: string, options?: { lang?: 'js' | 'jsx' | 'ts' | 'tsx' }) => unknown;\n },\n source: string,\n id: string,\n ): string | null {\n if (!path.isAbsolute(id) || !source.includes('import.meta.url')) return null;\n const extension = path.extname(id).toLowerCase();\n const lang = extension === '.tsx' ? 'tsx' : extension === '.jsx' ? 'jsx' : isTypeScriptEntry(id) ? 'ts' : 'js';\n const ranges: SourceRange[] = [];\n collectImportMetaUrlRanges(this.parse(source, { lang }), ranges);\n if (ranges.length === 0) return null;\n const replacement = JSON.stringify(pathToFileURL(id).href);\n let transformed = source;\n for (const range of ranges.sort((left, right) => right.start - left.start)) {\n transformed = `${transformed.slice(0, range.start)}${replacement}${transformed.slice(range.end)}`;\n }\n return transformed;\n },\n };\n}\n\n/**\n * Compiles an ordered extension set into one native ESM entry.\n *\n * The generated entry starts every module load together, then invokes factories\n * sequentially in activation order. Its manifest records every loaded module,\n * so a dependency edit invalidates the cache without running the compiler.\n */\nexport async function compileExtensionSet(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): Promise<string> {\n if (entries.length === 0) throw new Error('Cannot compile an empty extension set');\n const normalized = entries.map((entry) => path.resolve(entry));\n const setDirectory = path.join(cacheDirectory, SET_DIRECTORY);\n fs.mkdirSync(setDirectory, { recursive: true });\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? 'doom-set');\n fs.mkdirSync(outputDirectory, { recursive: true });\n // One graph can be emitted under several named mode artifacts. Keep their\n // cache records separate without changing extensionSetKey, which is the\n // runtime lookup key for an exact activation order.\n const outputKey = createHash('sha256').update(outputDirectory).update(outputName).digest('hex').slice(0, HASH_LENGTH);\n const manifestPath = path.join(setDirectory, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const inputs = new Set(normalized);\n const source = extensionSetSource(normalized);\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: VIRTUAL_SET_ENTRY,\n platform: 'node',\n plugins: [\n {\n name: 'doom-set-entry',\n resolveId(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? id : null;\n },\n load(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? source : null;\n },\n },\n setExternalResolver(inputs),\n preserveImportMetaUrl(),\n inputCollector(inputs),\n ],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`));\n compiled = writeCompiledGraph(generated, outputDirectory);\n } finally {\n await build.close();\n }\n\n const output = compiled.entry;\n const inputFingerprints = [...inputs]\n .map(fingerprint)\n .filter((value): value is InputFingerprint => value !== undefined)\n .sort((left, right) => left.path.localeCompare(right.path));\n writeAtomic(\n manifestPath,\n `${JSON.stringify(\n {\n version: SET_CACHE_VERSION,\n entries: normalized,\n output,\n artifacts: compiled.artifacts,\n inputs: inputFingerprints,\n },\n null,\n 2,\n )}\\n`,\n );\n return output;\n}\n\n/**\n * Bundles `entry` into `cacheDirectory` and returns the compiled path.\n *\n * Non-TypeScript entries are returned untouched. A cache hit skips the build.\n */\nexport async function compileExtension(entry: string, cacheDirectory: string): Promise<string> {\n if (!isTypeScriptEntry(entry)) return entry;\n\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const outputName = compiledName(entry, cacheKey(entry));\n const output = path.join(cacheDirectory, outputName);\n const manifestPath = `${output}${MANIFEST_SUFFIX}`;\n const previous = readCompiledExtensionManifest(manifestPath);\n if (previous && artifactsAreFresh(previous, CACHE_VERSION, output)) return output;\n\n // Rolldown loads a native module and a sizeable parser graph. Sync is the\n // only command that needs it, and a cache hit does not, so keep it off every\n // other CLI startup path.\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: entry,\n platform: 'node',\n plugins: [externalResolver(), preserveImportMetaUrl()],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(outputName));\n compiled = writeCompiledGraph(generated, cacheDirectory);\n } finally {\n await build.close();\n }\n writeAtomic(\n manifestPath,\n `${JSON.stringify({ version: CACHE_VERSION, output, artifacts: compiled.artifacts }, null, 2)}\\n`,\n );\n return output;\n}\n\n/**\n * Compiles every TypeScript entry in a resolution map, leaving the rest as-is.\n *\n * A failure is not fatal: the original path is kept so Pi falls back to loading\n * the TypeScript through jiti, which is what it did before this existed.\n */\nexport async function compileResolvedEntries(\n resolved: Record<string, string>,\n cacheDirectory: string,\n): Promise<Record<string, string>> {\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const compiled: Record<string, string> = {};\n for (const [key, target] of Object.entries(resolved)) {\n try {\n compiled[key] = await compileExtension(target, cacheDirectory);\n } catch {\n compiled[key] = target;\n }\n }\n return compiled;\n}\n"],"mappings":"iSAyBA,MAAM,EAAsB,CAAC,MAAO,OAAQ,OAAO,CAC7C,EAAkB,OAKlB,EAAkB,QAClB,EAAoB,yBACpB,EAA0B,qCAG1B,EAAqD,CACzD,gCAAiC,kCACjC,uBAAwB,yBACxB,sBAAuB,wBACvB,oBAAqB,UACtB,CAED,SAAgB,EAAkB,EAAwB,CACxD,OAA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AC,EAAK,KAAW,OAAO,QAAQ,EAAS,CAClD,GAAI,CACF,EAAS,GAAO,MAAM,EAAiB,EAAQ,EAAe,MACxD,CACN,EAAS,GAAO,EAGpB,OAAO"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{optionalPackageEntry as e}from"./modules/moduleResolution.mjs";import"../utils/index.mjs";import{builtinModules as t,createRequire as n}from"node:module";import r from"node:fs";import{pathToFileURL as i}from"node:url";import a from"node:path";import{createHash as o}from"node:crypto";const s=[`.ts`,`.mts`,`.cts`],c=`.mjs`,l=`.json`,u=`\0doompi-extension-set`,d=`@agimon-ai/doompi-ui/extensionName`,f={"@mariozechner/pi-coding-agent":`@earendil-works/pi-coding-agent`,"@mariozechner/pi-tui":`@earendil-works/pi-tui`,"@mariozechner/pi-ai":`@earendil-works/pi-ai`,"@sinclair/typebox":`typebox`};function p(e){return s.some(t=>e.endsWith(t))}function m(e){for(let[t,n]of Object.entries(f)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}function h(e){let t=r.readFileSync(e);return o(`sha256`).update(`v4`).update(e).update(t).digest(`hex`).slice(0,16)}function g(e,t){let n=a.basename(e).replace(/\.[cm]?ts$/,``);return`${a.basename(a.dirname(e))}-${n}.${t}${c}`}const _=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function v(t){let r=e(`@earendil-works/pi-coding-agent`);if(r)try{return n(r).resolve(t)}catch{return}}const y=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),b=new Set([`@agimon-ai/foundation-port-registry`,`@agimon-ai/foundation-process-registry`,`@agimon-ai/log-sink-mcp`,`@modelcontextprotocol/sdk`,`@narumitw/pi-tui-kit`,`@rmux/sdk`,`@tursodatabase/database`,`@tursodatabase/database-common`,`ajv`,`ajv-formats`,`gpt-tokenizer`,`highlight.js`,`hono`,`inversify`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),x=new Set(t.flatMap(e=>[e,`node:${e}`]));function S(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`doom-set`}function C(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function w(e){let t=e.split(a.sep).join(`/`),n=t.lastIndexOf(`/node_modules/`);if(n===-1)return;let r=t.slice(n+14).split(`/`),i=r.lastIndexOf(`node_modules`),o=i===-1?r:r.slice(i+1);return o[0]?.startsWith(`@`)?o.slice(0,2).join(`/`):o[0]}function T(){return{name:`doom-external-absolute`,async resolveId(t,n,r){if(t.startsWith(`.`)||a.isAbsolute(t)||t.startsWith(`node:`))return null;let i=m(t),o=C(i);if(o&&_.has(o)){let t=e(i);if(t)return{id:t,external:!0}}let s=await this.resolve(i,n,r);return!s||p(s.id)?null:{id:s.id,external:!0}}}}function E(e){try{let t=r.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function D(e,t,n){return e.version===t&&e.output===n&&r.existsSync(n)&&e.artifacts.every(e=>r.existsSync(e))}function O(e,t){return!D(e,`
|
|
2
|
-
`)}function R(e){return a.resolve(e).split(a.sep).join(`/`)}function z(t){return{name:`doom-set-external`,async resolveId(n,r,i){if(n===u)return null;if(x.has(n)||n.startsWith(`node:`))return{id:n,external:!0};if(a.isAbsolute(n)){let e=w(n);return e&&(_.has(e)||y.has(e)||b.has(e))?(t.add(n),{id:n,external:!0}):null}if(n.startsWith(`.`))return null;let o=m(n),s=C(o);if(s&&_.has(s)){let n=e(o);if(n)return t.add(n),{id:n,external:!0}}if(s===`typebox`){let e=v(o);if(e)return t.add(e),{id:e,external:!0}}if(s&&(y.has(s)||b.has(s))){let e=await this.resolve(o,r,i);if(e)return t.add(e.id),{id:e.id,external:!0}}return null}}}function B(e){return{name:`doom-set-inputs`,load(t){return a.isAbsolute(t)&&r.existsSync(t)&&e.add(t),null}}}function V(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e,t){if(Array.isArray(e)){for(let n of e)U(n,t);return}if(!H(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&H(n)&&n.type===`MetaProperty`&&H(n.meta)&&n.meta.name===`import`&&H(n.property)&&n.property.name===`meta`&&H(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))U(n,t)}function W(){return{name:`doom-original-import-meta-url`,transform(e,t){if(!a.isAbsolute(t)||!e.includes(`import.meta.url`))return null;let n=a.extname(t).toLowerCase(),r=n===`.tsx`?`tsx`:n===`.jsx`?`jsx`:p(t)?`ts`:`js`,o=[];if(U(this.parse(e,{lang:r}),o),o.length===0)return null;let s=JSON.stringify(i(t).href),c=e;for(let e of o.sort((e,t)=>t.start-e.start))c=`${c.slice(0,e.start)}${s}${c.slice(e.end)}`;return c}}}async function G(e,t,n={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let i=e.map(e=>a.resolve(e)),s=a.join(t,`sets`);r.mkdirSync(s,{recursive:!0});let d=I(i),f=a.resolve(n.outputDirectory??s),p=S(n.outputName??`doom-set`);r.mkdirSync(f,{recursive:!0});let m=o(`sha256`).update(f).update(p).digest(`hex`).slice(0,16),h=a.join(s,`${d}.${m}${l}`),g=A(h);if(g&&O(g,i))return g.output;let _=new Set(i),v=L(i),{rolldown:y}=await import(`rolldown`),b=await y({input:u,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===u?e:null},load(e){return e===u?v:null}},z(_),W(),B(_)],onLog:V}),x;try{x=F(await b.generate(M(`${p}.[hash:16]${c}`)),f)}finally{await b.close()}let C=x.entry,w=[..._].map(E).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));return j(h,`${JSON.stringify({version:`
|
|
1
|
+
import{optionalPackageEntry as e}from"./modules/moduleResolution.mjs";import"../utils/index.mjs";import{builtinModules as t,createRequire as n}from"node:module";import r from"node:fs";import{pathToFileURL as i}from"node:url";import a from"node:path";import{createHash as o}from"node:crypto";const s=[`.ts`,`.mts`,`.cts`],c=`.mjs`,l=`.json`,u=`\0doompi-extension-set`,d=`@agimon-ai/doompi-ui/extensionName`,f={"@mariozechner/pi-coding-agent":`@earendil-works/pi-coding-agent`,"@mariozechner/pi-tui":`@earendil-works/pi-tui`,"@mariozechner/pi-ai":`@earendil-works/pi-ai`,"@sinclair/typebox":`typebox`};function p(e){return s.some(t=>e.endsWith(t))}function m(e){for(let[t,n]of Object.entries(f)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}function h(e){let t=r.readFileSync(e);return o(`sha256`).update(`v4`).update(e).update(t).digest(`hex`).slice(0,16)}function g(e,t){let n=a.basename(e).replace(/\.[cm]?ts$/,``);return`${a.basename(a.dirname(e))}-${n}.${t}${c}`}const _=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function v(t){let r=e(`@earendil-works/pi-coding-agent`);if(r)try{return n(r).resolve(t)}catch{return}}const y=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),b=new Set([`@agimon-ai/foundation-port-registry`,`@agimon-ai/foundation-process-registry`,`@agimon-ai/log-sink-mcp`,`@modelcontextprotocol/sdk`,`@narumitw/pi-tui-kit`,`@rmux/sdk`,`@tursodatabase/database`,`@tursodatabase/database-common`,`ajv`,`ajv-formats`,`gpt-tokenizer`,`highlight.js`,`hono`,`inversify`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),x=new Set(t.flatMap(e=>[e,`node:${e}`]));function S(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||`doom-set`}function C(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function w(e){let t=e.split(a.sep).join(`/`),n=t.lastIndexOf(`/node_modules/`);if(n===-1)return;let r=t.slice(n+14).split(`/`),i=r.lastIndexOf(`node_modules`),o=i===-1?r:r.slice(i+1);return o[0]?.startsWith(`@`)?o.slice(0,2).join(`/`):o[0]}function T(){return{name:`doom-external-absolute`,async resolveId(t,n,r){if(t.startsWith(`.`)||a.isAbsolute(t)||t.startsWith(`node:`))return null;let i=m(t),o=C(i);if(o&&_.has(o)){let t=e(i);if(t)return{id:t,external:!0}}let s=await this.resolve(i,n,r);return!s||p(s.id)?null:{id:s.id,external:!0}}}}function E(e){try{let t=r.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function D(e,t,n){return e.version===t&&e.output===n&&r.existsSync(n)&&e.artifacts.every(e=>r.existsSync(e))}function O(e,t){return!D(e,`v11`,e.output)||JSON.stringify(e.entries)!==JSON.stringify(t)?!1:e.inputs.every(e=>{let t=E(e.path);return t?.size===e.size&&t.mtimeMs===e.mtimeMs})}function k(e){try{let t=JSON.parse(r.readFileSync(e,`utf8`));return t&&typeof t.output==`string`&&Array.isArray(t.artifacts)?t:void 0}catch{return}}function A(e){let t=k(e);return t&&Array.isArray(t.entries)&&Array.isArray(t.inputs)?t:void 0}function j(e,t){r.mkdirSync(a.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(n,t);try{r.renameSync(n,e)}catch(t){if(r.rmSync(n,{force:!0}),!r.existsSync(e))throw t}}function M(e){return{format:`esm`,sourcemap:!1,minify:!0,codeSplitting:!0,hashCharacters:`hex`,entryFileNames:e,chunkFileNames:`chunks/[name].[hash:16]${c}`,assetFileNames:`assets/[name].[hash:16][extname]`}}function N(e,t){let n=a.resolve(e,t.fileName),r=a.relative(e,n);if(r.startsWith(`..`)||a.isAbsolute(r))throw Error(`Rolldown emitted an artifact outside the output directory: ${t.fileName}`);return n}function P(e,t){try{let n=r.readFileSync(e),i=Buffer.from(t);return n.equals(i)}catch{return!1}}function F(e,t){let n=e.output.find(e=>e.type===`chunk`&&e.isEntry);if(!n||n.type!==`chunk`)throw Error(`Rolldown produced no extension entry`);let r=a.resolve(t),i=e.output.filter(e=>e!==n);for(let e of[...i,n]){let t=e.type===`chunk`?e.code:e.source,n=N(r,e);P(n,t)||j(n,t)}return{entry:N(r,n),artifacts:e.output.map(e=>N(r,e)).sort()}}function I(e){return o(`sha256`).update(`v11`).update(JSON.stringify(e.map(e=>a.resolve(e)))).digest(`hex`).slice(0,16)}function L(t){let n=e(d);if(!n)throw Error(`Cannot resolve ${d}`);let r=t.map(e=>`() => import(${JSON.stringify(R(e))})`),i=t.map(e=>JSON.stringify(e));return[`import { withExtensionSource } from ${JSON.stringify(R(n))};`,`const loaders = [${r.join(`,`)}];`,`const names = [${i.join(`,`)}];`,`function report(index, phase, startedAt, error) {`,` const elapsed = (performance.now() - startedAt).toFixed(1);`,` const detail = error instanceof Error ? ": " + error.message : error === undefined ? "" : ": " + String(error);`,` process.stderr.write("[doompi:timing] " + phase + " " + elapsed + "ms " + names[index] + detail + "\\n");`,`}`,`export default async function doompiExtensionSet(pi) {`,` const timings = process.env.DOOMPI_TIMING === "1" || process.env.PI_TIMING === "1";`,` const loaded = await Promise.all(loaders.map(async (load, index) => {`,` const startedAt = performance.now();`,` try {`,` const extension = await load();`,` if (timings) report(index, "import", startedAt);`,` return extension;`,` } catch (error) {`,` report(index, "import-error", startedAt, error);`,` return undefined;`,` }`,` }));`,` for (let index = 0; index < loaded.length; index += 1) {`,` const extension = loaded[index];`,` if (!extension) continue;`,` const startedAt = performance.now();`,` try {`,` const factory = extension.default;`,` if (typeof factory !== 'function') throw new Error('does not export an extension factory');`,` await factory(withExtensionSource(pi, names[index]));`,` if (timings) report(index, "factory", startedAt);`,` } catch (error) {`,` report(index, "factory-error", startedAt, error);`,` }`,` }`,`}`].join(`
|
|
2
|
+
`)}function R(e){return a.resolve(e).split(a.sep).join(`/`)}function z(t){return{name:`doom-set-external`,async resolveId(n,r,i){if(n===u)return null;if(x.has(n)||n.startsWith(`node:`))return{id:n,external:!0};if(a.isAbsolute(n)){let e=w(n);return e&&(_.has(e)||y.has(e)||b.has(e))?(t.add(n),{id:n,external:!0}):null}if(n.startsWith(`.`))return null;let o=m(n),s=C(o);if(s&&_.has(s)){let n=e(o);if(n)return t.add(n),{id:n,external:!0}}if(s===`typebox`){let e=v(o);if(e)return t.add(e),{id:e,external:!0}}if(s&&(y.has(s)||b.has(s))){let e=await this.resolve(o,r,i);if(e)return t.add(e.id),{id:e.id,external:!0}}return null}}}function B(e){return{name:`doom-set-inputs`,load(t){return a.isAbsolute(t)&&r.existsSync(t)&&e.add(t),null}}}function V(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e,t){if(Array.isArray(e)){for(let n of e)U(n,t);return}if(!H(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&H(n)&&n.type===`MetaProperty`&&H(n.meta)&&n.meta.name===`import`&&H(n.property)&&n.property.name===`meta`&&H(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))U(n,t)}function W(){return{name:`doom-original-import-meta-url`,transform(e,t){if(!a.isAbsolute(t)||!e.includes(`import.meta.url`))return null;let n=a.extname(t).toLowerCase(),r=n===`.tsx`?`tsx`:n===`.jsx`?`jsx`:p(t)?`ts`:`js`,o=[];if(U(this.parse(e,{lang:r}),o),o.length===0)return null;let s=JSON.stringify(i(t).href),c=e;for(let e of o.sort((e,t)=>t.start-e.start))c=`${c.slice(0,e.start)}${s}${c.slice(e.end)}`;return c}}}async function G(e,t,n={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let i=e.map(e=>a.resolve(e)),s=a.join(t,`sets`);r.mkdirSync(s,{recursive:!0});let d=I(i),f=a.resolve(n.outputDirectory??s),p=S(n.outputName??`doom-set`);r.mkdirSync(f,{recursive:!0});let m=o(`sha256`).update(f).update(p).digest(`hex`).slice(0,16),h=a.join(s,`${d}.${m}${l}`),g=A(h);if(g&&O(g,i))return g.output;let _=new Set(i),v=L(i),{rolldown:y}=await import(`rolldown`),b=await y({input:u,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===u?e:null},load(e){return e===u?v:null}},z(_),W(),B(_)],onLog:V}),x;try{x=F(await b.generate(M(`${p}.[hash:16]${c}`)),f)}finally{await b.close()}let C=x.entry,w=[..._].map(E).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));return j(h,`${JSON.stringify({version:`v11`,entries:i,output:C,artifacts:x.artifacts,inputs:w},null,2)}\n`),C}async function K(e,t){if(!p(e))return e;r.mkdirSync(t,{recursive:!0});let n=g(e,h(e)),i=a.join(t,n),o=`${i}${l}`,s=k(o);if(s&&D(s,`v4`,i))return i;let{rolldown:c}=await import(`rolldown`),u=await c({input:e,platform:`node`,plugins:[T(),W()],onLog:V}),d;try{d=F(await u.generate(M(n)),t)}finally{await u.close()}return j(o,`${JSON.stringify({version:`v4`,output:i,artifacts:d.artifacts},null,2)}\n`),i}async function q(e,t){r.mkdirSync(t,{recursive:!0});let n={};for(let[r,i]of Object.entries(e))try{n[r]=await K(i,t)}catch{n[r]=i}return n}export{G as compileExtensionSet,q as compileResolvedEntries,I as extensionSetKey};
|
|
3
3
|
//# sourceMappingURL=extensionCompiler.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extensionCompiler.mjs","names":[],"sources":["../../src/adapters/extensionCompiler.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport { builtinModules, createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { LogLevel, LogOrStringHandler, OutputAsset, OutputChunk, RolldownLog, RolldownOutput } from 'rolldown';\nimport { optionalPackageEntry } from '../utils/index.ts';\n\n/**\n * Compiles TypeScript extensions into plain ESM ahead of the session.\n *\n * Pi loads extensions through jiti, which transpiles TypeScript at import time.\n * That works, but it costs a transform per module on a cold cache and makes Node\n * complain about type stripping under node_modules on every launch. Resolution\n * already knows the full extension list, so each TypeScript graph is compiled\n * to native ESM here and Pi imports it without a runtime transform. Lazy imports\n * remain separate content-addressed chunks so their evaluation semantics survive\n * compilation.\n *\n * Mode artifacts bundle their JavaScript dependencies. Node built-ins, native\n * packages, and Pi's shared runtime stay external; those imports are rewritten\n * to absolute paths so an artifact under `.pi/doom/dist` never relies on that\n * directory having its own `node_modules` tree.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst CACHE_VERSION = 'v4';\nconst SET_CACHE_VERSION = 'v10';\nconst HASH_LENGTH = 16;\nconst SET_DIRECTORY = 'sets';\nconst MANIFEST_SUFFIX = '.json';\nconst VIRTUAL_SET_ENTRY = '\\0doompi-extension-set';\nconst EXTENSION_SOURCE_HELPER = '@agimon-ai/doompi-ui/extensionName';\n\n/** Pi's former npm scope. The packages are the same, published under a new name. */\nconst PI_SCOPE_RENAMES: Readonly<Record<string, string>> = {\n '@mariozechner/pi-coding-agent': '@earendil-works/pi-coding-agent',\n '@mariozechner/pi-tui': '@earendil-works/pi-tui',\n '@mariozechner/pi-ai': '@earendil-works/pi-ai',\n '@sinclair/typebox': 'typebox',\n};\n\nexport function isTypeScriptEntry(entry: string): boolean {\n return TYPESCRIPT_SUFFIXES.some((suffix) => entry.endsWith(suffix));\n}\n\nfunction renameScope(specifier: string): string {\n for (const [before, after] of Object.entries(PI_SCOPE_RENAMES)) {\n if (specifier === before) return after;\n if (specifier.startsWith(`${before}/`)) return `${after}${specifier.slice(before.length)}`;\n }\n return specifier;\n}\n\n/**\n * Cache key for a compiled entry.\n *\n * The entry's own bytes are the only cheap signal that the extension changed; a\n * dependency edit is not visible without walking the graph, so an upgrade that\n * leaves the entry byte-identical is served from cache until the version below\n * is raised.\n */\nfunction cacheKey(entry: string): string {\n const source = fs.readFileSync(entry);\n return createHash('sha256').update(CACHE_VERSION).update(entry).update(source).digest('hex').slice(0, HASH_LENGTH);\n}\n\nfunction compiledName(entry: string, key: string): string {\n const base = path.basename(entry).replace(/\\.[cm]?ts$/, '');\n const parent = path.basename(path.dirname(entry));\n return `${parent}-${base}.${key}${COMPILED_SUFFIX}`;\n}\n\n/**\n * Packages that must resolve to the copy this harness runs, never to a second\n * one bundled into an extension. Pi owns the TUI and the session state, so a\n * duplicate renders into a different screen and mutates a different store.\n */\nconst HOSTED_PACKAGES = new Set(['@earendil-works/pi-coding-agent', '@earendil-works/pi-tui', '@earendil-works/pi-ai']);\n\n/**\n * Resolves packages Pi exposes to extensions as compatibility aliases.\n *\n * Extensions do not need to declare TypeBox themselves because Pi's loader\n * provides it as a virtual module. A dist bundle bypasses that loader, so it\n * resolves the same package against Pi's dependency tree and bundles it.\n */\nfunction piExtensionDependencyEntry(specifier: string): string | undefined {\n const piEntry = optionalPackageEntry('@earendil-works/pi-coding-agent');\n if (!piEntry) return undefined;\n try {\n return createRequire(piEntry).resolve(specifier);\n } catch {\n return undefined;\n }\n}\n\n/** Packages whose native binaries or runtime discovery cannot be rolled up. */\nconst NATIVE_PACKAGES = new Set([\n '@parcel/watcher',\n '@napi-rs/keyring',\n 'better-sqlite3',\n 'canvas',\n 'fsevents',\n 'isolated-vm',\n 'keytar',\n 'node-pty',\n 'onnxruntime-node',\n 'playwright',\n 'playwright-core',\n 'puppeteer',\n 'sharp',\n // TypeScript's Node system adapter reads CommonJS globals such as\n // __filename. Rolldown does not provide those globals when it folds the\n // adapter into the aggregate ESM extension, so keep the installed runtime\n // intact and import it by its resolved absolute path.\n 'typescript',\n]);\n\n/**\n * Dependency-heavy ESM runtimes that should retain their installed graph.\n *\n * Folding these packages into the aggregate creates dozens of generated chunks\n * that Node must parse and link before any extension factory can register. Node\n * can load the installed graph directly while still sharing its module cache.\n */\nconst STARTUP_EXTERNAL_PACKAGES = new Set([\n '@agimon-ai/foundation-port-registry',\n '@agimon-ai/foundation-process-registry',\n '@agimon-ai/log-sink-mcp',\n '@modelcontextprotocol/sdk',\n '@narumitw/pi-tui-kit',\n '@rmux/sdk',\n '@tursodatabase/database',\n '@tursodatabase/database-common',\n 'ajv',\n 'ajv-formats',\n 'gpt-tokenizer',\n 'highlight.js',\n 'hono',\n 'inversify',\n 'reflect-metadata',\n 'zod-to-json-schema',\n 'yaml',\n 'zod',\n]);\nconst NODE_BUILTINS = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));\n\ninterface InputFingerprint {\n path: string;\n size: number;\n mtimeMs: number;\n}\n\ninterface CompiledExtensionManifest {\n version: string;\n output: string;\n artifacts: string[];\n}\n\ninterface ExtensionSetManifest extends CompiledExtensionManifest {\n entries: string[];\n inputs: InputFingerprint[];\n}\n\nexport interface CompileExtensionSetOptions {\n /** Persistent artifact directory. Compiler manifests remain in cacheDirectory. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n}\n\nfunction safeOutputName(value: string): string {\n const normalized = value\n .trim()\n .replace(/[^a-zA-Z0-9._-]+/g, '-')\n .replace(/^[-.]+|[-.]+$/g, '');\n return normalized || 'doom-set';\n}\n\nfunction packageRootOf(specifier: string): string | undefined {\n const slash = specifier.startsWith('@') ? specifier.indexOf('/', specifier.indexOf('/') + 1) : specifier.indexOf('/');\n return slash === -1 ? specifier : specifier.slice(0, slash);\n}\n\nfunction packageRootFromPath(target: string): string | undefined {\n const normalized = target.split(path.sep).join('/');\n const marker = '/node_modules/';\n const offset = normalized.lastIndexOf(marker);\n if (offset === -1) return undefined;\n const parts = normalized.slice(offset + marker.length).split('/');\n // pnpm's first segment is a store key; the second node_modules marker names\n // the package that owns the file.\n const nested = parts.lastIndexOf('node_modules');\n const packageParts = nested === -1 ? parts : parts.slice(nested + 1);\n return packageParts[0]?.startsWith('@') ? packageParts.slice(0, 2).join('/') : packageParts[0];\n}\n\nfunction externalResolver() {\n return {\n name: 'doom-external-absolute',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier.startsWith('.') || path.isAbsolute(specifier) || specifier.startsWith('node:')) return null;\n const renamed = renameScope(specifier);\n\n // Host packages are resolved from this module, the way the rest of the\n // harness resolves them, because an extension written against Pi's former\n // scope does not have the current one in its own dependency tree.\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) return { id: hosted, external: true };\n }\n\n // Rolldown's resolver rather than `createRequire`, which cannot see an\n // ESM-only package that publishes no `require` condition and would send\n // Pi's own core into the bundle.\n const resolved = await this.resolve(renamed, importer, options);\n if (!resolved) return null;\n // A dependency that is itself TypeScript cannot be handed to Node either,\n // so it is bundled rather than externalised.\n if (isTypeScriptEntry(resolved.id)) return null;\n return { id: resolved.id, external: true };\n },\n };\n}\n\nfunction fingerprint(target: string): InputFingerprint | undefined {\n try {\n const stat = fs.statSync(target);\n if (!stat.isFile()) return undefined;\n return { path: target, size: stat.size, mtimeMs: stat.mtimeMs };\n } catch {\n return undefined;\n }\n}\n\nfunction artifactsAreFresh(manifest: CompiledExtensionManifest, version: string, output: string): boolean {\n return (\n manifest.version === version &&\n manifest.output === output &&\n fs.existsSync(output) &&\n manifest.artifacts.every((artifact) => fs.existsSync(artifact))\n );\n}\n\nfunction manifestIsFresh(manifest: ExtensionSetManifest, entries: string[]): boolean {\n if (!artifactsAreFresh(manifest, SET_CACHE_VERSION, manifest.output)) return false;\n if (JSON.stringify(manifest.entries) !== JSON.stringify(entries)) {\n return false;\n }\n return manifest.inputs.every((previous) => {\n const current = fingerprint(previous.path);\n return current?.size === previous.size && current.mtimeMs === previous.mtimeMs;\n });\n}\n\nfunction readCompiledExtensionManifest(manifestPath: string): CompiledExtensionManifest | undefined {\n try {\n const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as CompiledExtensionManifest;\n return parsed && typeof parsed.output === 'string' && Array.isArray(parsed.artifacts) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readSetManifest(manifestPath: string): ExtensionSetManifest | undefined {\n const parsed = readCompiledExtensionManifest(manifestPath) as ExtensionSetManifest | undefined;\n return parsed && Array.isArray(parsed.entries) && Array.isArray(parsed.inputs) ? parsed : undefined;\n}\n\nfunction writeAtomic(target: string, contents: string | Uint8Array): void {\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(temporary, contents);\n try {\n fs.renameSync(temporary, target);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n if (!fs.existsSync(target)) throw error;\n }\n}\n\ninterface CompiledGraph {\n entry: string;\n artifacts: string[];\n}\n\nfunction splitOutputOptions(entryFileNames: string) {\n return {\n format: 'esm' as const,\n sourcemap: false,\n minify: true,\n codeSplitting: true,\n hashCharacters: 'hex' as const,\n entryFileNames,\n chunkFileNames: `chunks/[name].[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`,\n assetFileNames: `assets/[name].[hash:${HASH_LENGTH}][extname]`,\n };\n}\n\nfunction artifactTarget(outputDirectory: string, artifact: OutputAsset | OutputChunk): string {\n const target = path.resolve(outputDirectory, artifact.fileName);\n const relative = path.relative(outputDirectory, target);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n throw new Error(`Rolldown emitted an artifact outside the output directory: ${artifact.fileName}`);\n }\n return target;\n}\n\nfunction artifactMatches(target: string, contents: string | Uint8Array): boolean {\n try {\n const current = fs.readFileSync(target);\n const generated = typeof contents === 'string' ? Buffer.from(contents) : Buffer.from(contents);\n return current.equals(generated);\n } catch {\n return false;\n }\n}\n\n/** Writes referenced chunks first so a visible entry always has a complete graph. */\nfunction writeCompiledGraph(generated: RolldownOutput, outputDirectory: string): CompiledGraph {\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry || entry.type !== 'chunk') throw new Error('Rolldown produced no extension entry');\n const root = path.resolve(outputDirectory);\n const remaining = generated.output.filter((artifact) => artifact !== entry);\n for (const artifact of [...remaining, entry]) {\n const contents = artifact.type === 'chunk' ? artifact.code : artifact.source;\n const target = artifactTarget(root, artifact);\n if (!artifactMatches(target, contents)) writeAtomic(target, contents);\n }\n return {\n entry: artifactTarget(root, entry),\n artifacts: generated.output.map((artifact) => artifactTarget(root, artifact)).sort(),\n };\n}\n\n/** Stable lookup key for one exact Pi load order. */\nexport function extensionSetKey(entries: readonly string[]): string {\n return createHash('sha256')\n .update(SET_CACHE_VERSION)\n .update(JSON.stringify(entries.map((entry) => path.resolve(entry))))\n .digest('hex')\n .slice(0, HASH_LENGTH);\n}\n\nfunction extensionSetSource(entries: readonly string[]): string {\n const helper = optionalPackageEntry(EXTENSION_SOURCE_HELPER);\n if (!helper) throw new Error(`Cannot resolve ${EXTENSION_SOURCE_HELPER}`);\n const loaders = entries.map((entry) => `() => import(${JSON.stringify(pathToImportSpecifier(entry))})`);\n const names = entries.map((entry) => JSON.stringify(entry));\n return [\n `import { withExtensionSource } from ${JSON.stringify(pathToImportSpecifier(helper))};`,\n `const loaders = [${loaders.join(',')}];`,\n `const names = [${names.join(',')}];`,\n 'function report(index, phase, startedAt, error) {',\n ' const elapsed = (performance.now() - startedAt).toFixed(1);',\n ' const detail = error instanceof Error ? \": \" + error.message : error === undefined ? \"\" : \": \" + String(error);',\n ' process.stderr.write(\"[doompi:timing] \" + phase + \" \" + elapsed + \"ms \" + names[index] + detail + \"\\\\n\");',\n '}',\n 'export default async function doompiExtensionSet(pi) {',\n ' const timings = process.env.DOOMPI_TIMING === \"1\" || process.env.PI_TIMING === \"1\";',\n ' const loaded = await Promise.all(loaders.map(async (load, index) => {',\n ' const startedAt = performance.now();',\n ' try {',\n ' const extension = await load();',\n ' if (timings) report(index, \"import\", startedAt);',\n ' return extension;',\n ' } catch (error) {',\n ' report(index, \"import-error\", startedAt, error);',\n ' return undefined;',\n ' }',\n ' }));',\n ' for (let index = 0; index < loaded.length; index += 1) {',\n ' const extension = loaded[index];',\n ' if (!extension) continue;',\n ' const startedAt = performance.now();',\n ' try {',\n ' const factory = extension.default ?? extension.notifications;',\n \" if (typeof factory !== 'function') throw new Error('does not export an extension factory');\",\n ' await factory(withExtensionSource(pi, names[index]));',\n ' if (timings) report(index, \"factory\", startedAt);',\n ' } catch (error) {',\n ' report(index, \"factory-error\", startedAt, error);',\n ' }',\n ' }',\n '}',\n ].join('\\n');\n}\n\nfunction pathToImportSpecifier(target: string): string {\n // Rolldown accepts absolute POSIX paths directly. Windows needs a file URL,\n // but replacing separators is enough for its platform-independent parser.\n return path.resolve(target).split(path.sep).join('/');\n}\n\nfunction setExternalResolver(inputs: Set<string>) {\n return {\n name: 'doom-set-external',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier === VIRTUAL_SET_ENTRY) return null;\n if (NODE_BUILTINS.has(specifier) || specifier.startsWith('node:')) {\n return { id: specifier, external: true };\n }\n\n if (path.isAbsolute(specifier)) {\n const root = packageRootFromPath(specifier);\n if (root && (HOSTED_PACKAGES.has(root) || NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n inputs.add(specifier);\n return { id: specifier, external: true };\n }\n return null;\n }\n if (specifier.startsWith('.')) return null;\n\n const renamed = renameScope(specifier);\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) {\n inputs.add(hosted);\n return { id: hosted, external: true };\n }\n }\n if (root === 'typebox') {\n const typebox = piExtensionDependencyEntry(renamed);\n if (typebox) {\n inputs.add(typebox);\n return { id: typebox, external: true };\n }\n }\n if (root && (NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n const resolved = await this.resolve(renamed, importer, options);\n if (resolved) {\n inputs.add(resolved.id);\n return { id: resolved.id, external: true };\n }\n }\n return null;\n },\n };\n}\n\nfunction inputCollector(inputs: Set<string>) {\n return {\n name: 'doom-set-inputs',\n load(id: string): null {\n if (path.isAbsolute(id) && fs.existsSync(id)) inputs.add(id);\n return null;\n },\n };\n}\n\n/** An unresolved bare import would otherwise become a broken dist external. */\nfunction failUnresolvedImport(_level: LogLevel, log: RolldownLog, handler: LogOrStringHandler): void {\n if (log.code === 'UNRESOLVED_IMPORT') handler('error', log);\n}\n\ninterface SourceRange {\n start: number;\n end: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction collectImportMetaUrlRanges(value: unknown, ranges: SourceRange[]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectImportMetaUrlRanges(item, ranges);\n return;\n }\n if (!isRecord(value)) return;\n\n const object = value.object;\n const property = value.property;\n if (\n value.type === 'MemberExpression' &&\n value.computed === false &&\n typeof value.start === 'number' &&\n typeof value.end === 'number' &&\n isRecord(object) &&\n object.type === 'MetaProperty' &&\n isRecord(object.meta) &&\n object.meta.name === 'import' &&\n isRecord(object.property) &&\n object.property.name === 'meta' &&\n isRecord(property) &&\n property.name === 'url'\n ) {\n ranges.push({ start: value.start, end: value.end });\n return;\n }\n\n for (const child of Object.values(value)) collectImportMetaUrlRanges(child, ranges);\n}\n\n/** Keeps package-owned resource lookup anchored to each original source file. */\nfunction preserveImportMetaUrl() {\n return {\n name: 'doom-original-import-meta-url',\n transform(\n this: {\n parse: (source: string, options?: { lang?: 'js' | 'jsx' | 'ts' | 'tsx' }) => unknown;\n },\n source: string,\n id: string,\n ): string | null {\n if (!path.isAbsolute(id) || !source.includes('import.meta.url')) return null;\n const extension = path.extname(id).toLowerCase();\n const lang = extension === '.tsx' ? 'tsx' : extension === '.jsx' ? 'jsx' : isTypeScriptEntry(id) ? 'ts' : 'js';\n const ranges: SourceRange[] = [];\n collectImportMetaUrlRanges(this.parse(source, { lang }), ranges);\n if (ranges.length === 0) return null;\n const replacement = JSON.stringify(pathToFileURL(id).href);\n let transformed = source;\n for (const range of ranges.sort((left, right) => right.start - left.start)) {\n transformed = `${transformed.slice(0, range.start)}${replacement}${transformed.slice(range.end)}`;\n }\n return transformed;\n },\n };\n}\n\n/**\n * Compiles an ordered extension set into one native ESM entry.\n *\n * The generated entry starts every module load together, then invokes factories\n * sequentially in activation order. Its manifest records every loaded module,\n * so a dependency edit invalidates the cache without running the compiler.\n */\nexport async function compileExtensionSet(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): Promise<string> {\n if (entries.length === 0) throw new Error('Cannot compile an empty extension set');\n const normalized = entries.map((entry) => path.resolve(entry));\n const setDirectory = path.join(cacheDirectory, SET_DIRECTORY);\n fs.mkdirSync(setDirectory, { recursive: true });\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? 'doom-set');\n fs.mkdirSync(outputDirectory, { recursive: true });\n // One graph can be emitted under several named mode artifacts. Keep their\n // cache records separate without changing extensionSetKey, which is the\n // runtime lookup key for an exact activation order.\n const outputKey = createHash('sha256').update(outputDirectory).update(outputName).digest('hex').slice(0, HASH_LENGTH);\n const manifestPath = path.join(setDirectory, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const inputs = new Set(normalized);\n const source = extensionSetSource(normalized);\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: VIRTUAL_SET_ENTRY,\n platform: 'node',\n plugins: [\n {\n name: 'doom-set-entry',\n resolveId(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? id : null;\n },\n load(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? source : null;\n },\n },\n setExternalResolver(inputs),\n preserveImportMetaUrl(),\n inputCollector(inputs),\n ],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`));\n compiled = writeCompiledGraph(generated, outputDirectory);\n } finally {\n await build.close();\n }\n\n const output = compiled.entry;\n const inputFingerprints = [...inputs]\n .map(fingerprint)\n .filter((value): value is InputFingerprint => value !== undefined)\n .sort((left, right) => left.path.localeCompare(right.path));\n writeAtomic(\n manifestPath,\n `${JSON.stringify(\n {\n version: SET_CACHE_VERSION,\n entries: normalized,\n output,\n artifacts: compiled.artifacts,\n inputs: inputFingerprints,\n },\n null,\n 2,\n )}\\n`,\n );\n return output;\n}\n\n/**\n * Bundles `entry` into `cacheDirectory` and returns the compiled path.\n *\n * Non-TypeScript entries are returned untouched. A cache hit skips the build.\n */\nexport async function compileExtension(entry: string, cacheDirectory: string): Promise<string> {\n if (!isTypeScriptEntry(entry)) return entry;\n\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const outputName = compiledName(entry, cacheKey(entry));\n const output = path.join(cacheDirectory, outputName);\n const manifestPath = `${output}${MANIFEST_SUFFIX}`;\n const previous = readCompiledExtensionManifest(manifestPath);\n if (previous && artifactsAreFresh(previous, CACHE_VERSION, output)) return output;\n\n // Rolldown loads a native module and a sizeable parser graph. Sync is the\n // only command that needs it, and a cache hit does not, so keep it off every\n // other CLI startup path.\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: entry,\n platform: 'node',\n plugins: [externalResolver(), preserveImportMetaUrl()],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(outputName));\n compiled = writeCompiledGraph(generated, cacheDirectory);\n } finally {\n await build.close();\n }\n writeAtomic(\n manifestPath,\n `${JSON.stringify({ version: CACHE_VERSION, output, artifacts: compiled.artifacts }, null, 2)}\\n`,\n );\n return output;\n}\n\n/**\n * Compiles every TypeScript entry in a resolution map, leaving the rest as-is.\n *\n * A failure is not fatal: the original path is kept so Pi falls back to loading\n * the TypeScript through jiti, which is what it did before this existed.\n */\nexport async function compileResolvedEntries(\n resolved: Record<string, string>,\n cacheDirectory: string,\n): Promise<Record<string, string>> {\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const compiled: Record<string, string> = {};\n for (const [key, target] of Object.entries(resolved)) {\n try {\n compiled[key] = await compileExtension(target, cacheDirectory);\n } catch {\n compiled[key] = target;\n }\n }\n return compiled;\n}\n"],"mappings":"mSAyBA,MAAM,EAAsB,CAAC,MAAO,OAAQ,OAAO,CAC7C,EAAkB,OAKlB,EAAkB,QAClB,EAAoB,yBACpB,EAA0B,qCAG1B,EAAqD,CACzD,gCAAiC,kCACjC,uBAAwB,yBACxB,sBAAuB,wBACvB,oBAAqB,UACtB,CAED,SAAgB,EAAkB,EAAwB,CACxD,OAAO,EAAoB,KAAM,GAAW,EAAM,SAAS,EAAO,CAAC,CAGrE,SAAS,EAAY,EAA2B,CAC9C,IAAK,GAAM,CAAC,EAAQ,KAAU,OAAO,QAAQ,EAAiB,CAAE,CAC9D,GAAI,IAAc,EAAQ,OAAO,EACjC,GAAI,EAAU,WAAW,GAAG,EAAO,GAAG,CAAE,MAAO,GAAG,IAAQ,EAAU,MAAM,EAAO,OAAO,GAE1F,OAAO,EAWT,SAAS,EAAS,EAAuB,CACvC,IAAM,EAAS,EAAG,aAAa,EAAM,CACrC,OAAO,EAAW,SAAS,CAAC,OAAO,KAAc,CAAC,OAAO,EAAM,CAAC,OAAO,EAAO,CAAC,OAAO,MAAM,CAAC,MAAM,EAA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C,CACtD,MAAO,EACR,CAAC,CACE,EACJ,GAAI,CAEF,EAAW,EAAmB,MADN,EAAM,SAAS,EAAmB,EAAW,CAAC,CAC7B,EAAe,QAChD,CACR,MAAM,EAAM,OAAO,CAMrB,OAJA,EACE,EACA,GAAG,KAAK,UAAU,CAAE,QAAS,KAAe,SAAQ,UAAW,EAAS,UAAW,CAAE,KAAM,EAAE,CAAC,IAC/F,CACM,EAST,eAAsB,EACpB,EACA,EACiC,CACjC,EAAG,UAAU,EAAgB,CAAE,UAAW,GAAM,CAAC,CACjD,IAAM,EAAmC,EAAE,CAC3C,IAAK,GAAM,CAAC,EAAK,KAAW,OAAO,QAAQ,EAAS,CAClD,GAAI,CACF,EAAS,GAAO,MAAM,EAAiB,EAAQ,EAAe,MACxD,CACN,EAAS,GAAO,EAGpB,OAAO"}
|
|
1
|
+
{"version":3,"file":"extensionCompiler.mjs","names":[],"sources":["../../src/adapters/extensionCompiler.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport { builtinModules, createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { LogLevel, LogOrStringHandler, OutputAsset, OutputChunk, RolldownLog, RolldownOutput } from 'rolldown';\nimport { optionalPackageEntry } from '../utils/index.ts';\n\n/**\n * Compiles TypeScript extensions into plain ESM ahead of the session.\n *\n * Pi loads extensions through jiti, which transpiles TypeScript at import time.\n * That works, but it costs a transform per module on a cold cache and makes Node\n * complain about type stripping under node_modules on every launch. Resolution\n * already knows the full extension list, so each TypeScript graph is compiled\n * to native ESM here and Pi imports it without a runtime transform. Lazy imports\n * remain separate content-addressed chunks so their evaluation semantics survive\n * compilation.\n *\n * Mode artifacts bundle their JavaScript dependencies. Node built-ins, native\n * packages, and Pi's shared runtime stay external; those imports are rewritten\n * to absolute paths so an artifact under `.pi/doom/dist` never relies on that\n * directory having its own `node_modules` tree.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst CACHE_VERSION = 'v4';\nconst SET_CACHE_VERSION = 'v11';\nconst HASH_LENGTH = 16;\nconst SET_DIRECTORY = 'sets';\nconst MANIFEST_SUFFIX = '.json';\nconst VIRTUAL_SET_ENTRY = '\\0doompi-extension-set';\nconst EXTENSION_SOURCE_HELPER = '@agimon-ai/doompi-ui/extensionName';\n\n/** Pi's former npm scope. The packages are the same, published under a new name. */\nconst PI_SCOPE_RENAMES: Readonly<Record<string, string>> = {\n '@mariozechner/pi-coding-agent': '@earendil-works/pi-coding-agent',\n '@mariozechner/pi-tui': '@earendil-works/pi-tui',\n '@mariozechner/pi-ai': '@earendil-works/pi-ai',\n '@sinclair/typebox': 'typebox',\n};\n\nexport function isTypeScriptEntry(entry: string): boolean {\n return TYPESCRIPT_SUFFIXES.some((suffix) => entry.endsWith(suffix));\n}\n\nfunction renameScope(specifier: string): string {\n for (const [before, after] of Object.entries(PI_SCOPE_RENAMES)) {\n if (specifier === before) return after;\n if (specifier.startsWith(`${before}/`)) return `${after}${specifier.slice(before.length)}`;\n }\n return specifier;\n}\n\n/**\n * Cache key for a compiled entry.\n *\n * The entry's own bytes are the only cheap signal that the extension changed; a\n * dependency edit is not visible without walking the graph, so an upgrade that\n * leaves the entry byte-identical is served from cache until the version below\n * is raised.\n */\nfunction cacheKey(entry: string): string {\n const source = fs.readFileSync(entry);\n return createHash('sha256').update(CACHE_VERSION).update(entry).update(source).digest('hex').slice(0, HASH_LENGTH);\n}\n\nfunction compiledName(entry: string, key: string): string {\n const base = path.basename(entry).replace(/\\.[cm]?ts$/, '');\n const parent = path.basename(path.dirname(entry));\n return `${parent}-${base}.${key}${COMPILED_SUFFIX}`;\n}\n\n/**\n * Packages that must resolve to the copy this harness runs, never to a second\n * one bundled into an extension. Pi owns the TUI and the session state, so a\n * duplicate renders into a different screen and mutates a different store.\n */\nconst HOSTED_PACKAGES = new Set(['@earendil-works/pi-coding-agent', '@earendil-works/pi-tui', '@earendil-works/pi-ai']);\n\n/**\n * Resolves packages Pi exposes to extensions as compatibility aliases.\n *\n * Extensions do not need to declare TypeBox themselves because Pi's loader\n * provides it as a virtual module. A dist bundle bypasses that loader, so it\n * resolves the same package against Pi's dependency tree and bundles it.\n */\nfunction piExtensionDependencyEntry(specifier: string): string | undefined {\n const piEntry = optionalPackageEntry('@earendil-works/pi-coding-agent');\n if (!piEntry) return undefined;\n try {\n return createRequire(piEntry).resolve(specifier);\n } catch {\n return undefined;\n }\n}\n\n/** Packages whose native binaries or runtime discovery cannot be rolled up. */\nconst NATIVE_PACKAGES = new Set([\n '@parcel/watcher',\n '@napi-rs/keyring',\n 'better-sqlite3',\n 'canvas',\n 'fsevents',\n 'isolated-vm',\n 'keytar',\n 'node-pty',\n 'onnxruntime-node',\n 'playwright',\n 'playwright-core',\n 'puppeteer',\n 'sharp',\n // TypeScript's Node system adapter reads CommonJS globals such as\n // __filename. Rolldown does not provide those globals when it folds the\n // adapter into the aggregate ESM extension, so keep the installed runtime\n // intact and import it by its resolved absolute path.\n 'typescript',\n]);\n\n/**\n * Dependency-heavy ESM runtimes that should retain their installed graph.\n *\n * Folding these packages into the aggregate creates dozens of generated chunks\n * that Node must parse and link before any extension factory can register. Node\n * can load the installed graph directly while still sharing its module cache.\n */\nconst STARTUP_EXTERNAL_PACKAGES = new Set([\n '@agimon-ai/foundation-port-registry',\n '@agimon-ai/foundation-process-registry',\n '@agimon-ai/log-sink-mcp',\n '@modelcontextprotocol/sdk',\n '@narumitw/pi-tui-kit',\n '@rmux/sdk',\n '@tursodatabase/database',\n '@tursodatabase/database-common',\n 'ajv',\n 'ajv-formats',\n 'gpt-tokenizer',\n 'highlight.js',\n 'hono',\n 'inversify',\n 'reflect-metadata',\n 'zod-to-json-schema',\n 'yaml',\n 'zod',\n]);\nconst NODE_BUILTINS = new Set(builtinModules.flatMap((name) => [name, `node:${name}`]));\n\ninterface InputFingerprint {\n path: string;\n size: number;\n mtimeMs: number;\n}\n\ninterface CompiledExtensionManifest {\n version: string;\n output: string;\n artifacts: string[];\n}\n\ninterface ExtensionSetManifest extends CompiledExtensionManifest {\n entries: string[];\n inputs: InputFingerprint[];\n}\n\nexport interface CompileExtensionSetOptions {\n /** Persistent artifact directory. Compiler manifests remain in cacheDirectory. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n}\n\nfunction safeOutputName(value: string): string {\n const normalized = value\n .trim()\n .replace(/[^a-zA-Z0-9._-]+/g, '-')\n .replace(/^[-.]+|[-.]+$/g, '');\n return normalized || 'doom-set';\n}\n\nfunction packageRootOf(specifier: string): string | undefined {\n const slash = specifier.startsWith('@') ? specifier.indexOf('/', specifier.indexOf('/') + 1) : specifier.indexOf('/');\n return slash === -1 ? specifier : specifier.slice(0, slash);\n}\n\nfunction packageRootFromPath(target: string): string | undefined {\n const normalized = target.split(path.sep).join('/');\n const marker = '/node_modules/';\n const offset = normalized.lastIndexOf(marker);\n if (offset === -1) return undefined;\n const parts = normalized.slice(offset + marker.length).split('/');\n // pnpm's first segment is a store key; the second node_modules marker names\n // the package that owns the file.\n const nested = parts.lastIndexOf('node_modules');\n const packageParts = nested === -1 ? parts : parts.slice(nested + 1);\n return packageParts[0]?.startsWith('@') ? packageParts.slice(0, 2).join('/') : packageParts[0];\n}\n\nfunction externalResolver() {\n return {\n name: 'doom-external-absolute',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier.startsWith('.') || path.isAbsolute(specifier) || specifier.startsWith('node:')) return null;\n const renamed = renameScope(specifier);\n\n // Host packages are resolved from this module, the way the rest of the\n // harness resolves them, because an extension written against Pi's former\n // scope does not have the current one in its own dependency tree.\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) return { id: hosted, external: true };\n }\n\n // Rolldown's resolver rather than `createRequire`, which cannot see an\n // ESM-only package that publishes no `require` condition and would send\n // Pi's own core into the bundle.\n const resolved = await this.resolve(renamed, importer, options);\n if (!resolved) return null;\n // A dependency that is itself TypeScript cannot be handed to Node either,\n // so it is bundled rather than externalised.\n if (isTypeScriptEntry(resolved.id)) return null;\n return { id: resolved.id, external: true };\n },\n };\n}\n\nfunction fingerprint(target: string): InputFingerprint | undefined {\n try {\n const stat = fs.statSync(target);\n if (!stat.isFile()) return undefined;\n return { path: target, size: stat.size, mtimeMs: stat.mtimeMs };\n } catch {\n return undefined;\n }\n}\n\nfunction artifactsAreFresh(manifest: CompiledExtensionManifest, version: string, output: string): boolean {\n return (\n manifest.version === version &&\n manifest.output === output &&\n fs.existsSync(output) &&\n manifest.artifacts.every((artifact) => fs.existsSync(artifact))\n );\n}\n\nfunction manifestIsFresh(manifest: ExtensionSetManifest, entries: string[]): boolean {\n if (!artifactsAreFresh(manifest, SET_CACHE_VERSION, manifest.output)) return false;\n if (JSON.stringify(manifest.entries) !== JSON.stringify(entries)) {\n return false;\n }\n return manifest.inputs.every((previous) => {\n const current = fingerprint(previous.path);\n return current?.size === previous.size && current.mtimeMs === previous.mtimeMs;\n });\n}\n\nfunction readCompiledExtensionManifest(manifestPath: string): CompiledExtensionManifest | undefined {\n try {\n const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as CompiledExtensionManifest;\n return parsed && typeof parsed.output === 'string' && Array.isArray(parsed.artifacts) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readSetManifest(manifestPath: string): ExtensionSetManifest | undefined {\n const parsed = readCompiledExtensionManifest(manifestPath) as ExtensionSetManifest | undefined;\n return parsed && Array.isArray(parsed.entries) && Array.isArray(parsed.inputs) ? parsed : undefined;\n}\n\nfunction writeAtomic(target: string, contents: string | Uint8Array): void {\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;\n fs.writeFileSync(temporary, contents);\n try {\n fs.renameSync(temporary, target);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n if (!fs.existsSync(target)) throw error;\n }\n}\n\ninterface CompiledGraph {\n entry: string;\n artifacts: string[];\n}\n\nfunction splitOutputOptions(entryFileNames: string) {\n return {\n format: 'esm' as const,\n sourcemap: false,\n minify: true,\n codeSplitting: true,\n hashCharacters: 'hex' as const,\n entryFileNames,\n chunkFileNames: `chunks/[name].[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`,\n assetFileNames: `assets/[name].[hash:${HASH_LENGTH}][extname]`,\n };\n}\n\nfunction artifactTarget(outputDirectory: string, artifact: OutputAsset | OutputChunk): string {\n const target = path.resolve(outputDirectory, artifact.fileName);\n const relative = path.relative(outputDirectory, target);\n if (relative.startsWith('..') || path.isAbsolute(relative)) {\n throw new Error(`Rolldown emitted an artifact outside the output directory: ${artifact.fileName}`);\n }\n return target;\n}\n\nfunction artifactMatches(target: string, contents: string | Uint8Array): boolean {\n try {\n const current = fs.readFileSync(target);\n const generated = typeof contents === 'string' ? Buffer.from(contents) : Buffer.from(contents);\n return current.equals(generated);\n } catch {\n return false;\n }\n}\n\n/** Writes referenced chunks first so a visible entry always has a complete graph. */\nfunction writeCompiledGraph(generated: RolldownOutput, outputDirectory: string): CompiledGraph {\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry || entry.type !== 'chunk') throw new Error('Rolldown produced no extension entry');\n const root = path.resolve(outputDirectory);\n const remaining = generated.output.filter((artifact) => artifact !== entry);\n for (const artifact of [...remaining, entry]) {\n const contents = artifact.type === 'chunk' ? artifact.code : artifact.source;\n const target = artifactTarget(root, artifact);\n if (!artifactMatches(target, contents)) writeAtomic(target, contents);\n }\n return {\n entry: artifactTarget(root, entry),\n artifacts: generated.output.map((artifact) => artifactTarget(root, artifact)).sort(),\n };\n}\n\n/** Stable lookup key for one exact Pi load order. */\nexport function extensionSetKey(entries: readonly string[]): string {\n return createHash('sha256')\n .update(SET_CACHE_VERSION)\n .update(JSON.stringify(entries.map((entry) => path.resolve(entry))))\n .digest('hex')\n .slice(0, HASH_LENGTH);\n}\n\nfunction extensionSetSource(entries: readonly string[]): string {\n const helper = optionalPackageEntry(EXTENSION_SOURCE_HELPER);\n if (!helper) throw new Error(`Cannot resolve ${EXTENSION_SOURCE_HELPER}`);\n const loaders = entries.map((entry) => `() => import(${JSON.stringify(pathToImportSpecifier(entry))})`);\n const names = entries.map((entry) => JSON.stringify(entry));\n return [\n `import { withExtensionSource } from ${JSON.stringify(pathToImportSpecifier(helper))};`,\n `const loaders = [${loaders.join(',')}];`,\n `const names = [${names.join(',')}];`,\n 'function report(index, phase, startedAt, error) {',\n ' const elapsed = (performance.now() - startedAt).toFixed(1);',\n ' const detail = error instanceof Error ? \": \" + error.message : error === undefined ? \"\" : \": \" + String(error);',\n ' process.stderr.write(\"[doompi:timing] \" + phase + \" \" + elapsed + \"ms \" + names[index] + detail + \"\\\\n\");',\n '}',\n 'export default async function doompiExtensionSet(pi) {',\n ' const timings = process.env.DOOMPI_TIMING === \"1\" || process.env.PI_TIMING === \"1\";',\n ' const loaded = await Promise.all(loaders.map(async (load, index) => {',\n ' const startedAt = performance.now();',\n ' try {',\n ' const extension = await load();',\n ' if (timings) report(index, \"import\", startedAt);',\n ' return extension;',\n ' } catch (error) {',\n ' report(index, \"import-error\", startedAt, error);',\n ' return undefined;',\n ' }',\n ' }));',\n ' for (let index = 0; index < loaded.length; index += 1) {',\n ' const extension = loaded[index];',\n ' if (!extension) continue;',\n ' const startedAt = performance.now();',\n ' try {',\n ' const factory = extension.default;',\n \" if (typeof factory !== 'function') throw new Error('does not export an extension factory');\",\n ' await factory(withExtensionSource(pi, names[index]));',\n ' if (timings) report(index, \"factory\", startedAt);',\n ' } catch (error) {',\n ' report(index, \"factory-error\", startedAt, error);',\n ' }',\n ' }',\n '}',\n ].join('\\n');\n}\n\nfunction pathToImportSpecifier(target: string): string {\n // Rolldown accepts absolute POSIX paths directly. Windows needs a file URL,\n // but replacing separators is enough for its platform-independent parser.\n return path.resolve(target).split(path.sep).join('/');\n}\n\nfunction setExternalResolver(inputs: Set<string>) {\n return {\n name: 'doom-set-external',\n async resolveId(\n this: { resolve: (id: string, importer?: string, options?: unknown) => Promise<{ id: string } | null> },\n specifier: string,\n importer: string | undefined,\n options: unknown,\n ): Promise<{ id: string; external: boolean } | null> {\n if (specifier === VIRTUAL_SET_ENTRY) return null;\n if (NODE_BUILTINS.has(specifier) || specifier.startsWith('node:')) {\n return { id: specifier, external: true };\n }\n\n if (path.isAbsolute(specifier)) {\n const root = packageRootFromPath(specifier);\n if (root && (HOSTED_PACKAGES.has(root) || NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n inputs.add(specifier);\n return { id: specifier, external: true };\n }\n return null;\n }\n if (specifier.startsWith('.')) return null;\n\n const renamed = renameScope(specifier);\n const root = packageRootOf(renamed);\n if (root && HOSTED_PACKAGES.has(root)) {\n const hosted = optionalPackageEntry(renamed);\n if (hosted) {\n inputs.add(hosted);\n return { id: hosted, external: true };\n }\n }\n if (root === 'typebox') {\n const typebox = piExtensionDependencyEntry(renamed);\n if (typebox) {\n inputs.add(typebox);\n return { id: typebox, external: true };\n }\n }\n if (root && (NATIVE_PACKAGES.has(root) || STARTUP_EXTERNAL_PACKAGES.has(root))) {\n const resolved = await this.resolve(renamed, importer, options);\n if (resolved) {\n inputs.add(resolved.id);\n return { id: resolved.id, external: true };\n }\n }\n return null;\n },\n };\n}\n\nfunction inputCollector(inputs: Set<string>) {\n return {\n name: 'doom-set-inputs',\n load(id: string): null {\n if (path.isAbsolute(id) && fs.existsSync(id)) inputs.add(id);\n return null;\n },\n };\n}\n\n/** An unresolved bare import would otherwise become a broken dist external. */\nfunction failUnresolvedImport(_level: LogLevel, log: RolldownLog, handler: LogOrStringHandler): void {\n if (log.code === 'UNRESOLVED_IMPORT') handler('error', log);\n}\n\ninterface SourceRange {\n start: number;\n end: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction collectImportMetaUrlRanges(value: unknown, ranges: SourceRange[]): void {\n if (Array.isArray(value)) {\n for (const item of value) collectImportMetaUrlRanges(item, ranges);\n return;\n }\n if (!isRecord(value)) return;\n\n const object = value.object;\n const property = value.property;\n if (\n value.type === 'MemberExpression' &&\n value.computed === false &&\n typeof value.start === 'number' &&\n typeof value.end === 'number' &&\n isRecord(object) &&\n object.type === 'MetaProperty' &&\n isRecord(object.meta) &&\n object.meta.name === 'import' &&\n isRecord(object.property) &&\n object.property.name === 'meta' &&\n isRecord(property) &&\n property.name === 'url'\n ) {\n ranges.push({ start: value.start, end: value.end });\n return;\n }\n\n for (const child of Object.values(value)) collectImportMetaUrlRanges(child, ranges);\n}\n\n/** Keeps package-owned resource lookup anchored to each original source file. */\nfunction preserveImportMetaUrl() {\n return {\n name: 'doom-original-import-meta-url',\n transform(\n this: {\n parse: (source: string, options?: { lang?: 'js' | 'jsx' | 'ts' | 'tsx' }) => unknown;\n },\n source: string,\n id: string,\n ): string | null {\n if (!path.isAbsolute(id) || !source.includes('import.meta.url')) return null;\n const extension = path.extname(id).toLowerCase();\n const lang = extension === '.tsx' ? 'tsx' : extension === '.jsx' ? 'jsx' : isTypeScriptEntry(id) ? 'ts' : 'js';\n const ranges: SourceRange[] = [];\n collectImportMetaUrlRanges(this.parse(source, { lang }), ranges);\n if (ranges.length === 0) return null;\n const replacement = JSON.stringify(pathToFileURL(id).href);\n let transformed = source;\n for (const range of ranges.sort((left, right) => right.start - left.start)) {\n transformed = `${transformed.slice(0, range.start)}${replacement}${transformed.slice(range.end)}`;\n }\n return transformed;\n },\n };\n}\n\n/**\n * Compiles an ordered extension set into one native ESM entry.\n *\n * The generated entry starts every module load together, then invokes factories\n * sequentially in activation order. Its manifest records every loaded module,\n * so a dependency edit invalidates the cache without running the compiler.\n */\nexport async function compileExtensionSet(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): Promise<string> {\n if (entries.length === 0) throw new Error('Cannot compile an empty extension set');\n const normalized = entries.map((entry) => path.resolve(entry));\n const setDirectory = path.join(cacheDirectory, SET_DIRECTORY);\n fs.mkdirSync(setDirectory, { recursive: true });\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? 'doom-set');\n fs.mkdirSync(outputDirectory, { recursive: true });\n // One graph can be emitted under several named mode artifacts. Keep their\n // cache records separate without changing extensionSetKey, which is the\n // runtime lookup key for an exact activation order.\n const outputKey = createHash('sha256').update(outputDirectory).update(outputName).digest('hex').slice(0, HASH_LENGTH);\n const manifestPath = path.join(setDirectory, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const inputs = new Set(normalized);\n const source = extensionSetSource(normalized);\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: VIRTUAL_SET_ENTRY,\n platform: 'node',\n plugins: [\n {\n name: 'doom-set-entry',\n resolveId(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? id : null;\n },\n load(id: string): string | null {\n return id === VIRTUAL_SET_ENTRY ? source : null;\n },\n },\n setExternalResolver(inputs),\n preserveImportMetaUrl(),\n inputCollector(inputs),\n ],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`));\n compiled = writeCompiledGraph(generated, outputDirectory);\n } finally {\n await build.close();\n }\n\n const output = compiled.entry;\n const inputFingerprints = [...inputs]\n .map(fingerprint)\n .filter((value): value is InputFingerprint => value !== undefined)\n .sort((left, right) => left.path.localeCompare(right.path));\n writeAtomic(\n manifestPath,\n `${JSON.stringify(\n {\n version: SET_CACHE_VERSION,\n entries: normalized,\n output,\n artifacts: compiled.artifacts,\n inputs: inputFingerprints,\n },\n null,\n 2,\n )}\\n`,\n );\n return output;\n}\n\n/**\n * Bundles `entry` into `cacheDirectory` and returns the compiled path.\n *\n * Non-TypeScript entries are returned untouched. A cache hit skips the build.\n */\nexport async function compileExtension(entry: string, cacheDirectory: string): Promise<string> {\n if (!isTypeScriptEntry(entry)) return entry;\n\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const outputName = compiledName(entry, cacheKey(entry));\n const output = path.join(cacheDirectory, outputName);\n const manifestPath = `${output}${MANIFEST_SUFFIX}`;\n const previous = readCompiledExtensionManifest(manifestPath);\n if (previous && artifactsAreFresh(previous, CACHE_VERSION, output)) return output;\n\n // Rolldown loads a native module and a sizeable parser graph. Sync is the\n // only command that needs it, and a cache hit does not, so keep it off every\n // other CLI startup path.\n const { rolldown } = await import('rolldown');\n const build = await rolldown({\n input: entry,\n platform: 'node',\n plugins: [externalResolver(), preserveImportMetaUrl()],\n onLog: failUnresolvedImport,\n });\n let compiled: CompiledGraph;\n try {\n const generated = await build.generate(splitOutputOptions(outputName));\n compiled = writeCompiledGraph(generated, cacheDirectory);\n } finally {\n await build.close();\n }\n writeAtomic(\n manifestPath,\n `${JSON.stringify({ version: CACHE_VERSION, output, artifacts: compiled.artifacts }, null, 2)}\\n`,\n );\n return output;\n}\n\n/**\n * Compiles every TypeScript entry in a resolution map, leaving the rest as-is.\n *\n * A failure is not fatal: the original path is kept so Pi falls back to loading\n * the TypeScript through jiti, which is what it did before this existed.\n */\nexport async function compileResolvedEntries(\n resolved: Record<string, string>,\n cacheDirectory: string,\n): Promise<Record<string, string>> {\n fs.mkdirSync(cacheDirectory, { recursive: true });\n const compiled: Record<string, string> = {};\n for (const [key, target] of Object.entries(resolved)) {\n try {\n compiled[key] = await compileExtension(target, cacheDirectory);\n } catch {\n compiled[key] = target;\n }\n }\n return compiled;\n}\n"],"mappings":"mSAyBA,MAAM,EAAsB,CAAC,MAAO,OAAQ,OAAO,CAC7C,EAAkB,OAKlB,EAA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AM,KAAK,CAAC,CAe7D,OAdA,EACE,EACA,GAAG,KAAK,UACN,CACE,QAAS,MACT,QAAS,EACT,SACA,UAAW,EAAS,UACpB,OAAQ,EACT,CACD,KACA,EACD,CAAC,IACH,CACM,EAQT,eAAsB,EAAiB,EAAe,EAAyC,CAC7F,GAAI,CAAC,EAAkB,EAAM,CAAE,OAAO,EAEtC,EAAG,UAAU,EAAgB,CAAE,UAAW,GAAM,CAAC,CACjD,IAAM,EAAa,EAAa,EAAO,EAAS,EAAM,CAAC,CACjD,EAAS,EAAK,KAAK,EAAgB,EAAW,CAC9C,EAAe,GAAG,IAAS,IAC3B,EAAW,EAA8B,EAAa,CAC5D,GAAI,GAAY,EAAkB,EAAU,KAAe,EAAO,CAAE,OAAO,EAK3E,GAAM,CAAE,YAAa,MAAM,OAAO,YAC5B,EAAQ,MAAM,EAAS,CAC3B,MAAO,EACP,SAAU,OACV,QAAS,CAAC,GAAkB,CAAE,GAAuB,CAAC,CACtD,MAAO,EACR,CAAC,CACE,EACJ,GAAI,CAEF,EAAW,EAAmB,MADN,EAAM,SAAS,EAAmB,EAAW,CAAC,CAC7B,EAAe,QAChD,CACR,MAAM,EAAM,OAAO,CAMrB,OAJA,EACE,EACA,GAAG,KAAK,UAAU,CAAE,QAAS,KAAe,SAAQ,UAAW,EAAS,UAAW,CAAE,KAAM,EAAE,CAAC,IAC/F,CACM,EAST,eAAsB,EACpB,EACA,EACiC,CACjC,EAAG,UAAU,EAAgB,CAAE,UAAW,GAAM,CAAC,CACjD,IAAM,EAAmC,EAAE,CAC3C,IAAK,GAAM,CAAC,EAAK,KAAW,OAAO,QAAQ,EAAS,CAClD,GAAI,CACF,EAAS,GAAO,MAAM,EAAiB,EAAQ,EAAe,MACxD,CACN,EAAS,GAAO,EAGpB,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`../extensions/entries/autoStop.cjs`);exports.autoStop=e
|
|
1
|
+
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`../extensions/entries/autoStop.cjs`);exports.autoStop=e,exports.default=e;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"../extensions/entries/autoStop.mjs";export{e as autoStop,e as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`../extensions/entries/notifications.cjs`);exports.default=e
|
|
1
|
+
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`../extensions/entries/notifications.cjs`);exports.default=e,exports.notifications=e,exports.sendSystemNotification=e.sendSystemNotification;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e,{sendSystemNotification as t}from"../extensions/entries/notifications.mjs";export{e as default,e as notifications,t as sendSystemNotification};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){let t,n=()=>{t&&=(clearTimeout(t),void 0)};e.on(`input`,()=>{n()}),e.on(`agent_start`,()=>{n()}),e.on(`session_shutdown`,()=>{n()})
|
|
1
|
+
function e(e){let t,n=()=>{t&&=(clearTimeout(t),void 0)};e.on(`input`,()=>{n()}),e.on(`agent_start`,()=>{n()}),e.on(`session_shutdown`,()=>{n()});let r=(e,n)=>{t=setTimeout(()=>{if(t=void 0,!e.hasPendingMessages()){if(e.isIdle()){e.shutdown();return}r(e,100)}},n)};e.on(`agent_settled`,(e,t)=>{n(),!t.hasPendingMessages()&&r(t,5e3)})}exports.default=e;
|
|
2
2
|
//# sourceMappingURL=autoStop.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoStop.cjs","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\n\nconst AUTO_STOP_COOLDOWN_MS = 5_000;\n\nexport function autoStop(pi: ExtensionAPI): void {\n let shutdownTimer: NodeJS.Timeout | undefined;\n\n const cancelScheduledShutdown = () => {\n if (!shutdownTimer) return;\n clearTimeout(shutdownTimer);\n shutdownTimer = undefined;\n };\n\n pi.on('input', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('agent_start', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('session_shutdown', () => {\n cancelScheduledShutdown();\n });\n\n
|
|
1
|
+
{"version":3,"file":"autoStop.cjs","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"sourcesContent":["import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nconst AUTO_STOP_COOLDOWN_MS = 5_000;\nconst AUTO_STOP_IDLE_RETRY_MS = 100;\n\nexport function autoStop(pi: ExtensionAPI): void {\n let shutdownTimer: NodeJS.Timeout | undefined;\n\n const cancelScheduledShutdown = () => {\n if (!shutdownTimer) return;\n clearTimeout(shutdownTimer);\n shutdownTimer = undefined;\n };\n\n pi.on('input', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('agent_start', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('session_shutdown', () => {\n cancelScheduledShutdown();\n });\n\n const scheduleShutdown = (context: ExtensionContext, delayMs: number): void => {\n shutdownTimer = setTimeout(() => {\n shutdownTimer = undefined;\n if (context.hasPendingMessages()) return;\n if (context.isIdle()) {\n context.shutdown();\n return;\n }\n scheduleShutdown(context, AUTO_STOP_IDLE_RETRY_MS);\n }, delayMs);\n };\n\n pi.on('agent_settled', (_event, context) => {\n cancelScheduledShutdown();\n if (context.hasPendingMessages()) return;\n scheduleShutdown(context, AUTO_STOP_COOLDOWN_MS);\n });\n}\n\nexport default autoStop;\n"],"mappings":"AAKA,SAAgB,EAAS,EAAwB,CAC/C,IAAI,EAEE,MAAgC,CAC/B,AAEL,KADA,aAAa,EAAc,CACX,IAAA,KAGlB,EAAG,GAAG,YAAe,CACnB,GAAyB,EACzB,CAEF,EAAG,GAAG,kBAAqB,CACzB,GAAyB,EACzB,CAEF,EAAG,GAAG,uBAA0B,CAC9B,GAAyB,EACzB,CAEF,IAAM,GAAoB,EAA2B,IAA0B,CAC7E,EAAgB,eAAiB,CAC/B,KAAgB,IAAA,GACZ,GAAQ,oBAAoB,CAChC,IAAI,EAAQ,QAAQ,CAAE,CACpB,EAAQ,UAAU,CAClB,OAEF,EAAiB,EAAS,IAAwB,GACjD,EAAQ,EAGb,EAAG,GAAG,iBAAkB,EAAQ,IAAY,CAC1C,GAAyB,CACrB,GAAQ,oBAAoB,EAChC,EAAiB,EAAS,IAAsB,EAChD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoStop.d.cts","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"autoStop.d.cts","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"mappings":";;;iBAKgB,QAAA,CAAS,EAAA,EAAI,YAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoStop.d.mts","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"autoStop.d.mts","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"mappings":";;;iBAKgB,QAAA,CAAS,EAAA,EAAI,YAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e){let t,n=()=>{t&&=(clearTimeout(t),void 0)};e.on(`input`,()=>{n()}),e.on(`agent_start`,()=>{n()}),e.on(`session_shutdown`,()=>{n()})
|
|
1
|
+
function e(e){let t,n=()=>{t&&=(clearTimeout(t),void 0)};e.on(`input`,()=>{n()}),e.on(`agent_start`,()=>{n()}),e.on(`session_shutdown`,()=>{n()});let r=(e,n)=>{t=setTimeout(()=>{if(t=void 0,!e.hasPendingMessages()){if(e.isIdle()){e.shutdown();return}r(e,100)}},n)};e.on(`agent_settled`,(e,t)=>{n(),!t.hasPendingMessages()&&r(t,5e3)})}export{e as default};
|
|
2
2
|
//# sourceMappingURL=autoStop.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"autoStop.mjs","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\n\nconst AUTO_STOP_COOLDOWN_MS = 5_000;\n\nexport function autoStop(pi: ExtensionAPI): void {\n let shutdownTimer: NodeJS.Timeout | undefined;\n\n const cancelScheduledShutdown = () => {\n if (!shutdownTimer) return;\n clearTimeout(shutdownTimer);\n shutdownTimer = undefined;\n };\n\n pi.on('input', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('agent_start', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('session_shutdown', () => {\n cancelScheduledShutdown();\n });\n\n
|
|
1
|
+
{"version":3,"file":"autoStop.mjs","names":[],"sources":["../../../src/extensions/entries/autoStop.ts"],"sourcesContent":["import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nconst AUTO_STOP_COOLDOWN_MS = 5_000;\nconst AUTO_STOP_IDLE_RETRY_MS = 100;\n\nexport function autoStop(pi: ExtensionAPI): void {\n let shutdownTimer: NodeJS.Timeout | undefined;\n\n const cancelScheduledShutdown = () => {\n if (!shutdownTimer) return;\n clearTimeout(shutdownTimer);\n shutdownTimer = undefined;\n };\n\n pi.on('input', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('agent_start', () => {\n cancelScheduledShutdown();\n });\n\n pi.on('session_shutdown', () => {\n cancelScheduledShutdown();\n });\n\n const scheduleShutdown = (context: ExtensionContext, delayMs: number): void => {\n shutdownTimer = setTimeout(() => {\n shutdownTimer = undefined;\n if (context.hasPendingMessages()) return;\n if (context.isIdle()) {\n context.shutdown();\n return;\n }\n scheduleShutdown(context, AUTO_STOP_IDLE_RETRY_MS);\n }, delayMs);\n };\n\n pi.on('agent_settled', (_event, context) => {\n cancelScheduledShutdown();\n if (context.hasPendingMessages()) return;\n scheduleShutdown(context, AUTO_STOP_COOLDOWN_MS);\n });\n}\n\nexport default autoStop;\n"],"mappings":"AAKA,SAAgB,EAAS,EAAwB,CAC/C,IAAI,EAEE,MAAgC,CAC/B,AAEL,KADA,aAAa,EAAc,CACX,IAAA,KAGlB,EAAG,GAAG,YAAe,CACnB,GAAyB,EACzB,CAEF,EAAG,GAAG,kBAAqB,CACzB,GAAyB,EACzB,CAEF,EAAG,GAAG,uBAA0B,CAC9B,GAAyB,EACzB,CAEF,IAAM,GAAoB,EAA2B,IAA0B,CAC7E,EAAgB,eAAiB,CAC/B,KAAgB,IAAA,GACZ,GAAQ,oBAAoB,CAChC,IAAI,EAAQ,QAAQ,CAAE,CACpB,EAAQ,UAAU,CAClB,OAEF,EAAiB,EAAS,IAAwB,GACjD,EAAQ,EAGb,EAAG,GAAG,iBAAkB,EAAQ,IAAY,CAC1C,GAAyB,CACrB,GAAQ,oBAAoB,EAChC,EAAiB,EAAS,IAAsB,EAChD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
require(`../../../_virtual/_rolldown/runtime.cjs`);let e=require(`@earendil-works/pi-
|
|
1
|
+
require(`../../../_virtual/_rolldown/runtime.cjs`);let e=require(`@earendil-works/pi-tui`);function t(e){return{selectedPrefix:t=>e.fg(`accent`,t),selectedText:t=>e.bg(`selectedBg`,e.fg(`text`,t)),description:t=>e.fg(`dim`,t),scrollInfo:t=>e.fg(`muted`,t),noMatch:t=>e.fg(`warning`,t)}}var n=class{constructor(e){this.theme=e}render(e){return e>0?[this.theme.fg(`borderAccent`,`─`.repeat(e))]:[]}invalidate(){}};function r(e,t,n){return n?e.map(e=>({...e,label:`${t.includes(e.value)?`[x]`:`[ ]`} ${e.label}`})):e}function i(e,t){return e.filter(e=>e.value.toLowerCase().startsWith(t.toLowerCase())).map(e=>e.value)}function a(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}var o=class extends e.Container{filterInput=new e.Input;items;multi;title;theme;keybindings;done;list;selected;cursorValue;settled=!1;constructor(e,t,n,r){super(),this.items=e.items,this.multi=e.multi,this.title=e.title,this.theme=t,this.keybindings=n,this.done=r,this.selected=[...e.selected],this.cursorValue=e.selected[0],this.filterInput.focused=!0,this.filterInput.onEscape=()=>this.settle(void 0),this.list=this.buildList(),this.render_()}buildList(){let n=new e.SelectList(r(this.items,this.selected,this.multi),10,t(this.theme)),a=this.filterInput.getValue();a&&n.setFilter(a);let o=i(this.items,a),s=this.cursorValue?o.indexOf(this.cursorValue):-1;return s>=0&&n.setSelectedIndex(s),n.onSelectionChange=e=>{this.cursorValue=e.value},n.onSelect=e=>this.multi?this.settle(this.selected):this.settle([e.value]),n.onCancel=()=>this.settle(void 0),n}render_(){this.clear(),this.addChild(new n(this.theme)),this.addChild(new e.Spacer(1)),this.addChild(new e.Text(this.theme.fg(`mdHeading`,this.theme.bold(this.title)),1,0)),this.addChild(new e.Spacer(1)),this.addChild(this.filterInput),this.addChild(this.list),this.addChild(new e.Spacer(1)),this.addChild(new e.Text(this.theme.fg(`muted`,this.multi?`↑↓ navigate space toggle enter confirm esc cancel type to filter`:`↑↓ navigate enter select esc cancel type to filter`),1,0)),this.addChild(new e.Spacer(1)),this.addChild(new n(this.theme))}rebuild(){this.list=this.buildList(),this.render_()}settle(e){this.settled||(this.settled=!0,this.done(e))}handleInput(e){if(this.multi&&e===` `){let e=this.list.getSelectedItem();e&&(this.selected=a(this.selected,e.value),this.cursorValue=e.value,this.rebuild());return}if(this.keybindings.matches(e,`tui.select.up`)||this.keybindings.matches(e,`tui.select.down`)||this.keybindings.matches(e,`tui.select.confirm`)||this.keybindings.matches(e,`tui.select.cancel`)){this.list.handleInput(e);return}let t=this.filterInput.getValue();this.filterInput.handleInput(e);let n=this.filterInput.getValue();n!==t&&this.list.setFilter(n)}};exports.MatrixPickerComponent=o,exports.markItems=r,exports.toggleValue=a,exports.visibleValues=i;
|
|
2
2
|
//# sourceMappingURL=matrixPicker.cjs.map
|