@agimon-ai/doompi 0.0.1-alpha.39 → 0.0.1-alpha.40

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.
@@ -1,3 +1,3 @@
1
- const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./modules/moduleResolution.cjs"),n=require("./sharedBuildCache.cjs");let r=require("node:url"),i=require("node:path");i=e.__toESM(i,1);let a=require("node:fs");a=e.__toESM(a,1);let o=require("node:crypto"),s=require("node:module");const c=[`.ts`,`.mts`,`.cts`],l=`.mjs`,u=`sets`,d=`\0doompi-extension-set`,f=`@agimon-ai/doompi-ui/extensionName`,p=`__DOOMPI_PATH_`,m=`repo/`,h=`external/`,g=`doom-set`,_={"@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 v(e){return c.some(t=>e.endsWith(t))}function y(e){for(let[t,n]of Object.entries(_)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}const b=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function x(e){let n=t.optionalPackageEntry(`@earendil-works/pi-coding-agent`);if(n)try{return(0,s.createRequire)(n).resolve(e)}catch{return}}const S=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),C=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`,`open`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),ee=new Set(s.builtinModules.flatMap(e=>[e,`node:${e}`]));function w(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||g}function T(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function E(e){let t=i.default.dirname(e);for(;;){let e=i.default.join(t,`package.json`);if(a.default.existsSync(e))try{let t=JSON.parse(a.default.readFileSync(e,`utf8`));if(Z(t)&&typeof t.name==`string`)return t.name}catch{return}let n=i.default.dirname(t);if(n===t)return;t=n}}function D(e){let t=i.default.resolve(e);try{return a.default.realpathSync.native(t)}catch{return t}}function O(e,t){let n=i.default.relative(i.default.resolve(e),i.default.resolve(t));return n===``||!n.startsWith(`..`)&&!i.default.isAbsolute(n)}function k(e){let t=(0,o.createHash)(`sha256`).update(e).digest(`hex`);return`${h}${t}`}function A(e,t){let n=D(e);return O(t,n)?{logicalPath:`${m}${i.default.relative(t,n).split(i.default.sep).join(`/`)}`,target:n}:{logicalPath:k(n),target:n,sourcePath:n}}function te(e,t){if(e.logicalPath.startsWith(m)&&e.sourcePath===void 0){let n=i.default.resolve(t,e.logicalPath.slice(5));return O(t,n)?n:void 0}if(e.logicalPath.startsWith(h)&&e.sourcePath!==void 0&&e.logicalPath===k(e.sourcePath))return e.sourcePath}function j(e){try{let t=a.default.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function M(e,t,n){return e.version===t&&e.output===n&&a.default.existsSync(n)&&e.artifacts.every(e=>a.default.existsSync(e))}function N(e,t){return!M(e,`v14`,e.output)||JSON.stringify(e.entries)!==JSON.stringify(t)?!1:e.inputs.every(e=>{let t=j(e.path);return t?.size===e.size&&t.mtimeMs===e.mtimeMs})}function P(e){try{let t=JSON.parse(a.default.readFileSync(e,`utf8`));return t&&typeof t.output==`string`&&Array.isArray(t.artifacts)?t:void 0}catch{return}}function F(e){let t=P(e);return t&&Array.isArray(t.entries)&&Array.isArray(t.inputs)?t:void 0}function I(e,t){a.default.mkdirSync(i.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;a.default.writeFileSync(n,t);try{a.default.renameSync(n,e)}catch(t){if(a.default.rmSync(n,{force:!0}),!a.default.existsSync(e))throw t}}function ne(e){return{format:`esm`,sourcemap:!1,minify:!0,codeSplitting:!0,hashCharacters:`hex`,entryFileNames:e,chunkFileNames:`chunks/[name].[hash:16]${l}`,assetFileNames:`assets/[name].[hash:16][extname]`}}function L(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 R(e,t){try{let n=a.default.readFileSync(e),r=Buffer.from(t);return n.equals(r)}catch{return!1}}function z(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=L(r,e);R(n,t)||I(n,t)}return{entry:L(r,n),artifacts:e.output.map(e=>L(r,e)).sort()}}function B(e,t){return(0,o.createHash)(`sha256`).update(`v3-rolldown-1.2.5`).update(process.version).update(process.platform).update(process.arch).update(t).update(JSON.stringify(e.map(e=>e.logicalPath))).digest(`hex`)}function V(e,t){let r=[];for(let n of e)r.push(A(n,t));r.sort((e,t)=>e.logicalPath.localeCompare(t.logicalPath));let o=[{logicalPath:m,sha256:``,token:`${p}ROOT__`}],s=new Map([[t,`${p}ROOT__`]]),c=new Map;r.forEach((e,t)=>{let r=c.get(e.logicalPath),l=r??`${p}${String(t)}__`;r||(o.push({logicalPath:e.logicalPath,sha256:n.contentSha256(a.default.readFileSync(e.target)),token:l,...e.sourcePath?{sourcePath:e.sourcePath}:{}}),c.set(e.logicalPath,l)),s.set(i.default.resolve(e.target),l)});for(let n of e){let e=A(n,t),r=c.get(e.logicalPath);r&&s.set(i.default.resolve(n),r)}return{shared:o,byTarget:s}}function H(e,t){let n=new Map,i=[...t.entries()].sort(([e],[t])=>t.length-e.length);for(let t of e.output){if(t.type===`asset`){n.set(t.fileName,(t.source,t.source));continue}let e=t.code;for(let[t,n]of i)e=e.replaceAll((0,r.pathToFileURL)(t).href,`${n}:url`).replaceAll(q(t),n).replaceAll(t,n);n.set(t.fileName,e)}return n}function U(e,t,n,r,i){let a=[...i].map(j).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));I(e,`${JSON.stringify({version:`v14`,entries:t,output:n,artifacts:[...r].sort(),inputs:a},null,2)}\n`)}function W(e,t,r,a){let o=n.materializeSharedBuild(e,t),s=new Set(e.replacements.values());return U(r,a,o,e.manifest.artifacts.map(e=>i.default.join(t,e.path)),s),o}function G(e){return(0,o.createHash)(`sha256`).update(`v14`).update(JSON.stringify(e.map(e=>i.default.resolve(e)))).digest(`hex`).slice(0,16)}function K(e){let n=t.optionalPackageEntry(f);if(!n)throw Error(`Cannot resolve ${f}`);let r=e.map(e=>`() => import(${JSON.stringify(q(e))})`),i=e.map(e=>JSON.stringify(e));return[`import { withExtensionSource } from ${JSON.stringify(q(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 q(e){return i.default.resolve(e).split(i.default.sep).join(`/`)}function J(e,n){return{name:`doom-set-external`,async resolveId(r,a,o){if(r===d)return null;if(ee.has(r)||r.startsWith(`node:`))return{id:r,external:!0};if(i.default.isAbsolute(r)){if(!a&&n&&i.default.resolve(r)===i.default.resolve(n))return null;let t=E(r);return t&&(b.has(t)||S.has(t)||C.has(t))?(e.add(r),{id:r,external:!0}):null}if(r.startsWith(`.`))return null;let s=y(r),c=T(s);if(c&&b.has(c)){let n=t.optionalPackageEntry(s);if(n)return e.add(n),{id:n,external:!0}}if(c===`typebox`){let t=x(s);if(t)return e.add(t),{id:t,external:!0}}if(c&&(S.has(c)||C.has(c))){let t=await this.resolve(s,a,o);if(t)return e.add(t.id),{id:t.id,external:!0}}return null}}}function Y(e){return{name:`doom-set-inputs`,load(t){return i.default.isAbsolute(t)&&a.default.existsSync(t)&&e.add(t),null}}}function X(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){if(Array.isArray(e)){for(let n of e)Q(n,t);return}if(!Z(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&Z(n)&&n.type===`MetaProperty`&&Z(n.meta)&&n.meta.name===`import`&&Z(n.property)&&n.property.name===`meta`&&Z(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))Q(n,t)}function re(){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`:v(t)?`ts`:`js`,o=[];if(Q(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}}}function $(e,t,n={}){let r=G(e.map(e=>i.default.resolve(e))),a=i.default.resolve(n.outputDirectory??i.default.join(t,u)),s=w(n.outputName??g),c=(0,o.createHash)(`sha256`).update(a).update(s).digest(`hex`).slice(0,16);return i.default.join(t,u,`${r}.${c}.json`)}async function ie(e,t,r={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let o=e.map(e=>i.default.resolve(e)),s=i.default.join(t,u);a.default.mkdirSync(s,{recursive:!0});let c=i.default.resolve(r.outputDirectory??s),f=w(r.outputName??g);a.default.mkdirSync(c,{recursive:!0});let p=$(o,t,r),m=F(p);if(m&&N(m,o))return m.output;let h=async()=>{let e=new Set(o),t=K(o),{rolldown:n}=await import(`rolldown`),r=await n({input:d,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===d?e:null},load(e){return e===d?t:null}},J(e),re(),Y(e)],onLog:X});try{return{generated:await r.generate(ne(`${f}.[hash:16]${l}`)),inputs:e}}finally{await r.close()}},_=r.repositoryRoot?D(r.repositoryRoot):void 0;if(_&&r.sharedCacheDirectory){let e=B(o.map(e=>A(e,_)),f),t=e=>te(e,_);return n.withSharedBuildLock(r.sharedCacheDirectory,e,async()=>{let i=n.findSharedBuild(r.sharedCacheDirectory,e,t);if(i)return W(i,c,p,o);let{generated:a,inputs:s}=await h(),l=V(s,_),u=H(a,l.byTarget);if([...u.values()].some(e=>typeof e==`string`&&e.includes(_)))throw Error(`Shared build graph still contains an absolute worktree path after tokenization`);let d=a.output.find(e=>e.type===`chunk`&&e.isEntry);if(!d)throw Error(`Rolldown produced no shared extension entry`);n.publishSharedBuild({cacheDirectory:r.sharedCacheDirectory,lookupKey:e,entry:d.fileName,inputs:l.shared,artifacts:u});let f=n.findSharedBuild(r.sharedCacheDirectory,e,t);if(!f)throw Error(`Published shared build could not be verified`);return W(f,c,p,o)})}let{generated:v,inputs:y}=await h(),b=z(v,c);return U(p,o,b.entry,b.artifacts,y),b.entry}exports.compileExtensionSet=ie,exports.extensionSetKey=G,exports.extensionSetManifestPath=$,exports.isTypeScriptEntry=v;
1
+ const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("./modules/moduleResolution.cjs"),n=require("./sharedBuildCache.cjs");let r=require("node:url"),i=require("node:path");i=e.__toESM(i,1);let a=require("node:fs");a=e.__toESM(a,1);let o=require("node:crypto"),s=require("node:module");const c=[`.ts`,`.mts`,`.cts`],l=`.mjs`,u=`sets`,d=`\0doompi-extension-set`,f=`@agimon-ai/doompi-ui/extensionName`,p=`__DOOMPI_PATH_`,m=`repo/`,h=`external/`,g=`doom-set`;function _(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}const v={"@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 y(e){return c.some(t=>e.endsWith(t))}function b(e){for(let[t,n]of Object.entries(v)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}const x=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function S(e){let n=t.optionalPackageEntry(`@earendil-works/pi-coding-agent`);if(n)try{return(0,s.createRequire)(n).resolve(e)}catch{return}}const C=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),w=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`,`open`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),ee=new Set(s.builtinModules.flatMap(e=>[e,`node:${e}`]));function T(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||g}function E(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function D(e){let t=i.default.dirname(e);for(;;){let e=i.default.join(t,`package.json`);if(a.default.existsSync(e))try{let t=JSON.parse(a.default.readFileSync(e,`utf8`));if(Z(t)&&typeof t.name==`string`)return t.name}catch{return}let n=i.default.dirname(t);if(n===t)return;t=n}}function O(e){let t=i.default.resolve(e);try{return a.default.realpathSync.native(t)}catch{return t}}function k(e,t){let n=i.default.relative(i.default.resolve(e),i.default.resolve(t));return n===``||!n.startsWith(`..`)&&!i.default.isAbsolute(n)}function A(e){let t=(0,o.createHash)(`sha256`).update(e).digest(`hex`);return`${h}${t}`}function j(e,t){let n=O(e);return k(t,n)?{logicalPath:`${m}${i.default.relative(t,n).split(i.default.sep).join(`/`)}`,target:n}:{logicalPath:A(n),target:n,sourcePath:n}}function te(e,t){if(e.logicalPath.startsWith(m)&&e.sourcePath===void 0){let n=i.default.resolve(t,e.logicalPath.slice(5));return k(t,n)?n:void 0}if(e.logicalPath.startsWith(h)&&e.sourcePath!==void 0&&e.logicalPath===A(e.sourcePath))return e.sourcePath}function M(e){try{let t=a.default.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function N(e,t,n){return e.version===t&&e.output===n&&a.default.existsSync(n)&&e.artifacts.every(e=>a.default.existsSync(e))}function P(e,t){return!N(e,`v14`,e.output)||JSON.stringify(e.entries)!==JSON.stringify(t)?!1:e.inputs.every(e=>{let t=M(e.path);return t?.size===e.size&&t.mtimeMs===e.mtimeMs})}function F(e){try{let t=JSON.parse(a.default.readFileSync(e,`utf8`));return t&&typeof t.output==`string`&&Array.isArray(t.artifacts)?t:void 0}catch{return}}function ne(e){let t=F(e);return t&&Array.isArray(t.entries)&&Array.isArray(t.inputs)?t:void 0}function I(e,t){a.default.mkdirSync(i.default.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;a.default.writeFileSync(n,t);try{a.default.renameSync(n,e)}catch(t){if(a.default.rmSync(n,{force:!0}),!a.default.existsSync(e))throw t}}function re(e){return{format:`esm`,sourcemap:!1,minify:!0,codeSplitting:!0,hashCharacters:`hex`,entryFileNames:e,chunkFileNames:`chunks/[name].[hash:16]${l}`,assetFileNames:`assets/[name].[hash:16][extname]`}}function L(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 R(e,t){try{let n=a.default.readFileSync(e),r=Buffer.from(t);return n.equals(r)}catch{return!1}}function z(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=L(r,e);R(n,t)||I(n,t)}return{entry:L(r,n),artifacts:e.output.map(e=>L(r,e)).sort()}}function B(e,t){return(0,o.createHash)(`sha256`).update(`v3-rolldown-1.2.5`).update(process.version).update(process.platform).update(process.arch).update(t).update(JSON.stringify(e.map(e=>e.logicalPath))).digest(`hex`)}function V(e,t){let r=[];for(let n of e)r.push(j(n,t));r.sort((e,t)=>e.logicalPath.localeCompare(t.logicalPath));let o=[{logicalPath:m,sha256:``,token:`${p}ROOT__`}],s=new Map([[t,`${p}ROOT__`]]),c=new Map;r.forEach((e,t)=>{let r=c.get(e.logicalPath),l=r??`${p}${String(t)}__`;r||(o.push({logicalPath:e.logicalPath,sha256:n.contentSha256(a.default.readFileSync(e.target)),token:l,...e.sourcePath?{sourcePath:e.sourcePath}:{}}),c.set(e.logicalPath,l)),s.set(i.default.resolve(e.target),l)});for(let n of e){let e=j(n,t),r=c.get(e.logicalPath);r&&s.set(i.default.resolve(n),r)}return{shared:o,byTarget:s}}function H(e,t){let n=new Map,i=[...t.entries()].sort(([e],[t])=>t.length-e.length);for(let t of e.output){if(t.type===`asset`){n.set(t.fileName,(t.source,t.source));continue}let e=t.code;for(let[t,n]of i)e=e.replaceAll((0,r.pathToFileURL)(t).href,`${n}:url`).replaceAll(q(t),n).replaceAll(t,n);n.set(t.fileName,e)}return n}function U(e,t,n,r,i){let a=[...i].map(M).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));I(e,`${JSON.stringify({version:`v14`,entries:t,output:n,artifacts:[...r].sort(),inputs:a},null,2)}\n`)}function W(e,t,r,a){let o=n.materializeSharedBuild(e,t),s=new Set(e.replacements.values());return U(r,a,o,e.manifest.artifacts.map(e=>i.default.join(t,e.path)),s),o}function G(e){return(0,o.createHash)(`sha256`).update(`v14`).update(JSON.stringify(e.map(e=>i.default.resolve(e)))).digest(`hex`).slice(0,16)}function K(e){let n=t.optionalPackageEntry(f);if(!n)throw Error(`Cannot resolve ${f}`);let r=e.map(e=>`() => import(${_(q(e))})`),i=e.map(e=>_(e));return[`import { withExtensionSource } from ${_(q(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 q(e){return i.default.resolve(e).split(i.default.sep).join(`/`)}function J(e,n){return{name:`doom-set-external`,async resolveId(r,a,o){if(r===d)return null;if(ee.has(r)||r.startsWith(`node:`))return{id:r,external:!0};if(i.default.isAbsolute(r)){if(!a&&n&&i.default.resolve(r)===i.default.resolve(n))return null;let t=D(r);return t&&(x.has(t)||C.has(t)||w.has(t))?(e.add(r),{id:r,external:!0}):null}if(r.startsWith(`.`))return null;let s=b(r),c=E(s);if(c&&x.has(c)){let n=t.optionalPackageEntry(s);if(n)return e.add(n),{id:n,external:!0}}if(c===`typebox`){let t=S(s);if(t)return e.add(t),{id:t,external:!0}}if(c&&(C.has(c)||w.has(c))){let t=await this.resolve(s,a,o);if(t)return e.add(t.id),{id:t.id,external:!0}}return null}}}function Y(e){return{name:`doom-set-inputs`,load(t){return i.default.isAbsolute(t)&&a.default.existsSync(t)&&e.add(t),null}}}function X(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){if(Array.isArray(e)){for(let n of e)Q(n,t);return}if(!Z(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&Z(n)&&n.type===`MetaProperty`&&Z(n.meta)&&n.meta.name===`import`&&Z(n.property)&&n.property.name===`meta`&&Z(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))Q(n,t)}function ie(){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`:y(t)?`ts`:`js`,o=[];if(Q(this.parse(e,{lang:a}),o),o.length===0)return null;let s=_((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}}}function $(e,t,n={}){let r=G(e.map(e=>i.default.resolve(e))),a=i.default.resolve(n.outputDirectory??i.default.join(t,u)),s=T(n.outputName??g),c=(0,o.createHash)(`sha256`).update(a).update(s).digest(`hex`).slice(0,16);return i.default.join(t,u,`${r}.${c}.json`)}async function ae(e,t,r={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let o=e.map(e=>i.default.resolve(e)),s=i.default.join(t,u);a.default.mkdirSync(s,{recursive:!0});let c=i.default.resolve(r.outputDirectory??s),f=T(r.outputName??g);a.default.mkdirSync(c,{recursive:!0});let p=$(o,t,r),m=ne(p);if(m&&P(m,o))return m.output;let h=async()=>{let e=new Set(o),t=K(o),{rolldown:n}=await import(`rolldown`),r=await n({input:d,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===d?e:null},load(e){return e===d?t:null}},J(e),ie(),Y(e)],onLog:X});try{return{generated:await r.generate(re(`${f}.[hash:16]${l}`)),inputs:e}}finally{await r.close()}},_=r.repositoryRoot?O(r.repositoryRoot):void 0;if(_&&r.sharedCacheDirectory){let e=B(o.map(e=>j(e,_)),f),t=e=>te(e,_);return n.withSharedBuildLock(r.sharedCacheDirectory,e,async()=>{let i=n.findSharedBuild(r.sharedCacheDirectory,e,t);if(i)return W(i,c,p,o);let{generated:a,inputs:s}=await h(),l=V(s,_),u=H(a,l.byTarget);if([...u.values()].some(e=>typeof e==`string`&&e.includes(_)))throw Error(`Shared build graph still contains an absolute worktree path after tokenization`);let d=a.output.find(e=>e.type===`chunk`&&e.isEntry);if(!d)throw Error(`Rolldown produced no shared extension entry`);n.publishSharedBuild({cacheDirectory:r.sharedCacheDirectory,lookupKey:e,entry:d.fileName,inputs:l.shared,artifacts:u});let f=n.findSharedBuild(r.sharedCacheDirectory,e,t);if(!f)throw Error(`Published shared build could not be verified`);return W(f,c,p,o)})}let{generated:v,inputs:y}=await h(),b=z(v,c);return U(p,o,b.entry,b.artifacts,y),b.entry}exports.compileExtensionSet=ae,exports.extensionSetKey=G,exports.extensionSetManifestPath=$,exports.isTypeScriptEntry=y;
3
3
  //# sourceMappingURL=extensionCompiler.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"extensionCompiler.cjs","names":["optionalPackageEntry","createRequire","builtinModules","path","fs","createHash","contentSha256","pathToFileURL","materializeSharedBuild","withSharedBuildLock","findSharedBuild"],"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 './modules/moduleResolution';\nimport {\n contentSha256,\n findSharedBuild,\n materializeSharedBuild,\n publishSharedBuild,\n type ResolvedSharedBuild,\n type SharedBuildInput,\n withSharedBuildLock,\n} from './sharedBuildCache.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 a worktree-local artifact never relies on its\n * generated directory having its own `node_modules` tree. Immutable build objects\n * may be shared by linked worktrees, but materialized output stays worktree-local.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst SET_CACHE_VERSION = 'v14';\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';\nconst SHARED_BUILD_VERSION = 'v3-rolldown-1.2.5';\nconst SHARED_PATH_TOKEN_PREFIX = '__DOOMPI_PATH_';\nconst REPOSITORY_INPUT_PREFIX = 'repo/';\nconst EXTERNAL_INPUT_PREFIX = 'external/';\nconst DEFAULT_SET_OUTPUT_NAME = 'doom-set';\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 * 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 7 exposes version metadata at its top-level entry and keeps its\n // compiler APIs behind unstable native ESM subpaths. Preserve the installed\n // package graph so extensions resolve those entrypoints at runtime.\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 // open 11 resolves its bundled xdg-open helper relative to import.meta.url.\n // Bundling changes that module location and can break helper discovery.\n 'open',\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 worktree artifact directory. Compiler manifests remain local. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n /** Canonical worktree root used to create relocatable logical input paths. */\n repositoryRoot?: string;\n /** Repository-level immutable cache shared by linked worktrees. */\n sharedCacheDirectory?: 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 || DEFAULT_SET_OUTPUT_NAME;\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 let directory = path.dirname(target);\n while (true) {\n const manifestPath = path.join(directory, 'package.json');\n if (fs.existsSync(manifestPath)) {\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown;\n if (isRecord(manifest) && typeof manifest.name === 'string') return manifest.name;\n } catch {\n return undefined;\n }\n }\n const parent = path.dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n\ninterface LogicalInput {\n logicalPath: string;\n target: string;\n sourcePath?: string;\n}\n\nfunction canonicalPath(target: string): string {\n const absolute = path.resolve(target);\n try {\n return fs.realpathSync.native(absolute);\n } catch {\n return absolute;\n }\n}\n\nfunction isInside(directory: string, target: string): boolean {\n const relative = path.relative(path.resolve(directory), path.resolve(target));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\nfunction externalLogicalPath(sourcePath: string): string {\n const identity = createHash('sha256').update(sourcePath).digest('hex');\n return `${EXTERNAL_INPUT_PREFIX}${identity}`;\n}\n\nfunction logicalInput(target: string, repositoryRoot: string): LogicalInput {\n const absolute = canonicalPath(target);\n if (isInside(repositoryRoot, absolute)) {\n return {\n logicalPath: `${REPOSITORY_INPUT_PREFIX}${path.relative(repositoryRoot, absolute).split(path.sep).join('/')}`,\n target: absolute,\n };\n }\n return {\n logicalPath: externalLogicalPath(absolute),\n target: absolute,\n sourcePath: absolute,\n };\n}\n\nfunction resolveLogicalInputPath(input: SharedBuildInput, repositoryRoot: string): string | undefined {\n if (input.logicalPath.startsWith(REPOSITORY_INPUT_PREFIX) && input.sourcePath === undefined) {\n const target = path.resolve(repositoryRoot, input.logicalPath.slice(REPOSITORY_INPUT_PREFIX.length));\n return isInside(repositoryRoot, target) ? target : undefined;\n }\n if (\n input.logicalPath.startsWith(EXTERNAL_INPUT_PREFIX) &&\n input.sourcePath !== undefined &&\n input.logicalPath === externalLogicalPath(input.sourcePath)\n ) {\n return input.sourcePath;\n }\n return undefined;\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\nfunction sharedLookupKey(entries: readonly LogicalInput[], outputName: string): string {\n return createHash('sha256')\n .update(SHARED_BUILD_VERSION)\n .update(process.version)\n .update(process.platform)\n .update(process.arch)\n .update(outputName)\n .update(JSON.stringify(entries.map((entry) => entry.logicalPath)))\n .digest('hex');\n}\n\ninterface TokenizedInputs {\n shared: SharedBuildInput[];\n byTarget: Map<string, string>;\n}\n\nfunction tokenizedInputs(inputs: ReadonlySet<string>, repositoryRoot: string): TokenizedInputs {\n const logical: LogicalInput[] = [];\n for (const target of inputs) logical.push(logicalInput(target, repositoryRoot));\n logical.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath));\n const shared: SharedBuildInput[] = [\n { logicalPath: REPOSITORY_INPUT_PREFIX, sha256: '', token: `${SHARED_PATH_TOKEN_PREFIX}ROOT__` },\n ];\n const byTarget = new Map<string, string>([[repositoryRoot, `${SHARED_PATH_TOKEN_PREFIX}ROOT__`]]);\n const tokenByLogicalPath = new Map<string, string>();\n logical.forEach((input, index) => {\n const existing = tokenByLogicalPath.get(input.logicalPath);\n const token = existing ?? `${SHARED_PATH_TOKEN_PREFIX}${String(index)}__`;\n if (!existing) {\n shared.push({\n logicalPath: input.logicalPath,\n sha256: contentSha256(fs.readFileSync(input.target)),\n token,\n ...(input.sourcePath ? { sourcePath: input.sourcePath } : {}),\n });\n tokenByLogicalPath.set(input.logicalPath, token);\n }\n byTarget.set(path.resolve(input.target), token);\n });\n for (const target of inputs) {\n const input = logicalInput(target, repositoryRoot);\n const token = tokenByLogicalPath.get(input.logicalPath);\n if (token) byTarget.set(path.resolve(target), token);\n }\n return { shared, byTarget };\n}\n\nfunction tokenizedArtifactContents(\n generated: RolldownOutput,\n tokens: ReadonlyMap<string, string>,\n): Map<string, string | Uint8Array> {\n const artifacts = new Map<string, string | Uint8Array>();\n const replacements = [...tokens.entries()].sort(([left], [right]) => right.length - left.length);\n for (const artifact of generated.output) {\n if (artifact.type === 'asset') {\n artifacts.set(artifact.fileName, typeof artifact.source === 'string' ? artifact.source : artifact.source);\n continue;\n }\n let source = artifact.code;\n for (const [target, token] of replacements) {\n source = source\n .replaceAll(pathToFileURL(target).href, `${token}:url`)\n .replaceAll(pathToImportSpecifier(target), token)\n .replaceAll(target, token);\n }\n artifacts.set(artifact.fileName, source);\n }\n return artifacts;\n}\n\nfunction writeLocalSetManifest(\n manifestPath: string,\n entries: string[],\n output: string,\n artifacts: string[],\n inputs: ReadonlySet<string>,\n): void {\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 { version: SET_CACHE_VERSION, entries, output, artifacts: [...artifacts].sort(), inputs: inputFingerprints },\n null,\n 2,\n )}\\n`,\n );\n}\n\nfunction materializeSharedSet(\n build: ResolvedSharedBuild,\n outputDirectory: string,\n manifestPath: string,\n entries: string[],\n): string {\n const output = materializeSharedBuild(build, outputDirectory);\n const inputs = new Set(build.replacements.values());\n const artifacts = build.manifest.artifacts.map((artifact) => path.join(outputDirectory, artifact.path));\n writeLocalSetManifest(manifestPath, entries, output, artifacts, inputs);\n return output;\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>, entry?: 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 if (!importer && entry && path.resolve(specifier) === path.resolve(entry)) return null;\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/** Location of the lightweight input-fingerprint record for one extension set. */\nexport function extensionSetManifestPath(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): string {\n const normalized = entries.map((entry) => path.resolve(entry));\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? path.join(cacheDirectory, SET_DIRECTORY));\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\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 return path.join(cacheDirectory, SET_DIRECTORY, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\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 outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\n fs.mkdirSync(outputDirectory, { recursive: true });\n const manifestPath = extensionSetManifestPath(normalized, cacheDirectory, options);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const generate = async (): Promise<{ generated: RolldownOutput; inputs: Set<string> }> => {\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 try {\n return {\n generated: await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`)),\n inputs,\n };\n } finally {\n await build.close();\n }\n };\n\n const repositoryRoot = options.repositoryRoot ? canonicalPath(options.repositoryRoot) : undefined;\n\n if (repositoryRoot && options.sharedCacheDirectory) {\n const logicalEntries = normalized.map((entry) => logicalInput(entry, repositoryRoot));\n const lookupKey = sharedLookupKey(logicalEntries, outputName);\n const resolveInput = (input: SharedBuildInput): string | undefined =>\n resolveLogicalInputPath(input, repositoryRoot);\n return withSharedBuildLock(options.sharedCacheDirectory, lookupKey, async () => {\n const cached = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (cached) return materializeSharedSet(cached, outputDirectory, manifestPath, normalized);\n\n const { generated, inputs } = await generate();\n const tokenized = tokenizedInputs(inputs, repositoryRoot);\n const artifacts = tokenizedArtifactContents(generated, tokenized.byTarget);\n if (\n [...artifacts.values()].some((contents) => typeof contents === 'string' && contents.includes(repositoryRoot))\n ) {\n throw new Error('Shared build graph still contains an absolute worktree path after tokenization');\n }\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry) throw new Error('Rolldown produced no shared extension entry');\n publishSharedBuild({\n cacheDirectory: options.sharedCacheDirectory as string,\n lookupKey,\n entry: entry.fileName,\n inputs: tokenized.shared,\n artifacts,\n });\n const published = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (!published) throw new Error('Published shared build could not be verified');\n return materializeSharedSet(published, outputDirectory, manifestPath, normalized);\n });\n }\n\n const { generated, inputs } = await generate();\n const compiled = writeCompiledGraph(generated, outputDirectory);\n writeLocalSetManifest(manifestPath, normalized, compiled.entry, compiled.artifacts, inputs);\n return compiled.entry;\n}\n"],"mappings":"0SAmCA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AAgB,EAAQ,qBAAgC,EAAW,CAAY,EACjG,GAAI,CAAC,EAAW,MAAU,MAAM,8CAA8C,EAC9E,OAAO,EAAqB,EAAW,EAAiB,EAAc,CAAU,CAClF,CAAC,CACH,CAEA,GAAM,CAAE,YAAW,UAAW,MAAM,EAAS,EACvC,EAAW,EAAmB,EAAW,CAAe,EAE9D,OADA,EAAsB,EAAc,EAAY,EAAS,MAAO,EAAS,UAAW,CAAM,EACnF,EAAS,KAClB"}
1
+ {"version":3,"file":"extensionCompiler.cjs","names":["optionalPackageEntry","createRequire","builtinModules","path","fs","createHash","contentSha256","pathToFileURL","materializeSharedBuild","withSharedBuildLock","findSharedBuild"],"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 './modules/moduleResolution';\nimport {\n contentSha256,\n findSharedBuild,\n materializeSharedBuild,\n publishSharedBuild,\n type ResolvedSharedBuild,\n type SharedBuildInput,\n withSharedBuildLock,\n} from './sharedBuildCache.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 a worktree-local artifact never relies on its\n * generated directory having its own `node_modules` tree. Immutable build objects\n * may be shared by linked worktrees, but materialized output stays worktree-local.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst SET_CACHE_VERSION = 'v14';\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';\nconst SHARED_BUILD_VERSION = 'v3-rolldown-1.2.5';\nconst SHARED_PATH_TOKEN_PREFIX = '__DOOMPI_PATH_';\nconst REPOSITORY_INPUT_PREFIX = 'repo/';\nconst EXTERNAL_INPUT_PREFIX = 'external/';\nconst DEFAULT_SET_OUTPUT_NAME = 'doom-set';\n\n/** Serializes data embedded in generated JavaScript without leaving HTML or line-separator code boundaries. */\nfunction javascriptStringLiteral(value: string): string {\n return JSON.stringify(value)\n .replaceAll('<', '\\\\u003c')\n .replaceAll('\\u2028', '\\\\u2028')\n .replaceAll('\\u2029', '\\\\u2029');\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 * 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 7 exposes version metadata at its top-level entry and keeps its\n // compiler APIs behind unstable native ESM subpaths. Preserve the installed\n // package graph so extensions resolve those entrypoints at runtime.\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 // open 11 resolves its bundled xdg-open helper relative to import.meta.url.\n // Bundling changes that module location and can break helper discovery.\n 'open',\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 worktree artifact directory. Compiler manifests remain local. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n /** Canonical worktree root used to create relocatable logical input paths. */\n repositoryRoot?: string;\n /** Repository-level immutable cache shared by linked worktrees. */\n sharedCacheDirectory?: 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 || DEFAULT_SET_OUTPUT_NAME;\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 let directory = path.dirname(target);\n while (true) {\n const manifestPath = path.join(directory, 'package.json');\n if (fs.existsSync(manifestPath)) {\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown;\n if (isRecord(manifest) && typeof manifest.name === 'string') return manifest.name;\n } catch {\n return undefined;\n }\n }\n const parent = path.dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n\ninterface LogicalInput {\n logicalPath: string;\n target: string;\n sourcePath?: string;\n}\n\nfunction canonicalPath(target: string): string {\n const absolute = path.resolve(target);\n try {\n return fs.realpathSync.native(absolute);\n } catch {\n return absolute;\n }\n}\n\nfunction isInside(directory: string, target: string): boolean {\n const relative = path.relative(path.resolve(directory), path.resolve(target));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\nfunction externalLogicalPath(sourcePath: string): string {\n const identity = createHash('sha256').update(sourcePath).digest('hex');\n return `${EXTERNAL_INPUT_PREFIX}${identity}`;\n}\n\nfunction logicalInput(target: string, repositoryRoot: string): LogicalInput {\n const absolute = canonicalPath(target);\n if (isInside(repositoryRoot, absolute)) {\n return {\n logicalPath: `${REPOSITORY_INPUT_PREFIX}${path.relative(repositoryRoot, absolute).split(path.sep).join('/')}`,\n target: absolute,\n };\n }\n return {\n logicalPath: externalLogicalPath(absolute),\n target: absolute,\n sourcePath: absolute,\n };\n}\n\nfunction resolveLogicalInputPath(input: SharedBuildInput, repositoryRoot: string): string | undefined {\n if (input.logicalPath.startsWith(REPOSITORY_INPUT_PREFIX) && input.sourcePath === undefined) {\n const target = path.resolve(repositoryRoot, input.logicalPath.slice(REPOSITORY_INPUT_PREFIX.length));\n return isInside(repositoryRoot, target) ? target : undefined;\n }\n if (\n input.logicalPath.startsWith(EXTERNAL_INPUT_PREFIX) &&\n input.sourcePath !== undefined &&\n input.logicalPath === externalLogicalPath(input.sourcePath)\n ) {\n return input.sourcePath;\n }\n return undefined;\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\nfunction sharedLookupKey(entries: readonly LogicalInput[], outputName: string): string {\n return createHash('sha256')\n .update(SHARED_BUILD_VERSION)\n .update(process.version)\n .update(process.platform)\n .update(process.arch)\n .update(outputName)\n .update(JSON.stringify(entries.map((entry) => entry.logicalPath)))\n .digest('hex');\n}\n\ninterface TokenizedInputs {\n shared: SharedBuildInput[];\n byTarget: Map<string, string>;\n}\n\nfunction tokenizedInputs(inputs: ReadonlySet<string>, repositoryRoot: string): TokenizedInputs {\n const logical: LogicalInput[] = [];\n for (const target of inputs) logical.push(logicalInput(target, repositoryRoot));\n logical.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath));\n const shared: SharedBuildInput[] = [\n { logicalPath: REPOSITORY_INPUT_PREFIX, sha256: '', token: `${SHARED_PATH_TOKEN_PREFIX}ROOT__` },\n ];\n const byTarget = new Map<string, string>([[repositoryRoot, `${SHARED_PATH_TOKEN_PREFIX}ROOT__`]]);\n const tokenByLogicalPath = new Map<string, string>();\n logical.forEach((input, index) => {\n const existing = tokenByLogicalPath.get(input.logicalPath);\n const token = existing ?? `${SHARED_PATH_TOKEN_PREFIX}${String(index)}__`;\n if (!existing) {\n shared.push({\n logicalPath: input.logicalPath,\n sha256: contentSha256(fs.readFileSync(input.target)),\n token,\n ...(input.sourcePath ? { sourcePath: input.sourcePath } : {}),\n });\n tokenByLogicalPath.set(input.logicalPath, token);\n }\n byTarget.set(path.resolve(input.target), token);\n });\n for (const target of inputs) {\n const input = logicalInput(target, repositoryRoot);\n const token = tokenByLogicalPath.get(input.logicalPath);\n if (token) byTarget.set(path.resolve(target), token);\n }\n return { shared, byTarget };\n}\n\nfunction tokenizedArtifactContents(\n generated: RolldownOutput,\n tokens: ReadonlyMap<string, string>,\n): Map<string, string | Uint8Array> {\n const artifacts = new Map<string, string | Uint8Array>();\n const replacements = [...tokens.entries()].sort(([left], [right]) => right.length - left.length);\n for (const artifact of generated.output) {\n if (artifact.type === 'asset') {\n artifacts.set(artifact.fileName, typeof artifact.source === 'string' ? artifact.source : artifact.source);\n continue;\n }\n let source = artifact.code;\n for (const [target, token] of replacements) {\n source = source\n .replaceAll(pathToFileURL(target).href, `${token}:url`)\n .replaceAll(pathToImportSpecifier(target), token)\n .replaceAll(target, token);\n }\n artifacts.set(artifact.fileName, source);\n }\n return artifacts;\n}\n\nfunction writeLocalSetManifest(\n manifestPath: string,\n entries: string[],\n output: string,\n artifacts: string[],\n inputs: ReadonlySet<string>,\n): void {\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 { version: SET_CACHE_VERSION, entries, output, artifacts: [...artifacts].sort(), inputs: inputFingerprints },\n null,\n 2,\n )}\\n`,\n );\n}\n\nfunction materializeSharedSet(\n build: ResolvedSharedBuild,\n outputDirectory: string,\n manifestPath: string,\n entries: string[],\n): string {\n const output = materializeSharedBuild(build, outputDirectory);\n const inputs = new Set(build.replacements.values());\n const artifacts = build.manifest.artifacts.map((artifact) => path.join(outputDirectory, artifact.path));\n writeLocalSetManifest(manifestPath, entries, output, artifacts, inputs);\n return output;\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(${javascriptStringLiteral(pathToImportSpecifier(entry))})`);\n const names = entries.map((entry) => javascriptStringLiteral(entry));\n return [\n `import { withExtensionSource } from ${javascriptStringLiteral(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>, entry?: 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 if (!importer && entry && path.resolve(specifier) === path.resolve(entry)) return null;\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 = javascriptStringLiteral(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/** Location of the lightweight input-fingerprint record for one extension set. */\nexport function extensionSetManifestPath(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): string {\n const normalized = entries.map((entry) => path.resolve(entry));\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? path.join(cacheDirectory, SET_DIRECTORY));\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\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 return path.join(cacheDirectory, SET_DIRECTORY, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\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 outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\n fs.mkdirSync(outputDirectory, { recursive: true });\n const manifestPath = extensionSetManifestPath(normalized, cacheDirectory, options);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const generate = async (): Promise<{ generated: RolldownOutput; inputs: Set<string> }> => {\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 try {\n return {\n generated: await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`)),\n inputs,\n };\n } finally {\n await build.close();\n }\n };\n\n const repositoryRoot = options.repositoryRoot ? canonicalPath(options.repositoryRoot) : undefined;\n\n if (repositoryRoot && options.sharedCacheDirectory) {\n const logicalEntries = normalized.map((entry) => logicalInput(entry, repositoryRoot));\n const lookupKey = sharedLookupKey(logicalEntries, outputName);\n const resolveInput = (input: SharedBuildInput): string | undefined =>\n resolveLogicalInputPath(input, repositoryRoot);\n return withSharedBuildLock(options.sharedCacheDirectory, lookupKey, async () => {\n const cached = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (cached) return materializeSharedSet(cached, outputDirectory, manifestPath, normalized);\n\n const { generated, inputs } = await generate();\n const tokenized = tokenizedInputs(inputs, repositoryRoot);\n const artifacts = tokenizedArtifactContents(generated, tokenized.byTarget);\n if (\n [...artifacts.values()].some((contents) => typeof contents === 'string' && contents.includes(repositoryRoot))\n ) {\n throw new Error('Shared build graph still contains an absolute worktree path after tokenization');\n }\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry) throw new Error('Rolldown produced no shared extension entry');\n publishSharedBuild({\n cacheDirectory: options.sharedCacheDirectory as string,\n lookupKey,\n entry: entry.fileName,\n inputs: tokenized.shared,\n artifacts,\n });\n const published = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (!published) throw new Error('Published shared build could not be verified');\n return materializeSharedSet(published, outputDirectory, manifestPath, normalized);\n });\n }\n\n const { generated, inputs } = await generate();\n const compiled = writeCompiledGraph(generated, outputDirectory);\n writeLocalSetManifest(manifestPath, normalized, compiled.entry, compiled.artifacts, inputs);\n return compiled.entry;\n}\n"],"mappings":"0SAmCA,MAAM,EAAsB,CAAC,MAAO,OAAQ,MAAM,EAC5C,EAAkB,OAGlB,EAAgB,OAEhB,EAAoB,yBACpB,EAA0B,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,OAClB,WACF,CAAC,EACD,IAAM,EAAYA,EAAAA,gBAAgB,EAAQ,qBAAgC,EAAW,CAAY,EACjG,GAAI,CAAC,EAAW,MAAU,MAAM,8CAA8C,EAC9E,OAAO,EAAqB,EAAW,EAAiB,EAAc,CAAU,CAClF,CAAC,CACH,CAEA,GAAM,CAAE,YAAW,UAAW,MAAM,EAAS,EACvC,EAAW,EAAmB,EAAW,CAAe,EAE9D,OADA,EAAsB,EAAc,EAAY,EAAS,MAAO,EAAS,UAAW,CAAM,EACnF,EAAS,KAClB"}
@@ -1,3 +1,3 @@
1
- import{optionalPackageEntry as e}from"./modules/moduleResolution.mjs";import{contentSha256 as t,findSharedBuild as n,materializeSharedBuild as r,publishSharedBuild as i,withSharedBuildLock as a}from"./sharedBuildCache.mjs";import{builtinModules as o,createRequire as s}from"node:module";import{pathToFileURL as c}from"node:url";import l from"node:path";import u from"node:fs";import{createHash as d}from"node:crypto";const f=[`.ts`,`.mts`,`.cts`],p=`.mjs`,m=`sets`,h=`\0doompi-extension-set`,g=`@agimon-ai/doompi-ui/extensionName`,_=`__DOOMPI_PATH_`,v=`repo/`,y=`external/`,b=`doom-set`,x={"@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 S(e){return f.some(t=>e.endsWith(t))}function C(e){for(let[t,n]of Object.entries(x)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}const w=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function T(t){let n=e(`@earendil-works/pi-coding-agent`);if(n)try{return s(n).resolve(t)}catch{return}}const E=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),D=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`,`open`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),O=new Set(o.flatMap(e=>[e,`node:${e}`]));function k(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||b}function A(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function j(e){let t=l.dirname(e);for(;;){let e=l.join(t,`package.json`);if(u.existsSync(e))try{let t=JSON.parse(u.readFileSync(e,`utf8`));if(Z(t)&&typeof t.name==`string`)return t.name}catch{return}let n=l.dirname(t);if(n===t)return;t=n}}function M(e){let t=l.resolve(e);try{return u.realpathSync.native(t)}catch{return t}}function N(e,t){let n=l.relative(l.resolve(e),l.resolve(t));return n===``||!n.startsWith(`..`)&&!l.isAbsolute(n)}function P(e){let t=d(`sha256`).update(e).digest(`hex`);return`${y}${t}`}function F(e,t){let n=M(e);return N(t,n)?{logicalPath:`${v}${l.relative(t,n).split(l.sep).join(`/`)}`,target:n}:{logicalPath:P(n),target:n,sourcePath:n}}function I(e,t){if(e.logicalPath.startsWith(v)&&e.sourcePath===void 0){let n=l.resolve(t,e.logicalPath.slice(5));return N(t,n)?n:void 0}if(e.logicalPath.startsWith(y)&&e.sourcePath!==void 0&&e.logicalPath===P(e.sourcePath))return e.sourcePath}function L(e){try{let t=u.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function ee(e,t,n){return e.version===t&&e.output===n&&u.existsSync(n)&&e.artifacts.every(e=>u.existsSync(e))}function te(e,t){return!ee(e,`v14`,e.output)||JSON.stringify(e.entries)!==JSON.stringify(t)?!1:e.inputs.every(e=>{let t=L(e.path);return t?.size===e.size&&t.mtimeMs===e.mtimeMs})}function ne(e){try{let t=JSON.parse(u.readFileSync(e,`utf8`));return t&&typeof t.output==`string`&&Array.isArray(t.artifacts)?t:void 0}catch{return}}function re(e){let t=ne(e);return t&&Array.isArray(t.entries)&&Array.isArray(t.inputs)?t:void 0}function R(e,t){u.mkdirSync(l.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;u.writeFileSync(n,t);try{u.renameSync(n,e)}catch(t){if(u.rmSync(n,{force:!0}),!u.existsSync(e))throw t}}function z(e){return{format:`esm`,sourcemap:!1,minify:!0,codeSplitting:!0,hashCharacters:`hex`,entryFileNames:e,chunkFileNames:`chunks/[name].[hash:16]${p}`,assetFileNames:`assets/[name].[hash:16][extname]`}}function B(e,t){let n=l.resolve(e,t.fileName),r=l.relative(e,n);if(r.startsWith(`..`)||l.isAbsolute(r))throw Error(`Rolldown emitted an artifact outside the output directory: ${t.fileName}`);return n}function V(e,t){try{let n=u.readFileSync(e),r=Buffer.from(t);return n.equals(r)}catch{return!1}}function H(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=l.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=B(r,e);V(n,t)||R(n,t)}return{entry:B(r,n),artifacts:e.output.map(e=>B(r,e)).sort()}}function U(e,t){return d(`sha256`).update(`v3-rolldown-1.2.5`).update(process.version).update(process.platform).update(process.arch).update(t).update(JSON.stringify(e.map(e=>e.logicalPath))).digest(`hex`)}function W(e,n){let r=[];for(let t of e)r.push(F(t,n));r.sort((e,t)=>e.logicalPath.localeCompare(t.logicalPath));let i=[{logicalPath:v,sha256:``,token:`${_}ROOT__`}],a=new Map([[n,`${_}ROOT__`]]),o=new Map;r.forEach((e,n)=>{let r=o.get(e.logicalPath),s=r??`${_}${String(n)}__`;r||(i.push({logicalPath:e.logicalPath,sha256:t(u.readFileSync(e.target)),token:s,...e.sourcePath?{sourcePath:e.sourcePath}:{}}),o.set(e.logicalPath,s)),a.set(l.resolve(e.target),s)});for(let t of e){let e=F(t,n),r=o.get(e.logicalPath);r&&a.set(l.resolve(t),r)}return{shared:i,byTarget:a}}function G(e,t){let n=new Map,r=[...t.entries()].sort(([e],[t])=>t.length-e.length);for(let t of e.output){if(t.type===`asset`){n.set(t.fileName,(t.source,t.source));continue}let e=t.code;for(let[t,n]of r)e=e.replaceAll(c(t).href,`${n}:url`).replaceAll(X(t),n).replaceAll(t,n);n.set(t.fileName,e)}return n}function K(e,t,n,r,i){let a=[...i].map(L).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));R(e,`${JSON.stringify({version:`v14`,entries:t,output:n,artifacts:[...r].sort(),inputs:a},null,2)}\n`)}function q(e,t,n,i){let a=r(e,t),o=new Set(e.replacements.values());return K(n,i,a,e.manifest.artifacts.map(e=>l.join(t,e.path)),o),a}function J(e){return d(`sha256`).update(`v14`).update(JSON.stringify(e.map(e=>l.resolve(e)))).digest(`hex`).slice(0,16)}function Y(t){let n=e(g);if(!n)throw Error(`Cannot resolve ${g}`);let r=t.map(e=>`() => import(${JSON.stringify(X(e))})`),i=t.map(e=>JSON.stringify(e));return[`import { withExtensionSource } from ${JSON.stringify(X(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 X(e){return l.resolve(e).split(l.sep).join(`/`)}function ie(t,n){return{name:`doom-set-external`,async resolveId(r,i,a){if(r===h)return null;if(O.has(r)||r.startsWith(`node:`))return{id:r,external:!0};if(l.isAbsolute(r)){if(!i&&n&&l.resolve(r)===l.resolve(n))return null;let e=j(r);return e&&(w.has(e)||E.has(e)||D.has(e))?(t.add(r),{id:r,external:!0}):null}if(r.startsWith(`.`))return null;let o=C(r),s=A(o);if(s&&w.has(s)){let n=e(o);if(n)return t.add(n),{id:n,external:!0}}if(s===`typebox`){let e=T(o);if(e)return t.add(e),{id:e,external:!0}}if(s&&(E.has(s)||D.has(s))){let e=await this.resolve(o,i,a);if(e)return t.add(e.id),{id:e.id,external:!0}}return null}}}function ae(e){return{name:`doom-set-inputs`,load(t){return l.isAbsolute(t)&&u.existsSync(t)&&e.add(t),null}}}function oe(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){if(Array.isArray(e)){for(let n of e)Q(n,t);return}if(!Z(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&Z(n)&&n.type===`MetaProperty`&&Z(n.meta)&&n.meta.name===`import`&&Z(n.property)&&n.property.name===`meta`&&Z(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))Q(n,t)}function se(){return{name:`doom-original-import-meta-url`,transform(e,t){if(!l.isAbsolute(t)||!e.includes(`import.meta.url`))return null;let n=l.extname(t).toLowerCase(),r=n===`.tsx`?`tsx`:n===`.jsx`?`jsx`:S(t)?`ts`:`js`,i=[];if(Q(this.parse(e,{lang:r}),i),i.length===0)return null;let a=JSON.stringify(c(t).href),o=e;for(let e of i.sort((e,t)=>t.start-e.start))o=`${o.slice(0,e.start)}${a}${o.slice(e.end)}`;return o}}}function $(e,t,n={}){let r=J(e.map(e=>l.resolve(e))),i=l.resolve(n.outputDirectory??l.join(t,m)),a=k(n.outputName??b),o=d(`sha256`).update(i).update(a).digest(`hex`).slice(0,16);return l.join(t,m,`${r}.${o}.json`)}async function ce(e,t,r={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let o=e.map(e=>l.resolve(e)),s=l.join(t,m);u.mkdirSync(s,{recursive:!0});let c=l.resolve(r.outputDirectory??s),d=k(r.outputName??b);u.mkdirSync(c,{recursive:!0});let f=$(o,t,r),g=re(f);if(g&&te(g,o))return g.output;let _=async()=>{let e=new Set(o),t=Y(o),{rolldown:n}=await import(`rolldown`),r=await n({input:h,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===h?e:null},load(e){return e===h?t:null}},ie(e),se(),ae(e)],onLog:oe});try{return{generated:await r.generate(z(`${d}.[hash:16]${p}`)),inputs:e}}finally{await r.close()}},v=r.repositoryRoot?M(r.repositoryRoot):void 0;if(v&&r.sharedCacheDirectory){let e=U(o.map(e=>F(e,v)),d),t=e=>I(e,v);return a(r.sharedCacheDirectory,e,async()=>{let a=n(r.sharedCacheDirectory,e,t);if(a)return q(a,c,f,o);let{generated:s,inputs:l}=await _(),u=W(l,v),d=G(s,u.byTarget);if([...d.values()].some(e=>typeof e==`string`&&e.includes(v)))throw Error(`Shared build graph still contains an absolute worktree path after tokenization`);let p=s.output.find(e=>e.type===`chunk`&&e.isEntry);if(!p)throw Error(`Rolldown produced no shared extension entry`);i({cacheDirectory:r.sharedCacheDirectory,lookupKey:e,entry:p.fileName,inputs:u.shared,artifacts:d});let m=n(r.sharedCacheDirectory,e,t);if(!m)throw Error(`Published shared build could not be verified`);return q(m,c,f,o)})}let{generated:y,inputs:x}=await _(),S=H(y,c);return K(f,o,S.entry,S.artifacts,x),S.entry}export{ce as compileExtensionSet,J as extensionSetKey,$ as extensionSetManifestPath,S as isTypeScriptEntry};
1
+ import{optionalPackageEntry as e}from"./modules/moduleResolution.mjs";import{contentSha256 as t,findSharedBuild as n,materializeSharedBuild as r,publishSharedBuild as i,withSharedBuildLock as a}from"./sharedBuildCache.mjs";import{builtinModules as o,createRequire as s}from"node:module";import{pathToFileURL as c}from"node:url";import l from"node:path";import u from"node:fs";import{createHash as d}from"node:crypto";const f=[`.ts`,`.mts`,`.cts`],p=`.mjs`,m=`sets`,h=`\0doompi-extension-set`,g=`@agimon-ai/doompi-ui/extensionName`,_=`__DOOMPI_PATH_`,v=`repo/`,y=`external/`,b=`doom-set`;function x(e){return JSON.stringify(e).replaceAll(`<`,`\\u003c`).replaceAll(`\u2028`,`\\u2028`).replaceAll(`\u2029`,`\\u2029`)}const S={"@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 C(e){return f.some(t=>e.endsWith(t))}function w(e){for(let[t,n]of Object.entries(S)){if(e===t)return n;if(e.startsWith(`${t}/`))return`${n}${e.slice(t.length)}`}return e}const T=new Set([`@earendil-works/pi-coding-agent`,`@earendil-works/pi-tui`,`@earendil-works/pi-ai`]);function E(t){let n=e(`@earendil-works/pi-coding-agent`);if(n)try{return s(n).resolve(t)}catch{return}}const D=new Set([`@parcel/watcher`,`@napi-rs/keyring`,`better-sqlite3`,`canvas`,`fsevents`,`isolated-vm`,`keytar`,`node-pty`,`onnxruntime-node`,`playwright`,`playwright-core`,`puppeteer`,`sharp`,`typescript`]),O=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`,`open`,`reflect-metadata`,`zod-to-json-schema`,`yaml`,`zod`]),k=new Set(o.flatMap(e=>[e,`node:${e}`]));function A(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^[-.]+|[-.]+$/g,``)||b}function j(e){let t=e.startsWith(`@`)?e.indexOf(`/`,e.indexOf(`/`)+1):e.indexOf(`/`);return t===-1?e:e.slice(0,t)}function ee(e){let t=l.dirname(e);for(;;){let e=l.join(t,`package.json`);if(u.existsSync(e))try{let t=JSON.parse(u.readFileSync(e,`utf8`));if(X(t)&&typeof t.name==`string`)return t.name}catch{return}let n=l.dirname(t);if(n===t)return;t=n}}function M(e){let t=l.resolve(e);try{return u.realpathSync.native(t)}catch{return t}}function N(e,t){let n=l.relative(l.resolve(e),l.resolve(t));return n===``||!n.startsWith(`..`)&&!l.isAbsolute(n)}function P(e){let t=d(`sha256`).update(e).digest(`hex`);return`${y}${t}`}function F(e,t){let n=M(e);return N(t,n)?{logicalPath:`${v}${l.relative(t,n).split(l.sep).join(`/`)}`,target:n}:{logicalPath:P(n),target:n,sourcePath:n}}function I(e,t){if(e.logicalPath.startsWith(v)&&e.sourcePath===void 0){let n=l.resolve(t,e.logicalPath.slice(5));return N(t,n)?n:void 0}if(e.logicalPath.startsWith(y)&&e.sourcePath!==void 0&&e.logicalPath===P(e.sourcePath))return e.sourcePath}function L(e){try{let t=u.statSync(e);return t.isFile()?{path:e,size:t.size,mtimeMs:t.mtimeMs}:void 0}catch{return}}function te(e,t,n){return e.version===t&&e.output===n&&u.existsSync(n)&&e.artifacts.every(e=>u.existsSync(e))}function ne(e,t){return!te(e,`v14`,e.output)||JSON.stringify(e.entries)!==JSON.stringify(t)?!1:e.inputs.every(e=>{let t=L(e.path);return t?.size===e.size&&t.mtimeMs===e.mtimeMs})}function re(e){try{let t=JSON.parse(u.readFileSync(e,`utf8`));return t&&typeof t.output==`string`&&Array.isArray(t.artifacts)?t:void 0}catch{return}}function ie(e){let t=re(e);return t&&Array.isArray(t.entries)&&Array.isArray(t.inputs)?t:void 0}function R(e,t){u.mkdirSync(l.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;u.writeFileSync(n,t);try{u.renameSync(n,e)}catch(t){if(u.rmSync(n,{force:!0}),!u.existsSync(e))throw t}}function z(e){return{format:`esm`,sourcemap:!1,minify:!0,codeSplitting:!0,hashCharacters:`hex`,entryFileNames:e,chunkFileNames:`chunks/[name].[hash:16]${p}`,assetFileNames:`assets/[name].[hash:16][extname]`}}function B(e,t){let n=l.resolve(e,t.fileName),r=l.relative(e,n);if(r.startsWith(`..`)||l.isAbsolute(r))throw Error(`Rolldown emitted an artifact outside the output directory: ${t.fileName}`);return n}function V(e,t){try{let n=u.readFileSync(e),r=Buffer.from(t);return n.equals(r)}catch{return!1}}function H(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=l.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=B(r,e);V(n,t)||R(n,t)}return{entry:B(r,n),artifacts:e.output.map(e=>B(r,e)).sort()}}function U(e,t){return d(`sha256`).update(`v3-rolldown-1.2.5`).update(process.version).update(process.platform).update(process.arch).update(t).update(JSON.stringify(e.map(e=>e.logicalPath))).digest(`hex`)}function W(e,n){let r=[];for(let t of e)r.push(F(t,n));r.sort((e,t)=>e.logicalPath.localeCompare(t.logicalPath));let i=[{logicalPath:v,sha256:``,token:`${_}ROOT__`}],a=new Map([[n,`${_}ROOT__`]]),o=new Map;r.forEach((e,n)=>{let r=o.get(e.logicalPath),s=r??`${_}${String(n)}__`;r||(i.push({logicalPath:e.logicalPath,sha256:t(u.readFileSync(e.target)),token:s,...e.sourcePath?{sourcePath:e.sourcePath}:{}}),o.set(e.logicalPath,s)),a.set(l.resolve(e.target),s)});for(let t of e){let e=F(t,n),r=o.get(e.logicalPath);r&&a.set(l.resolve(t),r)}return{shared:i,byTarget:a}}function G(e,t){let n=new Map,r=[...t.entries()].sort(([e],[t])=>t.length-e.length);for(let t of e.output){if(t.type===`asset`){n.set(t.fileName,(t.source,t.source));continue}let e=t.code;for(let[t,n]of r)e=e.replaceAll(c(t).href,`${n}:url`).replaceAll(Y(t),n).replaceAll(t,n);n.set(t.fileName,e)}return n}function K(e,t,n,r,i){let a=[...i].map(L).filter(e=>e!==void 0).sort((e,t)=>e.path.localeCompare(t.path));R(e,`${JSON.stringify({version:`v14`,entries:t,output:n,artifacts:[...r].sort(),inputs:a},null,2)}\n`)}function q(e,t,n,i){let a=r(e,t),o=new Set(e.replacements.values());return K(n,i,a,e.manifest.artifacts.map(e=>l.join(t,e.path)),o),a}function J(e){return d(`sha256`).update(`v14`).update(JSON.stringify(e.map(e=>l.resolve(e)))).digest(`hex`).slice(0,16)}function ae(t){let n=e(g);if(!n)throw Error(`Cannot resolve ${g}`);let r=t.map(e=>`() => import(${x(Y(e))})`),i=t.map(e=>x(e));return[`import { withExtensionSource } from ${x(Y(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 Y(e){return l.resolve(e).split(l.sep).join(`/`)}function oe(t,n){return{name:`doom-set-external`,async resolveId(r,i,a){if(r===h)return null;if(k.has(r)||r.startsWith(`node:`))return{id:r,external:!0};if(l.isAbsolute(r)){if(!i&&n&&l.resolve(r)===l.resolve(n))return null;let e=ee(r);return e&&(T.has(e)||D.has(e)||O.has(e))?(t.add(r),{id:r,external:!0}):null}if(r.startsWith(`.`))return null;let o=w(r),s=j(o);if(s&&T.has(s)){let n=e(o);if(n)return t.add(n),{id:n,external:!0}}if(s===`typebox`){let e=E(o);if(e)return t.add(e),{id:e,external:!0}}if(s&&(D.has(s)||O.has(s))){let e=await this.resolve(o,i,a);if(e)return t.add(e.id),{id:e.id,external:!0}}return null}}}function se(e){return{name:`doom-set-inputs`,load(t){return l.isAbsolute(t)&&u.existsSync(t)&&e.add(t),null}}}function ce(e,t,n){t.code===`UNRESOLVED_IMPORT`&&n(`error`,t)}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e,t){if(Array.isArray(e)){for(let n of e)Z(n,t);return}if(!X(e))return;let n=e.object,r=e.property;if(e.type===`MemberExpression`&&e.computed===!1&&typeof e.start==`number`&&typeof e.end==`number`&&X(n)&&n.type===`MetaProperty`&&X(n.meta)&&n.meta.name===`import`&&X(n.property)&&n.property.name===`meta`&&X(r)&&r.name===`url`){t.push({start:e.start,end:e.end});return}for(let n of Object.values(e))Z(n,t)}function le(){return{name:`doom-original-import-meta-url`,transform(e,t){if(!l.isAbsolute(t)||!e.includes(`import.meta.url`))return null;let n=l.extname(t).toLowerCase(),r=n===`.tsx`?`tsx`:n===`.jsx`?`jsx`:C(t)?`ts`:`js`,i=[];if(Z(this.parse(e,{lang:r}),i),i.length===0)return null;let a=x(c(t).href),o=e;for(let e of i.sort((e,t)=>t.start-e.start))o=`${o.slice(0,e.start)}${a}${o.slice(e.end)}`;return o}}}function Q(e,t,n={}){let r=J(e.map(e=>l.resolve(e))),i=l.resolve(n.outputDirectory??l.join(t,m)),a=A(n.outputName??b),o=d(`sha256`).update(i).update(a).digest(`hex`).slice(0,16);return l.join(t,m,`${r}.${o}.json`)}async function $(e,t,r={}){if(e.length===0)throw Error(`Cannot compile an empty extension set`);let o=e.map(e=>l.resolve(e)),s=l.join(t,m);u.mkdirSync(s,{recursive:!0});let c=l.resolve(r.outputDirectory??s),d=A(r.outputName??b);u.mkdirSync(c,{recursive:!0});let f=Q(o,t,r),g=ie(f);if(g&&ne(g,o))return g.output;let _=async()=>{let e=new Set(o),t=ae(o),{rolldown:n}=await import(`rolldown`),r=await n({input:h,platform:`node`,plugins:[{name:`doom-set-entry`,resolveId(e){return e===h?e:null},load(e){return e===h?t:null}},oe(e),le(),se(e)],onLog:ce});try{return{generated:await r.generate(z(`${d}.[hash:16]${p}`)),inputs:e}}finally{await r.close()}},v=r.repositoryRoot?M(r.repositoryRoot):void 0;if(v&&r.sharedCacheDirectory){let e=U(o.map(e=>F(e,v)),d),t=e=>I(e,v);return a(r.sharedCacheDirectory,e,async()=>{let a=n(r.sharedCacheDirectory,e,t);if(a)return q(a,c,f,o);let{generated:s,inputs:l}=await _(),u=W(l,v),d=G(s,u.byTarget);if([...d.values()].some(e=>typeof e==`string`&&e.includes(v)))throw Error(`Shared build graph still contains an absolute worktree path after tokenization`);let p=s.output.find(e=>e.type===`chunk`&&e.isEntry);if(!p)throw Error(`Rolldown produced no shared extension entry`);i({cacheDirectory:r.sharedCacheDirectory,lookupKey:e,entry:p.fileName,inputs:u.shared,artifacts:d});let m=n(r.sharedCacheDirectory,e,t);if(!m)throw Error(`Published shared build could not be verified`);return q(m,c,f,o)})}let{generated:y,inputs:x}=await _(),S=H(y,c);return K(f,o,S.entry,S.artifacts,x),S.entry}export{$ as compileExtensionSet,J as extensionSetKey,Q as extensionSetManifestPath,C as isTypeScriptEntry};
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 './modules/moduleResolution';\nimport {\n contentSha256,\n findSharedBuild,\n materializeSharedBuild,\n publishSharedBuild,\n type ResolvedSharedBuild,\n type SharedBuildInput,\n withSharedBuildLock,\n} from './sharedBuildCache.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 a worktree-local artifact never relies on its\n * generated directory having its own `node_modules` tree. Immutable build objects\n * may be shared by linked worktrees, but materialized output stays worktree-local.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst SET_CACHE_VERSION = 'v14';\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';\nconst SHARED_BUILD_VERSION = 'v3-rolldown-1.2.5';\nconst SHARED_PATH_TOKEN_PREFIX = '__DOOMPI_PATH_';\nconst REPOSITORY_INPUT_PREFIX = 'repo/';\nconst EXTERNAL_INPUT_PREFIX = 'external/';\nconst DEFAULT_SET_OUTPUT_NAME = 'doom-set';\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 * 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 7 exposes version metadata at its top-level entry and keeps its\n // compiler APIs behind unstable native ESM subpaths. Preserve the installed\n // package graph so extensions resolve those entrypoints at runtime.\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 // open 11 resolves its bundled xdg-open helper relative to import.meta.url.\n // Bundling changes that module location and can break helper discovery.\n 'open',\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 worktree artifact directory. Compiler manifests remain local. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n /** Canonical worktree root used to create relocatable logical input paths. */\n repositoryRoot?: string;\n /** Repository-level immutable cache shared by linked worktrees. */\n sharedCacheDirectory?: 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 || DEFAULT_SET_OUTPUT_NAME;\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 let directory = path.dirname(target);\n while (true) {\n const manifestPath = path.join(directory, 'package.json');\n if (fs.existsSync(manifestPath)) {\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown;\n if (isRecord(manifest) && typeof manifest.name === 'string') return manifest.name;\n } catch {\n return undefined;\n }\n }\n const parent = path.dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n\ninterface LogicalInput {\n logicalPath: string;\n target: string;\n sourcePath?: string;\n}\n\nfunction canonicalPath(target: string): string {\n const absolute = path.resolve(target);\n try {\n return fs.realpathSync.native(absolute);\n } catch {\n return absolute;\n }\n}\n\nfunction isInside(directory: string, target: string): boolean {\n const relative = path.relative(path.resolve(directory), path.resolve(target));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\nfunction externalLogicalPath(sourcePath: string): string {\n const identity = createHash('sha256').update(sourcePath).digest('hex');\n return `${EXTERNAL_INPUT_PREFIX}${identity}`;\n}\n\nfunction logicalInput(target: string, repositoryRoot: string): LogicalInput {\n const absolute = canonicalPath(target);\n if (isInside(repositoryRoot, absolute)) {\n return {\n logicalPath: `${REPOSITORY_INPUT_PREFIX}${path.relative(repositoryRoot, absolute).split(path.sep).join('/')}`,\n target: absolute,\n };\n }\n return {\n logicalPath: externalLogicalPath(absolute),\n target: absolute,\n sourcePath: absolute,\n };\n}\n\nfunction resolveLogicalInputPath(input: SharedBuildInput, repositoryRoot: string): string | undefined {\n if (input.logicalPath.startsWith(REPOSITORY_INPUT_PREFIX) && input.sourcePath === undefined) {\n const target = path.resolve(repositoryRoot, input.logicalPath.slice(REPOSITORY_INPUT_PREFIX.length));\n return isInside(repositoryRoot, target) ? target : undefined;\n }\n if (\n input.logicalPath.startsWith(EXTERNAL_INPUT_PREFIX) &&\n input.sourcePath !== undefined &&\n input.logicalPath === externalLogicalPath(input.sourcePath)\n ) {\n return input.sourcePath;\n }\n return undefined;\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\nfunction sharedLookupKey(entries: readonly LogicalInput[], outputName: string): string {\n return createHash('sha256')\n .update(SHARED_BUILD_VERSION)\n .update(process.version)\n .update(process.platform)\n .update(process.arch)\n .update(outputName)\n .update(JSON.stringify(entries.map((entry) => entry.logicalPath)))\n .digest('hex');\n}\n\ninterface TokenizedInputs {\n shared: SharedBuildInput[];\n byTarget: Map<string, string>;\n}\n\nfunction tokenizedInputs(inputs: ReadonlySet<string>, repositoryRoot: string): TokenizedInputs {\n const logical: LogicalInput[] = [];\n for (const target of inputs) logical.push(logicalInput(target, repositoryRoot));\n logical.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath));\n const shared: SharedBuildInput[] = [\n { logicalPath: REPOSITORY_INPUT_PREFIX, sha256: '', token: `${SHARED_PATH_TOKEN_PREFIX}ROOT__` },\n ];\n const byTarget = new Map<string, string>([[repositoryRoot, `${SHARED_PATH_TOKEN_PREFIX}ROOT__`]]);\n const tokenByLogicalPath = new Map<string, string>();\n logical.forEach((input, index) => {\n const existing = tokenByLogicalPath.get(input.logicalPath);\n const token = existing ?? `${SHARED_PATH_TOKEN_PREFIX}${String(index)}__`;\n if (!existing) {\n shared.push({\n logicalPath: input.logicalPath,\n sha256: contentSha256(fs.readFileSync(input.target)),\n token,\n ...(input.sourcePath ? { sourcePath: input.sourcePath } : {}),\n });\n tokenByLogicalPath.set(input.logicalPath, token);\n }\n byTarget.set(path.resolve(input.target), token);\n });\n for (const target of inputs) {\n const input = logicalInput(target, repositoryRoot);\n const token = tokenByLogicalPath.get(input.logicalPath);\n if (token) byTarget.set(path.resolve(target), token);\n }\n return { shared, byTarget };\n}\n\nfunction tokenizedArtifactContents(\n generated: RolldownOutput,\n tokens: ReadonlyMap<string, string>,\n): Map<string, string | Uint8Array> {\n const artifacts = new Map<string, string | Uint8Array>();\n const replacements = [...tokens.entries()].sort(([left], [right]) => right.length - left.length);\n for (const artifact of generated.output) {\n if (artifact.type === 'asset') {\n artifacts.set(artifact.fileName, typeof artifact.source === 'string' ? artifact.source : artifact.source);\n continue;\n }\n let source = artifact.code;\n for (const [target, token] of replacements) {\n source = source\n .replaceAll(pathToFileURL(target).href, `${token}:url`)\n .replaceAll(pathToImportSpecifier(target), token)\n .replaceAll(target, token);\n }\n artifacts.set(artifact.fileName, source);\n }\n return artifacts;\n}\n\nfunction writeLocalSetManifest(\n manifestPath: string,\n entries: string[],\n output: string,\n artifacts: string[],\n inputs: ReadonlySet<string>,\n): void {\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 { version: SET_CACHE_VERSION, entries, output, artifacts: [...artifacts].sort(), inputs: inputFingerprints },\n null,\n 2,\n )}\\n`,\n );\n}\n\nfunction materializeSharedSet(\n build: ResolvedSharedBuild,\n outputDirectory: string,\n manifestPath: string,\n entries: string[],\n): string {\n const output = materializeSharedBuild(build, outputDirectory);\n const inputs = new Set(build.replacements.values());\n const artifacts = build.manifest.artifacts.map((artifact) => path.join(outputDirectory, artifact.path));\n writeLocalSetManifest(manifestPath, entries, output, artifacts, inputs);\n return output;\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>, entry?: 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 if (!importer && entry && path.resolve(specifier) === path.resolve(entry)) return null;\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/** Location of the lightweight input-fingerprint record for one extension set. */\nexport function extensionSetManifestPath(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): string {\n const normalized = entries.map((entry) => path.resolve(entry));\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? path.join(cacheDirectory, SET_DIRECTORY));\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\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 return path.join(cacheDirectory, SET_DIRECTORY, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\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 outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\n fs.mkdirSync(outputDirectory, { recursive: true });\n const manifestPath = extensionSetManifestPath(normalized, cacheDirectory, options);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const generate = async (): Promise<{ generated: RolldownOutput; inputs: Set<string> }> => {\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 try {\n return {\n generated: await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`)),\n inputs,\n };\n } finally {\n await build.close();\n }\n };\n\n const repositoryRoot = options.repositoryRoot ? canonicalPath(options.repositoryRoot) : undefined;\n\n if (repositoryRoot && options.sharedCacheDirectory) {\n const logicalEntries = normalized.map((entry) => logicalInput(entry, repositoryRoot));\n const lookupKey = sharedLookupKey(logicalEntries, outputName);\n const resolveInput = (input: SharedBuildInput): string | undefined =>\n resolveLogicalInputPath(input, repositoryRoot);\n return withSharedBuildLock(options.sharedCacheDirectory, lookupKey, async () => {\n const cached = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (cached) return materializeSharedSet(cached, outputDirectory, manifestPath, normalized);\n\n const { generated, inputs } = await generate();\n const tokenized = tokenizedInputs(inputs, repositoryRoot);\n const artifacts = tokenizedArtifactContents(generated, tokenized.byTarget);\n if (\n [...artifacts.values()].some((contents) => typeof contents === 'string' && contents.includes(repositoryRoot))\n ) {\n throw new Error('Shared build graph still contains an absolute worktree path after tokenization');\n }\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry) throw new Error('Rolldown produced no shared extension entry');\n publishSharedBuild({\n cacheDirectory: options.sharedCacheDirectory as string,\n lookupKey,\n entry: entry.fileName,\n inputs: tokenized.shared,\n artifacts,\n });\n const published = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (!published) throw new Error('Published shared build could not be verified');\n return materializeSharedSet(published, outputDirectory, manifestPath, normalized);\n });\n }\n\n const { generated, inputs } = await generate();\n const compiled = writeCompiledGraph(generated, outputDirectory);\n writeLocalSetManifest(manifestPath, normalized, compiled.entry, compiled.artifacts, inputs);\n return compiled.entry;\n}\n"],"mappings":"iaAmCA,MAAM,EAAsB,CAAC,MAAO,OAAQ,MAAM,EAC5C,EAAkB,OAGlB,EAAgB,OAEhB,EAAoB,yBACpB,EAA0B,qCAE1B,EAA2B,iBAC3B,EAA0B,QAC1B,EAAwB,YACxB,EAA0B,WAG1B,EAAqD,CACzD,gCAAiC,kCACjC,uBAAwB,yBACxB,sBAAuB,wBACvB,oBAAqB,SACvB,EAEA,SAAgB,EAAkB,EAAwB,CACxD,OAAO,EAAoB,KAAM,GAAW,EAAM,SAAS,CAAM,CAAC,CACpE,CAEA,SAAS,EAAY,EAA2B,CAC9C,IAAK,GAAM,CAAC,EAAQ,KAAU,OAAO,QAAQ,C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,SAAW,EAAS,OAAO,EAC/F,GAAI,CAAC,EAAO,MAAU,MAAM,6CAA6C,EACzE,EAAmB,CACjB,eAAgB,EAAQ,qBACxB,YACA,MAAO,EAAM,SACb,OAAQ,EAAU,OAClB,WACF,CAAC,EACD,IAAM,EAAY,EAAgB,EAAQ,qBAAgC,EAAW,CAAY,EACjG,GAAI,CAAC,EAAW,MAAU,MAAM,8CAA8C,EAC9E,OAAO,EAAqB,EAAW,EAAiB,EAAc,CAAU,CAClF,CAAC,CACH,CAEA,GAAM,CAAE,YAAW,UAAW,MAAM,EAAS,EACvC,EAAW,EAAmB,EAAW,CAAe,EAE9D,OADA,EAAsB,EAAc,EAAY,EAAS,MAAO,EAAS,UAAW,CAAM,EACnF,EAAS,KAClB"}
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 './modules/moduleResolution';\nimport {\n contentSha256,\n findSharedBuild,\n materializeSharedBuild,\n publishSharedBuild,\n type ResolvedSharedBuild,\n type SharedBuildInput,\n withSharedBuildLock,\n} from './sharedBuildCache.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 a worktree-local artifact never relies on its\n * generated directory having its own `node_modules` tree. Immutable build objects\n * may be shared by linked worktrees, but materialized output stays worktree-local.\n */\n\nconst TYPESCRIPT_SUFFIXES = ['.ts', '.mts', '.cts'] as const;\nconst COMPILED_SUFFIX = '.mjs';\nconst SET_CACHE_VERSION = 'v14';\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';\nconst SHARED_BUILD_VERSION = 'v3-rolldown-1.2.5';\nconst SHARED_PATH_TOKEN_PREFIX = '__DOOMPI_PATH_';\nconst REPOSITORY_INPUT_PREFIX = 'repo/';\nconst EXTERNAL_INPUT_PREFIX = 'external/';\nconst DEFAULT_SET_OUTPUT_NAME = 'doom-set';\n\n/** Serializes data embedded in generated JavaScript without leaving HTML or line-separator code boundaries. */\nfunction javascriptStringLiteral(value: string): string {\n return JSON.stringify(value)\n .replaceAll('<', '\\\\u003c')\n .replaceAll('\\u2028', '\\\\u2028')\n .replaceAll('\\u2029', '\\\\u2029');\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 * 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 7 exposes version metadata at its top-level entry and keeps its\n // compiler APIs behind unstable native ESM subpaths. Preserve the installed\n // package graph so extensions resolve those entrypoints at runtime.\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 // open 11 resolves its bundled xdg-open helper relative to import.meta.url.\n // Bundling changes that module location and can break helper discovery.\n 'open',\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 worktree artifact directory. Compiler manifests remain local. */\n outputDirectory?: string;\n /** Human-readable artifact prefix, normally the major-mode name. */\n outputName?: string;\n /** Canonical worktree root used to create relocatable logical input paths. */\n repositoryRoot?: string;\n /** Repository-level immutable cache shared by linked worktrees. */\n sharedCacheDirectory?: 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 || DEFAULT_SET_OUTPUT_NAME;\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 let directory = path.dirname(target);\n while (true) {\n const manifestPath = path.join(directory, 'package.json');\n if (fs.existsSync(manifestPath)) {\n try {\n const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as unknown;\n if (isRecord(manifest) && typeof manifest.name === 'string') return manifest.name;\n } catch {\n return undefined;\n }\n }\n const parent = path.dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n\ninterface LogicalInput {\n logicalPath: string;\n target: string;\n sourcePath?: string;\n}\n\nfunction canonicalPath(target: string): string {\n const absolute = path.resolve(target);\n try {\n return fs.realpathSync.native(absolute);\n } catch {\n return absolute;\n }\n}\n\nfunction isInside(directory: string, target: string): boolean {\n const relative = path.relative(path.resolve(directory), path.resolve(target));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\nfunction externalLogicalPath(sourcePath: string): string {\n const identity = createHash('sha256').update(sourcePath).digest('hex');\n return `${EXTERNAL_INPUT_PREFIX}${identity}`;\n}\n\nfunction logicalInput(target: string, repositoryRoot: string): LogicalInput {\n const absolute = canonicalPath(target);\n if (isInside(repositoryRoot, absolute)) {\n return {\n logicalPath: `${REPOSITORY_INPUT_PREFIX}${path.relative(repositoryRoot, absolute).split(path.sep).join('/')}`,\n target: absolute,\n };\n }\n return {\n logicalPath: externalLogicalPath(absolute),\n target: absolute,\n sourcePath: absolute,\n };\n}\n\nfunction resolveLogicalInputPath(input: SharedBuildInput, repositoryRoot: string): string | undefined {\n if (input.logicalPath.startsWith(REPOSITORY_INPUT_PREFIX) && input.sourcePath === undefined) {\n const target = path.resolve(repositoryRoot, input.logicalPath.slice(REPOSITORY_INPUT_PREFIX.length));\n return isInside(repositoryRoot, target) ? target : undefined;\n }\n if (\n input.logicalPath.startsWith(EXTERNAL_INPUT_PREFIX) &&\n input.sourcePath !== undefined &&\n input.logicalPath === externalLogicalPath(input.sourcePath)\n ) {\n return input.sourcePath;\n }\n return undefined;\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\nfunction sharedLookupKey(entries: readonly LogicalInput[], outputName: string): string {\n return createHash('sha256')\n .update(SHARED_BUILD_VERSION)\n .update(process.version)\n .update(process.platform)\n .update(process.arch)\n .update(outputName)\n .update(JSON.stringify(entries.map((entry) => entry.logicalPath)))\n .digest('hex');\n}\n\ninterface TokenizedInputs {\n shared: SharedBuildInput[];\n byTarget: Map<string, string>;\n}\n\nfunction tokenizedInputs(inputs: ReadonlySet<string>, repositoryRoot: string): TokenizedInputs {\n const logical: LogicalInput[] = [];\n for (const target of inputs) logical.push(logicalInput(target, repositoryRoot));\n logical.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath));\n const shared: SharedBuildInput[] = [\n { logicalPath: REPOSITORY_INPUT_PREFIX, sha256: '', token: `${SHARED_PATH_TOKEN_PREFIX}ROOT__` },\n ];\n const byTarget = new Map<string, string>([[repositoryRoot, `${SHARED_PATH_TOKEN_PREFIX}ROOT__`]]);\n const tokenByLogicalPath = new Map<string, string>();\n logical.forEach((input, index) => {\n const existing = tokenByLogicalPath.get(input.logicalPath);\n const token = existing ?? `${SHARED_PATH_TOKEN_PREFIX}${String(index)}__`;\n if (!existing) {\n shared.push({\n logicalPath: input.logicalPath,\n sha256: contentSha256(fs.readFileSync(input.target)),\n token,\n ...(input.sourcePath ? { sourcePath: input.sourcePath } : {}),\n });\n tokenByLogicalPath.set(input.logicalPath, token);\n }\n byTarget.set(path.resolve(input.target), token);\n });\n for (const target of inputs) {\n const input = logicalInput(target, repositoryRoot);\n const token = tokenByLogicalPath.get(input.logicalPath);\n if (token) byTarget.set(path.resolve(target), token);\n }\n return { shared, byTarget };\n}\n\nfunction tokenizedArtifactContents(\n generated: RolldownOutput,\n tokens: ReadonlyMap<string, string>,\n): Map<string, string | Uint8Array> {\n const artifacts = new Map<string, string | Uint8Array>();\n const replacements = [...tokens.entries()].sort(([left], [right]) => right.length - left.length);\n for (const artifact of generated.output) {\n if (artifact.type === 'asset') {\n artifacts.set(artifact.fileName, typeof artifact.source === 'string' ? artifact.source : artifact.source);\n continue;\n }\n let source = artifact.code;\n for (const [target, token] of replacements) {\n source = source\n .replaceAll(pathToFileURL(target).href, `${token}:url`)\n .replaceAll(pathToImportSpecifier(target), token)\n .replaceAll(target, token);\n }\n artifacts.set(artifact.fileName, source);\n }\n return artifacts;\n}\n\nfunction writeLocalSetManifest(\n manifestPath: string,\n entries: string[],\n output: string,\n artifacts: string[],\n inputs: ReadonlySet<string>,\n): void {\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 { version: SET_CACHE_VERSION, entries, output, artifacts: [...artifacts].sort(), inputs: inputFingerprints },\n null,\n 2,\n )}\\n`,\n );\n}\n\nfunction materializeSharedSet(\n build: ResolvedSharedBuild,\n outputDirectory: string,\n manifestPath: string,\n entries: string[],\n): string {\n const output = materializeSharedBuild(build, outputDirectory);\n const inputs = new Set(build.replacements.values());\n const artifacts = build.manifest.artifacts.map((artifact) => path.join(outputDirectory, artifact.path));\n writeLocalSetManifest(manifestPath, entries, output, artifacts, inputs);\n return output;\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(${javascriptStringLiteral(pathToImportSpecifier(entry))})`);\n const names = entries.map((entry) => javascriptStringLiteral(entry));\n return [\n `import { withExtensionSource } from ${javascriptStringLiteral(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>, entry?: 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 if (!importer && entry && path.resolve(specifier) === path.resolve(entry)) return null;\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 = javascriptStringLiteral(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/** Location of the lightweight input-fingerprint record for one extension set. */\nexport function extensionSetManifestPath(\n entries: readonly string[],\n cacheDirectory: string,\n options: CompileExtensionSetOptions = {},\n): string {\n const normalized = entries.map((entry) => path.resolve(entry));\n const key = extensionSetKey(normalized);\n const outputDirectory = path.resolve(options.outputDirectory ?? path.join(cacheDirectory, SET_DIRECTORY));\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\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 return path.join(cacheDirectory, SET_DIRECTORY, `${key}.${outputKey}${MANIFEST_SUFFIX}`);\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 outputDirectory = path.resolve(options.outputDirectory ?? setDirectory);\n const outputName = safeOutputName(options.outputName ?? DEFAULT_SET_OUTPUT_NAME);\n fs.mkdirSync(outputDirectory, { recursive: true });\n const manifestPath = extensionSetManifestPath(normalized, cacheDirectory, options);\n const previous = readSetManifest(manifestPath);\n if (previous && manifestIsFresh(previous, normalized)) return previous.output;\n\n const generate = async (): Promise<{ generated: RolldownOutput; inputs: Set<string> }> => {\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 try {\n return {\n generated: await build.generate(splitOutputOptions(`${outputName}.[hash:${HASH_LENGTH}]${COMPILED_SUFFIX}`)),\n inputs,\n };\n } finally {\n await build.close();\n }\n };\n\n const repositoryRoot = options.repositoryRoot ? canonicalPath(options.repositoryRoot) : undefined;\n\n if (repositoryRoot && options.sharedCacheDirectory) {\n const logicalEntries = normalized.map((entry) => logicalInput(entry, repositoryRoot));\n const lookupKey = sharedLookupKey(logicalEntries, outputName);\n const resolveInput = (input: SharedBuildInput): string | undefined =>\n resolveLogicalInputPath(input, repositoryRoot);\n return withSharedBuildLock(options.sharedCacheDirectory, lookupKey, async () => {\n const cached = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (cached) return materializeSharedSet(cached, outputDirectory, manifestPath, normalized);\n\n const { generated, inputs } = await generate();\n const tokenized = tokenizedInputs(inputs, repositoryRoot);\n const artifacts = tokenizedArtifactContents(generated, tokenized.byTarget);\n if (\n [...artifacts.values()].some((contents) => typeof contents === 'string' && contents.includes(repositoryRoot))\n ) {\n throw new Error('Shared build graph still contains an absolute worktree path after tokenization');\n }\n const entry = generated.output.find((artifact) => artifact.type === 'chunk' && artifact.isEntry);\n if (!entry) throw new Error('Rolldown produced no shared extension entry');\n publishSharedBuild({\n cacheDirectory: options.sharedCacheDirectory as string,\n lookupKey,\n entry: entry.fileName,\n inputs: tokenized.shared,\n artifacts,\n });\n const published = findSharedBuild(options.sharedCacheDirectory as string, lookupKey, resolveInput);\n if (!published) throw new Error('Published shared build could not be verified');\n return materializeSharedSet(published, outputDirectory, manifestPath, normalized);\n });\n }\n\n const { generated, inputs } = await generate();\n const compiled = writeCompiledGraph(generated, outputDirectory);\n writeLocalSetManifest(manifestPath, normalized, compiled.entry, compiled.artifacts, inputs);\n return compiled.entry;\n}\n"],"mappings":"iaAmCA,MAAM,E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EAAa,EAAO,CAAc,CACpC,EAAG,CAAU,EACtD,EAAgB,GACpB,EAAwB,EAAO,CAAc,EAC/C,OAAO,EAAoB,EAAQ,qBAAsB,EAAW,SAAY,CAC9E,IAAM,EAAS,EAAgB,EAAQ,qBAAgC,EAAW,CAAY,EAC9F,GAAI,EAAQ,OAAO,EAAqB,EAAQ,EAAiB,EAAc,CAAU,EAEzF,GAAM,CAAE,YAAW,UAAW,MAAM,EAAS,EACvC,EAAY,EAAgB,EAAQ,CAAc,EAClD,EAAY,EAA0B,EAAW,EAAU,QAAQ,EACzE,GACE,CAAC,GAAG,EAAU,OAAO,CAAC,CAAC,CAAC,KAAM,GAAa,OAAO,GAAa,UAAY,EAAS,SAAS,CAAc,CAAC,EAE5G,MAAU,MAAM,gFAAgF,EAElG,IAAM,EAAQ,EAAU,OAAO,KAAM,GAAa,EAAS,OAAS,SAAW,EAAS,OAAO,EAC/F,GAAI,CAAC,EAAO,MAAU,MAAM,6CAA6C,EACzE,EAAmB,CACjB,eAAgB,EAAQ,qBACxB,YACA,MAAO,EAAM,SACb,OAAQ,EAAU,OAClB,WACF,CAAC,EACD,IAAM,EAAY,EAAgB,EAAQ,qBAAgC,EAAW,CAAY,EACjG,GAAI,CAAC,EAAW,MAAU,MAAM,8CAA8C,EAC9E,OAAO,EAAqB,EAAW,EAAiB,EAAc,CAAU,CAClF,CAAC,CACH,CAEA,GAAM,CAAE,YAAW,UAAW,MAAM,EAAS,EACvC,EAAW,EAAmB,EAAW,CAAe,EAE9D,OADA,EAAsB,EAAc,EAAY,EAAS,MAAO,EAAS,UAAW,CAAM,EACnF,EAAS,KAClB"}
@@ -1,2 +1,2 @@
1
- const e={cliFailed:`doom_pi.cli_failed`,contextBuildFailed:`doom_pi.context_build_failed`,resourceCollectionFailed:`doom_pi.resource_collection_failed`,configLoadFailed:`doom_pi.config_load_failed`,launchFailed:`doom_pi.launch_failed`,compatibilityLaunchFailed:`doom_pi.compatibility_launch_failed`,harnessStateParseFailed:`doom_pi.harness_state_parse_failed`,hookFailed:`doom_pi.hook_failed`,hookRegistryReadFailed:`doom_pi.hook_registry_read_failed`,personaReadFailed:`doom_pi.persona_read_failed`,styleSystemRenderFailed:`doom_pi.style_system_render_failed`,majorModeUnavailable:`doom_pi.major_mode_unavailable`,profileLoadFailed:`doom_pi.profile_load_failed`,launchCompleted:`doom_pi.launch_completed`,projectTrustResolved:`doom_pi.project_trust_resolved`,majorModeSwitched:`doom_pi.major_mode_switched`,profileApplied:`doom_pi.profile_applied`};function t(e={}){let t,n=[],r=()=>(t??=import(`@agimon-ai/doompi-telemetry`).then(({createDoomTelemetry:t})=>t({serviceName:`doom-pi`,packageName:`@agimon-ai/doompi`,cwd:e.cwd,workspaceRoot:e.workspaceRoot,env:e.env,telemetryFactory:e.telemetryFactory,warn:e.warn,enableLogs:!0,enableTraces:!0})),t),i=async e=>{for(let t of n.splice(0))await e.recordEvent(t.event,t.attributes)};return{recordError:async(e,t,n)=>{let a=await r();await i(a),await a.recordError(e,t,n)},recordWarning:async(e,t,n)=>{let a=await r();await i(a),await a.recordWarning(e,t,n)},recordEvent:async(i,a)=>{if(e.deferSpans&&!t){n.push({event:i,attributes:a});return}await(await r()).recordEvent(i,a)},runInSpan:(n,i,a)=>e.deferSpans&&!t?a():r().then(e=>e.runInSpan(n,i,a)),flush:async()=>{if(!t&&n.length===0)return;let e=await r();await i(e),await e.flush()},shutdown:async()=>{if(!t&&n.length===0)return;let e=await r();await i(e),await e.shutdown()}}}function n(e){return{error:(t,n,r)=>void e.recordError(t,n,r),warn:(t,n,r)=>void e.recordWarning(t,n,r)}}exports.HARNESS_EVENT=e,exports.createHarnessTelemetry=t,exports.toFailureReporter=n;
1
+ const e={cliFailed:`doom_pi.cli_failed`,contextBuildFailed:`doom_pi.context_build_failed`,resourceCollectionFailed:`doom_pi.resource_collection_failed`,configLoadFailed:`doom_pi.config_load_failed`,launchFailed:`doom_pi.launch_failed`,compatibilityLaunchFailed:`doom_pi.compatibility_launch_failed`,harnessStateParseFailed:`doom_pi.harness_state_parse_failed`,hookFailed:`doom_pi.hook_failed`,hookRegistryReadFailed:`doom_pi.hook_registry_read_failed`,personaReadFailed:`doom_pi.persona_read_failed`,styleSystemRenderFailed:`doom_pi.style_system_render_failed`,majorModeUnavailable:`doom_pi.major_mode_unavailable`,profileLoadFailed:`doom_pi.profile_load_failed`,launchCompleted:`doom_pi.launch_completed`,projectTrustResolved:`doom_pi.project_trust_resolved`,majorModeSwitched:`doom_pi.major_mode_switched`,profileApplied:`doom_pi.profile_applied`};function t(e={}){let t,n=[],r=!1,i=()=>(t??=import(`@agimon-ai/doompi-telemetry`).then(({createDoomTelemetry:t})=>t({serviceName:`doom-pi`,packageName:`@agimon-ai/doompi`,cwd:e.cwd,workspaceRoot:e.workspaceRoot,env:e.env,telemetryFactory:e.telemetryFactory,warn:e.warn,enableLogs:!0,enableTraces:!0})),t),a=async e=>{for(let t of n.splice(0))await e.recordEvent(t.event,t.attributes)};return{recordError:async(e,t,n)=>{let r=await i();await a(r),await r.recordError(e,t,n)},recordWarning:async(e,t,n)=>{let r=await i();await a(r),await r.recordWarning(e,t,n)},recordEvent:async(a,o)=>{if(e.deferSpans&&!t){if(n.length<64)n.push({event:a,attributes:o});else if(!r){r=!0;try{(e.warn??(e=>process.emitWarning(e)))(`Doom telemetry deferred event limit reached; later events were dropped.`)}catch{}}return}await(await i()).recordEvent(a,o)},runInSpan:(n,r,a)=>e.deferSpans&&!t?a():i().then(e=>e.runInSpan(n,r,a)),flush:async()=>{if(!t&&n.length===0)return;let e=await i();await a(e),await e.flush()},shutdown:async()=>{if(!t&&n.length===0)return;let e=await i();await a(e),await e.shutdown()}}}function n(e){return{error:(t,n,r)=>void e.recordError(t,n,r),warn:(t,n,r)=>void e.recordWarning(t,n,r)}}exports.HARNESS_EVENT=e,exports.createHarnessTelemetry=t,exports.toFailureReporter=n;
2
2
  //# sourceMappingURL=logSinkTelemetry.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"logSinkTelemetry.cjs","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"sourcesContent":["import type { DoomTelemetry, DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nconst SERVICE_NAME = 'doom-pi';\nconst PACKAGE_NAME = '@agimon-ai/doompi';\n\nexport const HARNESS_EVENT = {\n cliFailed: 'doom_pi.cli_failed',\n contextBuildFailed: 'doom_pi.context_build_failed',\n resourceCollectionFailed: 'doom_pi.resource_collection_failed',\n configLoadFailed: 'doom_pi.config_load_failed',\n launchFailed: 'doom_pi.launch_failed',\n compatibilityLaunchFailed: 'doom_pi.compatibility_launch_failed',\n harnessStateParseFailed: 'doom_pi.harness_state_parse_failed',\n hookFailed: 'doom_pi.hook_failed',\n hookRegistryReadFailed: 'doom_pi.hook_registry_read_failed',\n personaReadFailed: 'doom_pi.persona_read_failed',\n styleSystemRenderFailed: 'doom_pi.style_system_render_failed',\n majorModeUnavailable: 'doom_pi.major_mode_unavailable',\n profileLoadFailed: 'doom_pi.profile_load_failed',\n launchCompleted: 'doom_pi.launch_completed',\n projectTrustResolved: 'doom_pi.project_trust_resolved',\n majorModeSwitched: 'doom_pi.major_mode_switched',\n profileApplied: 'doom_pi.profile_applied',\n} as const;\n\nexport type HarnessEventName = (typeof HARNESS_EVENT)[keyof typeof HARNESS_EVENT];\nexport type HarnessEventAttributes = Record<string, string | number | boolean>;\nexport type HarnessErrorSink = (event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes) => void;\n\nexport interface HarnessFailureReporter {\n error: HarnessErrorSink;\n warn: HarnessErrorSink;\n}\n\nexport interface HarnessTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n /** Run startup callbacks before loading the telemetry backend. */\n deferSpans?: boolean;\n}\n\nexport interface HarnessTelemetry {\n recordError(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordWarning(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordEvent(event: HarnessEventName, attributes?: HarnessEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: HarnessEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createHarnessTelemetry(options: HarnessTelemetryOptions = {}): HarnessTelemetry {\n let telemetryPromise: Promise<DoomTelemetry> | undefined;\n const pendingEvents: Array<{ event: HarnessEventName; attributes?: HarnessEventAttributes }> = [];\n const telemetry = (): Promise<DoomTelemetry> => {\n telemetryPromise ??= import('@agimon-ai/doompi-telemetry').then(({ createDoomTelemetry }) =>\n createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n }),\n );\n return telemetryPromise;\n };\n const drainEvents = async (loaded: DoomTelemetry): Promise<void> => {\n for (const pending of pendingEvents.splice(0)) {\n await loaded.recordEvent(pending.event, pending.attributes);\n }\n };\n return {\n recordError: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordError(event, error, attributes);\n },\n recordWarning: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordWarning(event, error, attributes);\n },\n recordEvent: async (event, attributes) => {\n if (options.deferSpans && !telemetryPromise) {\n pendingEvents.push({ event, attributes });\n return;\n }\n await (await telemetry()).recordEvent(event, attributes);\n },\n runInSpan: (name, attributes, callback) => {\n // The launcher opts into this path for pre-spawn preparation. Lifecycle\n // events remain buffered until flush; failures still initialize the real\n // sink immediately so diagnostics are not lost.\n if (options.deferSpans && !telemetryPromise) return callback();\n return telemetry().then((loaded) => loaded.runInSpan(name, attributes, callback));\n },\n flush: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.flush();\n },\n shutdown: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.shutdown();\n },\n };\n}\n\nexport function toFailureReporter(telemetry: HarnessTelemetry): HarnessFailureReporter {\n return {\n error: (event, error, attributes) => void telemetry.recordError(event, error, attributes),\n warn: (event, error, attributes) => void telemetry.recordWarning(event, error, attributes),\n };\n}\n"],"mappings":"AAEA,MAGa,EAAgB,CAC3B,UAAW,qBACX,mBAAoB,+BACpB,yBAA0B,qCAC1B,iBAAkB,6BAClB,aAAc,wBACd,0BAA2B,sCAC3B,wBAAyB,qCACzB,WAAY,sBACZ,uBAAwB,oCACxB,kBAAmB,8BACnB,wBAAyB,qCACzB,qBAAsB,iCACtB,kBAAmB,8BACnB,gBAAiB,2BACjB,qBAAsB,iCACtB,kBAAmB,8BACnB,eAAgB,yBAClB,EA8BA,SAAgB,EAAuB,EAAmC,CAAC,EAAqB,CAC9F,IAAI,EACE,EAAyF,CAAC,EAC1F,OACJ,IAAqB,OAAO,8BAA8B,CAAC,MAAM,CAAE,yBACjE,EAAoB,CAClB,YAAa,UACb,YAAa,oBACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,EAChB,CAAC,CACH,EACO,GAEH,EAAc,KAAO,IAAyC,CAClE,IAAK,IAAM,KAAW,EAAc,OAAO,CAAC,EAC1C,MAAM,EAAO,YAAY,EAAQ,MAAO,EAAQ,UAAU,CAE9D,EACA,MAAO,CACL,YAAa,MAAO,EAAO,EAAO,IAAe,CAC/C,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,YAAY,EAAO,EAAO,CAAU,CACnD,EACA,cAAe,MAAO,EAAO,EAAO,IAAe,CACjD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,cAAc,EAAO,EAAO,CAAU,CACrD,EACA,YAAa,MAAO,EAAO,IAAe,CACxC,GAAI,EAAQ,YAAc,CAAC,EAAkB,CAC3C,EAAc,KAAK,CAAE,QAAO,YAAW,CAAC,EACxC,MACF,CACA,MAAO,MAAM,EAAU,EAAA,CAAG,YAAY,EAAO,CAAU,CACzD,EACA,WAAY,EAAM,EAAY,IAIxB,EAAQ,YAAc,CAAC,EAAyB,EAAS,EACtD,EAAU,CAAC,CAAC,KAAM,GAAW,EAAO,UAAU,EAAM,EAAY,CAAQ,CAAC,EAElF,MAAO,SAAY,CACjB,GAAI,CAAC,GAAoB,EAAc,SAAW,EAAG,OACrD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,MAAM,CACrB,EACA,SAAU,SAAY,CACpB,GAAI,CAAC,GAAoB,EAAc,SAAW,EAAG,OACrD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,SAAS,CACxB,CACF,CACF,CAEA,SAAgB,EAAkB,EAAqD,CACrF,MAAO,CACL,OAAQ,EAAO,EAAO,IAAe,KAAK,EAAU,YAAY,EAAO,EAAO,CAAU,EACxF,MAAO,EAAO,EAAO,IAAe,KAAK,EAAU,cAAc,EAAO,EAAO,CAAU,CAC3F,CACF"}
1
+ {"version":3,"file":"logSinkTelemetry.cjs","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"sourcesContent":["import type { DoomTelemetry, DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nconst MAX_PENDING_EVENTS = 64;\nconst SERVICE_NAME = 'doom-pi';\nconst PACKAGE_NAME = '@agimon-ai/doompi';\n\nexport const HARNESS_EVENT = {\n cliFailed: 'doom_pi.cli_failed',\n contextBuildFailed: 'doom_pi.context_build_failed',\n resourceCollectionFailed: 'doom_pi.resource_collection_failed',\n configLoadFailed: 'doom_pi.config_load_failed',\n launchFailed: 'doom_pi.launch_failed',\n compatibilityLaunchFailed: 'doom_pi.compatibility_launch_failed',\n harnessStateParseFailed: 'doom_pi.harness_state_parse_failed',\n hookFailed: 'doom_pi.hook_failed',\n hookRegistryReadFailed: 'doom_pi.hook_registry_read_failed',\n personaReadFailed: 'doom_pi.persona_read_failed',\n styleSystemRenderFailed: 'doom_pi.style_system_render_failed',\n majorModeUnavailable: 'doom_pi.major_mode_unavailable',\n profileLoadFailed: 'doom_pi.profile_load_failed',\n launchCompleted: 'doom_pi.launch_completed',\n projectTrustResolved: 'doom_pi.project_trust_resolved',\n majorModeSwitched: 'doom_pi.major_mode_switched',\n profileApplied: 'doom_pi.profile_applied',\n} as const;\n\nexport type HarnessEventName = (typeof HARNESS_EVENT)[keyof typeof HARNESS_EVENT];\nexport type HarnessEventAttributes = Record<string, string | number | boolean>;\nexport type HarnessErrorSink = (event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes) => void;\n\nexport interface HarnessFailureReporter {\n error: HarnessErrorSink;\n warn: HarnessErrorSink;\n}\n\nexport interface HarnessTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n /** Run startup callbacks before loading the telemetry backend. */\n deferSpans?: boolean;\n}\n\nexport interface HarnessTelemetry {\n recordError(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordWarning(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordEvent(event: HarnessEventName, attributes?: HarnessEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: HarnessEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createHarnessTelemetry(options: HarnessTelemetryOptions = {}): HarnessTelemetry {\n let telemetryPromise: Promise<DoomTelemetry> | undefined;\n const pendingEvents: Array<{ event: HarnessEventName; attributes?: HarnessEventAttributes }> = [];\n let pendingEventDropReported = false;\n const telemetry = (): Promise<DoomTelemetry> => {\n telemetryPromise ??= import('@agimon-ai/doompi-telemetry').then(({ createDoomTelemetry }) =>\n createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n }),\n );\n return telemetryPromise;\n };\n const drainEvents = async (loaded: DoomTelemetry): Promise<void> => {\n for (const pending of pendingEvents.splice(0)) {\n await loaded.recordEvent(pending.event, pending.attributes);\n }\n };\n return {\n recordError: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordError(event, error, attributes);\n },\n recordWarning: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordWarning(event, error, attributes);\n },\n recordEvent: async (event, attributes) => {\n if (options.deferSpans && !telemetryPromise) {\n if (pendingEvents.length < MAX_PENDING_EVENTS) pendingEvents.push({ event, attributes });\n else if (!pendingEventDropReported) {\n pendingEventDropReported = true;\n try {\n const reportWarning = options.warn ?? ((message: string) => process.emitWarning(message));\n reportWarning('Doom telemetry deferred event limit reached; later events were dropped.');\n } catch {\n // Telemetry warnings must not interrupt launcher startup.\n }\n }\n return;\n }\n await (await telemetry()).recordEvent(event, attributes);\n },\n runInSpan: (name, attributes, callback) => {\n // The launcher opts into this path for pre-spawn preparation. Lifecycle\n // events remain buffered until flush; failures still initialize the real\n // sink immediately so diagnostics are not lost.\n if (options.deferSpans && !telemetryPromise) return callback();\n return telemetry().then((loaded) => loaded.runInSpan(name, attributes, callback));\n },\n flush: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.flush();\n },\n shutdown: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.shutdown();\n },\n };\n}\n\nexport function toFailureReporter(telemetry: HarnessTelemetry): HarnessFailureReporter {\n return {\n error: (event, error, attributes) => void telemetry.recordError(event, error, attributes),\n warn: (event, error, attributes) => void telemetry.recordWarning(event, error, attributes),\n };\n}\n"],"mappings":"AAEA,MAIa,EAAgB,CAC3B,UAAW,qBACX,mBAAoB,+BACpB,yBAA0B,qCAC1B,iBAAkB,6BAClB,aAAc,wBACd,0BAA2B,sCAC3B,wBAAyB,qCACzB,WAAY,sBACZ,uBAAwB,oCACxB,kBAAmB,8BACnB,wBAAyB,qCACzB,qBAAsB,iCACtB,kBAAmB,8BACnB,gBAAiB,2BACjB,qBAAsB,iCACtB,kBAAmB,8BACnB,eAAgB,yBAClB,EA8BA,SAAgB,EAAuB,EAAmC,CAAC,EAAqB,CAC9F,IAAI,EACE,EAAyF,CAAC,EAC5F,EAA2B,GACzB,OACJ,IAAqB,OAAO,8BAA8B,CAAC,MAAM,CAAE,yBACjE,EAAoB,CAClB,YAAa,UACb,YAAa,oBACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,EAChB,CAAC,CACH,EACO,GAEH,EAAc,KAAO,IAAyC,CAClE,IAAK,IAAM,KAAW,EAAc,OAAO,CAAC,EAC1C,MAAM,EAAO,YAAY,EAAQ,MAAO,EAAQ,UAAU,CAE9D,EACA,MAAO,CACL,YAAa,MAAO,EAAO,EAAO,IAAe,CAC/C,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,YAAY,EAAO,EAAO,CAAU,CACnD,EACA,cAAe,MAAO,EAAO,EAAO,IAAe,CACjD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,cAAc,EAAO,EAAO,CAAU,CACrD,EACA,YAAa,MAAO,EAAO,IAAe,CACxC,GAAI,EAAQ,YAAc,CAAC,EAAkB,CAC3C,GAAI,EAAc,OAAS,GAAoB,EAAc,KAAK,CAAE,QAAO,YAAW,CAAC,OAClF,GAAI,CAAC,EAA0B,CAClC,EAA2B,GAC3B,GAAI,EACoB,EAAQ,OAAU,GAAoB,QAAQ,YAAY,CAAO,GAAA,CACzE,yEAAyE,CACzF,MAAQ,CAER,CACF,CACA,MACF,CACA,MAAO,MAAM,EAAU,EAAA,CAAG,YAAY,EAAO,CAAU,CACzD,EACA,WAAY,EAAM,EAAY,IAIxB,EAAQ,YAAc,CAAC,EAAyB,EAAS,EACtD,EAAU,CAAC,CAAC,KAAM,GAAW,EAAO,UAAU,EAAM,EAAY,CAAQ,CAAC,EAElF,MAAO,SAAY,CACjB,GAAI,CAAC,GAAoB,EAAc,SAAW,EAAG,OACrD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,MAAM,CACrB,EACA,SAAU,SAAY,CACpB,GAAI,CAAC,GAAoB,EAAc,SAAW,EAAG,OACrD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,SAAS,CACxB,CACF,CACF,CAEA,SAAgB,EAAkB,EAAqD,CACrF,MAAO,CACL,OAAQ,EAAO,EAAO,IAAe,KAAK,EAAU,YAAY,EAAO,EAAO,CAAU,EACxF,MAAO,EAAO,EAAO,IAAe,KAAK,EAAU,cAAc,EAAO,EAAO,CAAU,CAC3F,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"logSinkTelemetry.d.cts","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"mappings":";;cAKa;WACX;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;KAGU,2BAA2B,4BAA4B;KACvD,yBAAyB;KACzB,oBAAoB,OAAO,kBAAkB,gBAAgB,aAAa;UAErE;EACf,OAAO;EACP,MAAM;;UAGS;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;EAER;;UAGe;EACf,YAAY,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC3F,cAAc,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC7F,YAAY,OAAO,kBAAkB,aAAa,yBAAyB;EAC3E,UAAU,GAAG,cAAc,YAAY,wBAAwB,gBAAgB,QAAQ,KAAK,QAAQ;EACpG,SAAS;EACT,YAAY;;iBAGE,uBAAuB,UAAS,0BAA+B;iBAgE/D,kBAAkB,WAAW,mBAAmB"}
1
+ {"version":3,"file":"logSinkTelemetry.d.cts","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"mappings":";;cAMa;WACX;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;KAGU,2BAA2B,4BAA4B;KACvD,yBAAyB;KACzB,oBAAoB,OAAO,kBAAkB,gBAAgB,aAAa;UAErE;EACf,OAAO;EACP,MAAM;;UAGS;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;EAER;;UAGe;EACf,YAAY,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC3F,cAAc,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC7F,YAAY,OAAO,kBAAkB,aAAa,yBAAyB;EAC3E,UAAU,GAAG,cAAc,YAAY,wBAAwB,gBAAgB,QAAQ,KAAK,QAAQ;EACpG,SAAS;EACT,YAAY;;iBAGE,uBAAuB,UAAS,0BAA+B;iBA0E/D,kBAAkB,WAAW,mBAAmB"}
@@ -1 +1 @@
1
- {"version":3,"file":"logSinkTelemetry.d.mts","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"mappings":";;cAKa;WACX;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;KAGU,2BAA2B,4BAA4B;KACvD,yBAAyB;KACzB,oBAAoB,OAAO,kBAAkB,gBAAgB,aAAa;UAErE;EACf,OAAO;EACP,MAAM;;UAGS;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;EAER;;UAGe;EACf,YAAY,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC3F,cAAc,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC7F,YAAY,OAAO,kBAAkB,aAAa,yBAAyB;EAC3E,UAAU,GAAG,cAAc,YAAY,wBAAwB,gBAAgB,QAAQ,KAAK,QAAQ;EACpG,SAAS;EACT,YAAY;;iBAGE,uBAAuB,UAAS,0BAA+B;iBAgE/D,kBAAkB,WAAW,mBAAmB"}
1
+ {"version":3,"file":"logSinkTelemetry.d.mts","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"mappings":";;cAMa;WACX;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;KAGU,2BAA2B,4BAA4B;KACvD,yBAAyB;KACzB,oBAAoB,OAAO,kBAAkB,gBAAgB,aAAa;UAErE;EACf,OAAO;EACP,MAAM;;UAGS;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;EAER;;UAGe;EACf,YAAY,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC3F,cAAc,OAAO,kBAAkB,gBAAgB,aAAa,yBAAyB;EAC7F,YAAY,OAAO,kBAAkB,aAAa,yBAAyB;EAC3E,UAAU,GAAG,cAAc,YAAY,wBAAwB,gBAAgB,QAAQ,KAAK,QAAQ;EACpG,SAAS;EACT,YAAY;;iBAGE,uBAAuB,UAAS,0BAA+B;iBA0E/D,kBAAkB,WAAW,mBAAmB"}
@@ -1,2 +1,2 @@
1
- const e={cliFailed:`doom_pi.cli_failed`,contextBuildFailed:`doom_pi.context_build_failed`,resourceCollectionFailed:`doom_pi.resource_collection_failed`,configLoadFailed:`doom_pi.config_load_failed`,launchFailed:`doom_pi.launch_failed`,compatibilityLaunchFailed:`doom_pi.compatibility_launch_failed`,harnessStateParseFailed:`doom_pi.harness_state_parse_failed`,hookFailed:`doom_pi.hook_failed`,hookRegistryReadFailed:`doom_pi.hook_registry_read_failed`,personaReadFailed:`doom_pi.persona_read_failed`,styleSystemRenderFailed:`doom_pi.style_system_render_failed`,majorModeUnavailable:`doom_pi.major_mode_unavailable`,profileLoadFailed:`doom_pi.profile_load_failed`,launchCompleted:`doom_pi.launch_completed`,projectTrustResolved:`doom_pi.project_trust_resolved`,majorModeSwitched:`doom_pi.major_mode_switched`,profileApplied:`doom_pi.profile_applied`};function t(e={}){let t,n=[],r=()=>(t??=import(`@agimon-ai/doompi-telemetry`).then(({createDoomTelemetry:t})=>t({serviceName:`doom-pi`,packageName:`@agimon-ai/doompi`,cwd:e.cwd,workspaceRoot:e.workspaceRoot,env:e.env,telemetryFactory:e.telemetryFactory,warn:e.warn,enableLogs:!0,enableTraces:!0})),t),i=async e=>{for(let t of n.splice(0))await e.recordEvent(t.event,t.attributes)};return{recordError:async(e,t,n)=>{let a=await r();await i(a),await a.recordError(e,t,n)},recordWarning:async(e,t,n)=>{let a=await r();await i(a),await a.recordWarning(e,t,n)},recordEvent:async(i,a)=>{if(e.deferSpans&&!t){n.push({event:i,attributes:a});return}await(await r()).recordEvent(i,a)},runInSpan:(n,i,a)=>e.deferSpans&&!t?a():r().then(e=>e.runInSpan(n,i,a)),flush:async()=>{if(!t&&n.length===0)return;let e=await r();await i(e),await e.flush()},shutdown:async()=>{if(!t&&n.length===0)return;let e=await r();await i(e),await e.shutdown()}}}function n(e){return{error:(t,n,r)=>void e.recordError(t,n,r),warn:(t,n,r)=>void e.recordWarning(t,n,r)}}export{e as HARNESS_EVENT,t as createHarnessTelemetry,n as toFailureReporter};
1
+ const e={cliFailed:`doom_pi.cli_failed`,contextBuildFailed:`doom_pi.context_build_failed`,resourceCollectionFailed:`doom_pi.resource_collection_failed`,configLoadFailed:`doom_pi.config_load_failed`,launchFailed:`doom_pi.launch_failed`,compatibilityLaunchFailed:`doom_pi.compatibility_launch_failed`,harnessStateParseFailed:`doom_pi.harness_state_parse_failed`,hookFailed:`doom_pi.hook_failed`,hookRegistryReadFailed:`doom_pi.hook_registry_read_failed`,personaReadFailed:`doom_pi.persona_read_failed`,styleSystemRenderFailed:`doom_pi.style_system_render_failed`,majorModeUnavailable:`doom_pi.major_mode_unavailable`,profileLoadFailed:`doom_pi.profile_load_failed`,launchCompleted:`doom_pi.launch_completed`,projectTrustResolved:`doom_pi.project_trust_resolved`,majorModeSwitched:`doom_pi.major_mode_switched`,profileApplied:`doom_pi.profile_applied`};function t(e={}){let t,n=[],r=!1,i=()=>(t??=import(`@agimon-ai/doompi-telemetry`).then(({createDoomTelemetry:t})=>t({serviceName:`doom-pi`,packageName:`@agimon-ai/doompi`,cwd:e.cwd,workspaceRoot:e.workspaceRoot,env:e.env,telemetryFactory:e.telemetryFactory,warn:e.warn,enableLogs:!0,enableTraces:!0})),t),a=async e=>{for(let t of n.splice(0))await e.recordEvent(t.event,t.attributes)};return{recordError:async(e,t,n)=>{let r=await i();await a(r),await r.recordError(e,t,n)},recordWarning:async(e,t,n)=>{let r=await i();await a(r),await r.recordWarning(e,t,n)},recordEvent:async(a,o)=>{if(e.deferSpans&&!t){if(n.length<64)n.push({event:a,attributes:o});else if(!r){r=!0;try{(e.warn??(e=>process.emitWarning(e)))(`Doom telemetry deferred event limit reached; later events were dropped.`)}catch{}}return}await(await i()).recordEvent(a,o)},runInSpan:(n,r,a)=>e.deferSpans&&!t?a():i().then(e=>e.runInSpan(n,r,a)),flush:async()=>{if(!t&&n.length===0)return;let e=await i();await a(e),await e.flush()},shutdown:async()=>{if(!t&&n.length===0)return;let e=await i();await a(e),await e.shutdown()}}}function n(e){return{error:(t,n,r)=>void e.recordError(t,n,r),warn:(t,n,r)=>void e.recordWarning(t,n,r)}}export{e as HARNESS_EVENT,t as createHarnessTelemetry,n as toFailureReporter};
2
2
  //# sourceMappingURL=logSinkTelemetry.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"logSinkTelemetry.mjs","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"sourcesContent":["import type { DoomTelemetry, DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nconst SERVICE_NAME = 'doom-pi';\nconst PACKAGE_NAME = '@agimon-ai/doompi';\n\nexport const HARNESS_EVENT = {\n cliFailed: 'doom_pi.cli_failed',\n contextBuildFailed: 'doom_pi.context_build_failed',\n resourceCollectionFailed: 'doom_pi.resource_collection_failed',\n configLoadFailed: 'doom_pi.config_load_failed',\n launchFailed: 'doom_pi.launch_failed',\n compatibilityLaunchFailed: 'doom_pi.compatibility_launch_failed',\n harnessStateParseFailed: 'doom_pi.harness_state_parse_failed',\n hookFailed: 'doom_pi.hook_failed',\n hookRegistryReadFailed: 'doom_pi.hook_registry_read_failed',\n personaReadFailed: 'doom_pi.persona_read_failed',\n styleSystemRenderFailed: 'doom_pi.style_system_render_failed',\n majorModeUnavailable: 'doom_pi.major_mode_unavailable',\n profileLoadFailed: 'doom_pi.profile_load_failed',\n launchCompleted: 'doom_pi.launch_completed',\n projectTrustResolved: 'doom_pi.project_trust_resolved',\n majorModeSwitched: 'doom_pi.major_mode_switched',\n profileApplied: 'doom_pi.profile_applied',\n} as const;\n\nexport type HarnessEventName = (typeof HARNESS_EVENT)[keyof typeof HARNESS_EVENT];\nexport type HarnessEventAttributes = Record<string, string | number | boolean>;\nexport type HarnessErrorSink = (event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes) => void;\n\nexport interface HarnessFailureReporter {\n error: HarnessErrorSink;\n warn: HarnessErrorSink;\n}\n\nexport interface HarnessTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n /** Run startup callbacks before loading the telemetry backend. */\n deferSpans?: boolean;\n}\n\nexport interface HarnessTelemetry {\n recordError(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordWarning(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordEvent(event: HarnessEventName, attributes?: HarnessEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: HarnessEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createHarnessTelemetry(options: HarnessTelemetryOptions = {}): HarnessTelemetry {\n let telemetryPromise: Promise<DoomTelemetry> | undefined;\n const pendingEvents: Array<{ event: HarnessEventName; attributes?: HarnessEventAttributes }> = [];\n const telemetry = (): Promise<DoomTelemetry> => {\n telemetryPromise ??= import('@agimon-ai/doompi-telemetry').then(({ createDoomTelemetry }) =>\n createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n }),\n );\n return telemetryPromise;\n };\n const drainEvents = async (loaded: DoomTelemetry): Promise<void> => {\n for (const pending of pendingEvents.splice(0)) {\n await loaded.recordEvent(pending.event, pending.attributes);\n }\n };\n return {\n recordError: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordError(event, error, attributes);\n },\n recordWarning: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordWarning(event, error, attributes);\n },\n recordEvent: async (event, attributes) => {\n if (options.deferSpans && !telemetryPromise) {\n pendingEvents.push({ event, attributes });\n return;\n }\n await (await telemetry()).recordEvent(event, attributes);\n },\n runInSpan: (name, attributes, callback) => {\n // The launcher opts into this path for pre-spawn preparation. Lifecycle\n // events remain buffered until flush; failures still initialize the real\n // sink immediately so diagnostics are not lost.\n if (options.deferSpans && !telemetryPromise) return callback();\n return telemetry().then((loaded) => loaded.runInSpan(name, attributes, callback));\n },\n flush: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.flush();\n },\n shutdown: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.shutdown();\n },\n };\n}\n\nexport function toFailureReporter(telemetry: HarnessTelemetry): HarnessFailureReporter {\n return {\n error: (event, error, attributes) => void telemetry.recordError(event, error, attributes),\n warn: (event, error, attributes) => void telemetry.recordWarning(event, error, attributes),\n };\n}\n"],"mappings":"AAEA,MAGa,EAAgB,CAC3B,UAAW,qBACX,mBAAoB,+BACpB,yBAA0B,qCAC1B,iBAAkB,6BAClB,aAAc,wBACd,0BAA2B,sCAC3B,wBAAyB,qCACzB,WAAY,sBACZ,uBAAwB,oCACxB,kBAAmB,8BACnB,wBAAyB,qCACzB,qBAAsB,iCACtB,kBAAmB,8BACnB,gBAAiB,2BACjB,qBAAsB,iCACtB,kBAAmB,8BACnB,eAAgB,yBAClB,EA8BA,SAAgB,EAAuB,EAAmC,CAAC,EAAqB,CAC9F,IAAI,EACE,EAAyF,CAAC,EAC1F,OACJ,IAAqB,OAAO,8BAA8B,CAAC,MAAM,CAAE,yBACjE,EAAoB,CAClB,YAAa,UACb,YAAa,oBACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,EAChB,CAAC,CACH,EACO,GAEH,EAAc,KAAO,IAAyC,CAClE,IAAK,IAAM,KAAW,EAAc,OAAO,CAAC,EAC1C,MAAM,EAAO,YAAY,EAAQ,MAAO,EAAQ,UAAU,CAE9D,EACA,MAAO,CACL,YAAa,MAAO,EAAO,EAAO,IAAe,CAC/C,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,YAAY,EAAO,EAAO,CAAU,CACnD,EACA,cAAe,MAAO,EAAO,EAAO,IAAe,CACjD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,cAAc,EAAO,EAAO,CAAU,CACrD,EACA,YAAa,MAAO,EAAO,IAAe,CACxC,GAAI,EAAQ,YAAc,CAAC,EAAkB,CAC3C,EAAc,KAAK,CAAE,QAAO,YAAW,CAAC,EACxC,MACF,CACA,MAAO,MAAM,EAAU,EAAA,CAAG,YAAY,EAAO,CAAU,CACzD,EACA,WAAY,EAAM,EAAY,IAIxB,EAAQ,YAAc,CAAC,EAAyB,EAAS,EACtD,EAAU,CAAC,CAAC,KAAM,GAAW,EAAO,UAAU,EAAM,EAAY,CAAQ,CAAC,EAElF,MAAO,SAAY,CACjB,GAAI,CAAC,GAAoB,EAAc,SAAW,EAAG,OACrD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,MAAM,CACrB,EACA,SAAU,SAAY,CACpB,GAAI,CAAC,GAAoB,EAAc,SAAW,EAAG,OACrD,IAAM,EAAS,MAAM,EAAU,EAC/B,MAAM,EAAY,CAAM,EACxB,MAAM,EAAO,SAAS,CACxB,CACF,CACF,CAEA,SAAgB,EAAkB,EAAqD,CACrF,MAAO,CACL,OAAQ,EAAO,EAAO,IAAe,KAAK,EAAU,YAAY,EAAO,EAAO,CAAU,EACxF,MAAO,EAAO,EAAO,IAAe,KAAK,EAAU,cAAc,EAAO,EAAO,CAAU,CAC3F,CACF"}
1
+ {"version":3,"file":"logSinkTelemetry.mjs","names":[],"sources":["../../../../src/adapters/telemetry/logSinkTelemetry.ts"],"sourcesContent":["import type { DoomTelemetry, DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nconst MAX_PENDING_EVENTS = 64;\nconst SERVICE_NAME = 'doom-pi';\nconst PACKAGE_NAME = '@agimon-ai/doompi';\n\nexport const HARNESS_EVENT = {\n cliFailed: 'doom_pi.cli_failed',\n contextBuildFailed: 'doom_pi.context_build_failed',\n resourceCollectionFailed: 'doom_pi.resource_collection_failed',\n configLoadFailed: 'doom_pi.config_load_failed',\n launchFailed: 'doom_pi.launch_failed',\n compatibilityLaunchFailed: 'doom_pi.compatibility_launch_failed',\n harnessStateParseFailed: 'doom_pi.harness_state_parse_failed',\n hookFailed: 'doom_pi.hook_failed',\n hookRegistryReadFailed: 'doom_pi.hook_registry_read_failed',\n personaReadFailed: 'doom_pi.persona_read_failed',\n styleSystemRenderFailed: 'doom_pi.style_system_render_failed',\n majorModeUnavailable: 'doom_pi.major_mode_unavailable',\n profileLoadFailed: 'doom_pi.profile_load_failed',\n launchCompleted: 'doom_pi.launch_completed',\n projectTrustResolved: 'doom_pi.project_trust_resolved',\n majorModeSwitched: 'doom_pi.major_mode_switched',\n profileApplied: 'doom_pi.profile_applied',\n} as const;\n\nexport type HarnessEventName = (typeof HARNESS_EVENT)[keyof typeof HARNESS_EVENT];\nexport type HarnessEventAttributes = Record<string, string | number | boolean>;\nexport type HarnessErrorSink = (event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes) => void;\n\nexport interface HarnessFailureReporter {\n error: HarnessErrorSink;\n warn: HarnessErrorSink;\n}\n\nexport interface HarnessTelemetryOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n /** Run startup callbacks before loading the telemetry backend. */\n deferSpans?: boolean;\n}\n\nexport interface HarnessTelemetry {\n recordError(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordWarning(event: HarnessEventName, error: unknown, attributes?: HarnessEventAttributes): Promise<void>;\n recordEvent(event: HarnessEventName, attributes?: HarnessEventAttributes): Promise<void>;\n runInSpan<T>(name: string, attributes: HarnessEventAttributes, callback: () => Promise<T>): Promise<T>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createHarnessTelemetry(options: HarnessTelemetryOptions = {}): HarnessTelemetry {\n let telemetryPromise: Promise<DoomTelemetry> | undefined;\n const pendingEvents: Array<{ event: HarnessEventName; attributes?: HarnessEventAttributes }> = [];\n let pendingEventDropReported = false;\n const telemetry = (): Promise<DoomTelemetry> => {\n telemetryPromise ??= import('@agimon-ai/doompi-telemetry').then(({ createDoomTelemetry }) =>\n createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n }),\n );\n return telemetryPromise;\n };\n const drainEvents = async (loaded: DoomTelemetry): Promise<void> => {\n for (const pending of pendingEvents.splice(0)) {\n await loaded.recordEvent(pending.event, pending.attributes);\n }\n };\n return {\n recordError: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordError(event, error, attributes);\n },\n recordWarning: async (event, error, attributes) => {\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.recordWarning(event, error, attributes);\n },\n recordEvent: async (event, attributes) => {\n if (options.deferSpans && !telemetryPromise) {\n if (pendingEvents.length < MAX_PENDING_EVENTS) pendingEvents.push({ event, attributes });\n else if (!pendingEventDropReported) {\n pendingEventDropReported = true;\n try {\n const reportWarning = options.warn ?? ((message: string) => process.emitWarning(message));\n reportWarning('Doom telemetry deferred event limit reached; later events were dropped.');\n } catch {\n // Telemetry warnings must not interrupt launcher startup.\n }\n }\n return;\n }\n await (await telemetry()).recordEvent(event, attributes);\n },\n runInSpan: (name, attributes, callback) => {\n // The launcher opts into this path for pre-spawn preparation. Lifecycle\n // events remain buffered until flush; failures still initialize the real\n // sink immediately so diagnostics are not lost.\n if (options.deferSpans && !telemetryPromise) return callback();\n return telemetry().then((loaded) => loaded.runInSpan(name, attributes, callback));\n },\n flush: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.flush();\n },\n shutdown: async () => {\n if (!telemetryPromise && pendingEvents.length === 0) return;\n const loaded = await telemetry();\n await drainEvents(loaded);\n await loaded.shutdown();\n },\n };\n}\n\nexport function toFailureReporter(telemetry: HarnessTelemetry): HarnessFailureReporter {\n return {\n error: (event, error, attributes) => void telemetry.recordError(event, error, attributes),\n warn: (event, error, attributes) => void telemetry.recordWarning(event, error, attributes),\n };\n}\n"],"mappings":"AAEA,MAIa,EAAgB,CAC3B,UAAW,qBACX,mBAAoB,+BACpB,yBAA0B,qCAC1B,iBAAkB,6BAClB,aAAc,wBACd,0BAA2B,sCAC3B,wBAAyB,qCACzB,WAAY,sBACZ,uBAAwB,oCACxB,kBAAmB,8BACnB,wBAAyB,qCACzB,qBAAsB,iCACtB,kBAAmB,8BACnB,gBAAiB,2BACjB,qBAAsB,iCACtB,kBAAmB,8BACnB,eAAgB,yBAClB,EA8BA,SAAgB,EAAuB,EAAmC,CAAC,EAAqB,CAC9F,IAAI,EACE,EAAyF,CAAC,EAC5F,EAA2B,GACzB,OACJ,IAAqB,OAAO,8BAA8B,CAAC,MAAM,CAAE,yBACjE,EAAoB,CAClB,YAAa,UACb,YAAa,oBACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,EAChB,CAAC,CACH,EACO,GAEH,EAAc,KAAO,IAAyC,CAClE,IAAK,IAAM,KAAW,EAAc,OAAO,CAAC,EAC1C,MAAM,EAAO,YAAY,EAAQ,MAAO,EAAQ,UAAU,CAE9D,EACA,MAAO,CACL,YAAa,MAAO,EAAO,EAAO,IAAe,CAC/C,IAAM,EAAS,MAAM,EAAU,EAC/B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/minorModeProjection.cjs"),n=require("./minorModeCommand.cjs");let r=require("@agimon-ai/doompi-extension-contracts/cordis-host"),i=require("@agimon-ai/doompi-extension-contracts/mode"),a=require("@agimon-ai/doompi-extension-contracts/help"),o=require("@agimon-ai/doompi-extension-contracts/transition");function s(e){return e.includes(`voice`)?`voice`:e.includes(`leader`)?`leader`:e.includes(`ui`)?`ui`:`system`}async function c(e){let t={current:void 0};n.registerMinorModeCommand(e,()=>t.current),e.on(`session_start`,()=>{setTimeout(()=>t.republish?.(),500)});let i=await(0,r.connectDoomCordisHost)(e,`@agimon-ai/doompi/mode-catalog`),a=i.root.plugin(n=>{l(n,e,t)});try{await a}catch(e){throw await a.dispose(),await i.dispose(),e}let o;e.on(`session_shutdown`,()=>o??=(async()=>{try{await a.dispose()}finally{await i.dispose()}})())}function l(n,c,l){n.inject([a.DOOM_HELP_SERVICE],e=>{let t=(0,a.requireDoomHelpService)(e).register({source:`@agimon-ai/doompi`,moduleUrl:require("url").pathToFileURL(__filename).href,skills:[{name:`doompi-author-extension`,description:`Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.`}]});return()=>t.dispose()}),n.inject([r.DOOM_CORDIS_SESSION_SERVICE,o.DOOM_TRANSITION_SERVICE],n=>{let a=n.get(r.DOOM_CORDIS_SESSION_SERVICE),u=a.context,d=(0,o.requireDoomTransitionCoordinator)(n),f=a.reason===`reload`,p=a.sessionId,m=f?(0,o.consumeMinorModeReloadHandoff)(p):void 0;f||(0,o.discardMinorModeReloadHandoff)(p);let h=u.hasUI&&u.mode===`tui`?`tui`:`headless`,g=e.createMinorModeCatalogHost({sessionKind:h,context:u,restoreSnapshot:m,onRestorationError(e){u.ui.notify(`Could not restore a minor mode after reload: ${e instanceof Error?e.message:String(e)}`,`warning`)},async routeInvocation(e,t,n){let r,i=await d.execute({sessionId:u.sessionManager.getSessionId(),hostGeneration:d.hostGeneration,operationId:e.operationId,source:s(t),target:{axis:`minor-mode`,action:e,requesterSource:t}},async()=>(r=await n(),`applied`));if(i.outcome!==`applied`||!r)throw Error(`Minor-mode transition was ${i.outcome}: ${i.diagnostics.join(`, `)}`);return r}});n.provide(i.DOOM_MINOR_MODE_CATALOG_SERVICE,g),l.current=g;let _,v,y=()=>{v=void 0;let e=t.projectMinorModes(g.getSnapshot(),h),n=JSON.stringify(e);n!==_&&(_=n,c.appendEntry(i.DOOM_MINOR_MODE_ENTRY_TYPE,e))},b=g.subscribe(()=>{v??=setTimeout(y,50)});return l.republish=()=>{_=void 0,y()},()=>{v&&clearTimeout(v),b(),l.republish=void 0,l.current=void 0,g.dispose()}})}exports.default=c,exports.modeCatalogExtension=c;
1
+ const e=require("../../services/modeCatalog.cjs"),t=require("../../services/minorModeProjection.cjs"),n=require("./minorModeCommand.cjs");let r=require("@agimon-ai/doompi-extension-contracts/cordis-host"),i=require("@agimon-ai/doompi-extension-contracts/mode"),a=require("@agimon-ai/doompi-extension-contracts/help"),o=require("@agimon-ai/doompi-extension-contracts/notification"),s=require("@agimon-ai/doompi-extension-contracts/transition");function c(e,t,n,r){let i=(0,o.readDoomNotificationService)(e);if(i){try{Promise.resolve(i.request({body:n,level:r})).catch(()=>void 0)}catch{}return}t.ui.notify(n,r)}function l(e){return e.includes(`voice`)?`voice`:e.includes(`leader`)?`leader`:e.includes(`ui`)?`ui`:`system`}async function u(e){let t={current:void 0};n.registerMinorModeCommand(e,()=>t.current),e.on(`session_start`,()=>{setTimeout(()=>t.republish?.(),500)});let i=await(0,r.connectDoomCordisHost)(e,`@agimon-ai/doompi/mode-catalog`),a=i.root.plugin(n=>{d(n,e,t)});try{await a}catch(e){throw await a.dispose(),await i.dispose(),e}let o;e.on(`session_shutdown`,()=>o??=(async()=>{try{await a.dispose()}finally{await i.dispose()}})())}function d(n,o,u){n.inject([a.DOOM_HELP_SERVICE],e=>{let t=(0,a.requireDoomHelpService)(e).register({source:`@agimon-ai/doompi`,moduleUrl:require("url").pathToFileURL(__filename).href,skills:[{name:`doompi-author-extension`,description:`Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.`}]});return()=>t.dispose()}),n.inject([r.DOOM_CORDIS_SESSION_SERVICE,s.DOOM_TRANSITION_SERVICE],n=>{let a=n.get(r.DOOM_CORDIS_SESSION_SERVICE),d=a.context,f=(0,s.requireDoomTransitionCoordinator)(n),p=a.reason===`reload`,m=a.sessionId,h=p?(0,s.consumeMinorModeReloadHandoff)(m):void 0;p||(0,s.discardMinorModeReloadHandoff)(m);let g=d.hasUI&&d.mode===`tui`?`tui`:`headless`,_=e.createMinorModeCatalogHost({sessionKind:g,context:d,restoreSnapshot:h,onRestorationError(e){c(n,d,`Could not restore a minor mode after reload: ${e instanceof Error?e.message:String(e)}`,`warning`)},async routeInvocation(e,t,n){let r,i=await f.execute({sessionId:d.sessionManager.getSessionId(),hostGeneration:f.hostGeneration,operationId:e.operationId,source:l(t),target:{axis:`minor-mode`,action:e,requesterSource:t}},async()=>(r=await n(),`applied`));if(i.outcome!==`applied`||!r)throw Error(`Minor-mode transition was ${i.outcome}: ${i.diagnostics.join(`, `)}`);return r}});n.provide(i.DOOM_MINOR_MODE_CATALOG_SERVICE,_),u.current=_;let v,y,b=()=>{y=void 0;let e=t.projectMinorModes(_.getSnapshot(),g),n=JSON.stringify(e);n!==v&&(v=n,o.appendEntry(i.DOOM_MINOR_MODE_ENTRY_TYPE,e))},x=_.subscribe(()=>{y??=setTimeout(b,50)});return u.republish=()=>{v=void 0,b()},()=>{y&&clearTimeout(y),x(),u.republish=void 0,u.current=void 0,_.dispose()}})}exports.default=u,exports.modeCatalogExtension=u;
2
2
  //# sourceMappingURL=modeCatalog.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"modeCatalog.cjs","names":["connectDoomCordisHost","DOOM_HELP_SERVICE","requireDoomHelpService","DOOM_CORDIS_SESSION_SERVICE","DOOM_TRANSITION_SERVICE","requireDoomTransitionCoordinator","consumeMinorModeReloadHandoff","createMinorModeCatalogHost","DOOM_MINOR_MODE_CATALOG_SERVICE","projectMinorModes","DOOM_MINOR_MODE_ENTRY_TYPE"],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"sourcesContent":["import {\n DOOM_MINOR_MODE_CATALOG_SERVICE,\n DOOM_MINOR_MODE_ENTRY_TYPE,\n type MinorModeActionResponse,\n type MinorModeCatalogService,\n} from '@agimon-ai/doompi-extension-contracts/mode';\nimport {\n connectDoomCordisHost,\n DOOM_CORDIS_SESSION_SERVICE,\n type DoomCordisSessionService,\n} from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { DOOM_HELP_SERVICE, requireDoomHelpService } from '@agimon-ai/doompi-extension-contracts/help';\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport {\n consumeMinorModeReloadHandoff,\n discardMinorModeReloadHandoff,\n type MinorModeCatalogHost,\n DOOM_TRANSITION_SERVICE,\n requireDoomTransitionCoordinator,\n type TransitionSource,\n} from '@agimon-ai/doompi-extension-contracts/transition';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { projectMinorModes } from '../../services/minorModeProjection.ts';\nimport { createMinorModeCatalogHost } from '../../services/modeCatalog.ts';\nimport { registerMinorModeCommand } from './minorModeCommand.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi/mode-catalog';\nconst HELP_CONTRIBUTION_SOURCE = '@agimon-ai/doompi';\n/** Registrations and state flips arrive in bursts; one entry covers a burst. */\nconst PROJECTION_SETTLE_MS = 50;\n/**\n * Pi's rpc mode subscribes to session events only after bindExtensions()\n * returns, which is after session_start has run, so an entry journaled during\n * startup never reaches a client. A publish deferred past that point does.\n */\nconst BOOT_PUBLISH_DELAY_MS = 500;\n\ninterface CatalogBinding {\n current: MinorModeCatalogService | undefined;\n /** Journals the projection even if unchanged; set while a session is bound. */\n republish?: () => void;\n}\n\nfunction transitionSource(requesterSource: string): TransitionSource {\n if (requesterSource.includes('voice')) return 'voice';\n if (requesterSource.includes('leader')) return 'leader';\n if (requesterSource.includes('ui')) return 'ui';\n return 'system';\n}\n\nexport async function modeCatalogExtension(pi: ExtensionAPI): Promise<void> {\n // The command outlives any one session: it is registered once and reads the\n // catalog binding the session-scoped inject below sets and clears.\n const activeCatalog: CatalogBinding = { current: undefined };\n registerMinorModeCommand(pi, () => activeCatalog.current);\n pi.on('session_start', () => {\n setTimeout(() => activeCatalog.republish?.(), BOOT_PUBLISH_DELAY_MS);\n });\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin((cordis: Context) => {\n modeCatalogPlugin(cordis, pi, activeCatalog);\n });\n try {\n await fiber;\n } catch (error) {\n await fiber.dispose();\n await connection.dispose();\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\nfunction modeCatalogPlugin(\n cordis: Context,\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n activeCatalog: CatalogBinding,\n): void {\n cordis.inject([DOOM_HELP_SERVICE], (helpContext) => {\n const contribution = requireDoomHelpService(helpContext).register({\n source: HELP_CONTRIBUTION_SOURCE,\n moduleUrl: import.meta.url,\n skills: [\n {\n name: 'doompi-author-extension',\n description:\n 'Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.',\n },\n ],\n });\n return () => contribution.dispose();\n });\n\n cordis.inject([DOOM_CORDIS_SESSION_SERVICE, DOOM_TRANSITION_SERVICE], (sessionContext) => {\n const session = sessionContext.get(DOOM_CORDIS_SESSION_SERVICE) as DoomCordisSessionService;\n const context = session.context;\n const coordinator = requireDoomTransitionCoordinator(sessionContext);\n const reloadSession = session.reason === 'reload';\n const sessionId = session.sessionId;\n const restoreSnapshot = reloadSession ? consumeMinorModeReloadHandoff(sessionId) : undefined;\n if (!reloadSession) discardMinorModeReloadHandoff(sessionId);\n const sessionKind = context.hasUI && context.mode === 'tui' ? 'tui' : 'headless';\n const catalog: MinorModeCatalogHost = createMinorModeCatalogHost({\n sessionKind,\n context,\n restoreSnapshot,\n onRestorationError(error) {\n context.ui.notify(\n `Could not restore a minor mode after reload: ${error instanceof Error ? error.message : String(error)}`,\n 'warning',\n );\n },\n async routeInvocation(request, requesterSource, invoke) {\n let response: MinorModeActionResponse | undefined;\n const result = await coordinator.execute(\n {\n sessionId: context.sessionManager.getSessionId(),\n hostGeneration: coordinator.hostGeneration,\n operationId: request.operationId,\n source: transitionSource(requesterSource),\n target: { axis: 'minor-mode', action: request, requesterSource },\n },\n async () => {\n response = await invoke();\n return 'applied';\n },\n );\n if (result.outcome !== 'applied' || !response) {\n throw new Error(`Minor-mode transition was ${result.outcome}: ${result.diagnostics.join(', ')}`);\n }\n return response;\n },\n });\n sessionContext.provide(DOOM_MINOR_MODE_CATALOG_SERVICE, catalog);\n activeCatalog.current = catalog;\n\n // Journal the projection so RPC clients see catalog state live and on\n // replay; identical projections are skipped so detail churn stays cheap.\n let published: string | undefined;\n let settle: NodeJS.Timeout | undefined;\n const publish = (): void => {\n settle = undefined;\n const projection = projectMinorModes(catalog.getSnapshot(), sessionKind);\n const serialized = JSON.stringify(projection);\n if (serialized === published) return;\n published = serialized;\n pi.appendEntry(DOOM_MINOR_MODE_ENTRY_TYPE, projection);\n };\n const unsubscribe = catalog.subscribe(() => {\n settle ??= setTimeout(publish, PROJECTION_SETTLE_MS);\n });\n activeCatalog.republish = () => {\n published = undefined;\n publish();\n };\n\n return () => {\n if (settle) clearTimeout(settle);\n unsubscribe();\n activeCatalog.republish = undefined;\n activeCatalog.current = undefined;\n catalog.dispose();\n };\n });\n}\n\nexport default modeCatalogExtension;\n"],"mappings":"2XA2CA,SAAS,EAAiB,EAA2C,CAInE,OAHI,EAAgB,SAAS,OAAO,EAAU,QAC1C,EAAgB,SAAS,QAAQ,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CAClB,CACF,CAAC,CACH"}
1
+ {"version":3,"file":"modeCatalog.cjs","names":["readDoomNotificationService","connectDoomCordisHost","DOOM_HELP_SERVICE","requireDoomHelpService","DOOM_CORDIS_SESSION_SERVICE","DOOM_TRANSITION_SERVICE","requireDoomTransitionCoordinator","consumeMinorModeReloadHandoff","createMinorModeCatalogHost","DOOM_MINOR_MODE_CATALOG_SERVICE","projectMinorModes","DOOM_MINOR_MODE_ENTRY_TYPE"],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"sourcesContent":["import {\n DOOM_MINOR_MODE_CATALOG_SERVICE,\n DOOM_MINOR_MODE_ENTRY_TYPE,\n type MinorModeActionResponse,\n type MinorModeCatalogService,\n} from '@agimon-ai/doompi-extension-contracts/mode';\nimport {\n connectDoomCordisHost,\n DOOM_CORDIS_SESSION_SERVICE,\n type DoomCordisSessionService,\n} from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { DOOM_HELP_SERVICE, requireDoomHelpService } from '@agimon-ai/doompi-extension-contracts/help';\nimport {\n type DoomNotificationLevel,\n readDoomNotificationService,\n} from '@agimon-ai/doompi-extension-contracts/notification';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport {\n consumeMinorModeReloadHandoff,\n discardMinorModeReloadHandoff,\n type MinorModeCatalogHost,\n DOOM_TRANSITION_SERVICE,\n requireDoomTransitionCoordinator,\n type TransitionSource,\n} from '@agimon-ai/doompi-extension-contracts/transition';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { projectMinorModes } from '../../services/minorModeProjection.ts';\nimport { createMinorModeCatalogHost } from '../../services/modeCatalog.ts';\nimport { registerMinorModeCommand } from './minorModeCommand.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi/mode-catalog';\nconst HELP_CONTRIBUTION_SOURCE = '@agimon-ai/doompi';\n/** Registrations and state flips arrive in bursts; one entry covers a burst. */\nconst PROJECTION_SETTLE_MS = 50;\n/**\n * Pi's rpc mode subscribes to session events only after bindExtensions()\n * returns, which is after session_start has run, so an entry journaled during\n * startup never reaches a client. A publish deferred past that point does.\n */\nconst BOOT_PUBLISH_DELAY_MS = 500;\n\ninterface CatalogBinding {\n current: MinorModeCatalogService | undefined;\n /** Journals the projection even if unchanged; set while a session is bound. */\n republish?: () => void;\n}\n\nfunction notify(cordis: Context, context: ExtensionContext, body: string, level: DoomNotificationLevel): void {\n const service = readDoomNotificationService(cordis);\n if (service) {\n try {\n void Promise.resolve(service.request({ body, level })).catch(() => undefined);\n } catch {\n // Notification delivery is best effort and does not fall back after routing.\n }\n return;\n }\n context.ui.notify(body, level);\n}\n\nfunction transitionSource(requesterSource: string): TransitionSource {\n if (requesterSource.includes('voice')) return 'voice';\n if (requesterSource.includes('leader')) return 'leader';\n if (requesterSource.includes('ui')) return 'ui';\n return 'system';\n}\n\nexport async function modeCatalogExtension(pi: ExtensionAPI): Promise<void> {\n // The command outlives any one session: it is registered once and reads the\n // catalog binding the session-scoped inject below sets and clears.\n const activeCatalog: CatalogBinding = { current: undefined };\n registerMinorModeCommand(pi, () => activeCatalog.current);\n pi.on('session_start', () => {\n setTimeout(() => activeCatalog.republish?.(), BOOT_PUBLISH_DELAY_MS);\n });\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin((cordis: Context) => {\n modeCatalogPlugin(cordis, pi, activeCatalog);\n });\n try {\n await fiber;\n } catch (error) {\n await fiber.dispose();\n await connection.dispose();\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\nfunction modeCatalogPlugin(\n cordis: Context,\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n activeCatalog: CatalogBinding,\n): void {\n cordis.inject([DOOM_HELP_SERVICE], (helpContext) => {\n const contribution = requireDoomHelpService(helpContext).register({\n source: HELP_CONTRIBUTION_SOURCE,\n moduleUrl: import.meta.url,\n skills: [\n {\n name: 'doompi-author-extension',\n description:\n 'Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.',\n },\n ],\n });\n return () => contribution.dispose();\n });\n\n cordis.inject([DOOM_CORDIS_SESSION_SERVICE, DOOM_TRANSITION_SERVICE], (sessionContext) => {\n const session = sessionContext.get(DOOM_CORDIS_SESSION_SERVICE) as DoomCordisSessionService;\n const context = session.context;\n const coordinator = requireDoomTransitionCoordinator(sessionContext);\n const reloadSession = session.reason === 'reload';\n const sessionId = session.sessionId;\n const restoreSnapshot = reloadSession ? consumeMinorModeReloadHandoff(sessionId) : undefined;\n if (!reloadSession) discardMinorModeReloadHandoff(sessionId);\n const sessionKind = context.hasUI && context.mode === 'tui' ? 'tui' : 'headless';\n const catalog: MinorModeCatalogHost = createMinorModeCatalogHost({\n sessionKind,\n context,\n restoreSnapshot,\n onRestorationError(error) {\n notify(\n sessionContext,\n context,\n `Could not restore a minor mode after reload: ${error instanceof Error ? error.message : String(error)}`,\n 'warning',\n );\n },\n async routeInvocation(request, requesterSource, invoke) {\n let response: MinorModeActionResponse | undefined;\n const result = await coordinator.execute(\n {\n sessionId: context.sessionManager.getSessionId(),\n hostGeneration: coordinator.hostGeneration,\n operationId: request.operationId,\n source: transitionSource(requesterSource),\n target: { axis: 'minor-mode', action: request, requesterSource },\n },\n async () => {\n response = await invoke();\n return 'applied';\n },\n );\n if (result.outcome !== 'applied' || !response) {\n throw new Error(`Minor-mode transition was ${result.outcome}: ${result.diagnostics.join(', ')}`);\n }\n return response;\n },\n });\n sessionContext.provide(DOOM_MINOR_MODE_CATALOG_SERVICE, catalog);\n activeCatalog.current = catalog;\n\n // Journal the projection so RPC clients see catalog state live and on\n // replay; identical projections are skipped so detail churn stays cheap.\n let published: string | undefined;\n let settle: NodeJS.Timeout | undefined;\n const publish = (): void => {\n settle = undefined;\n const projection = projectMinorModes(catalog.getSnapshot(), sessionKind);\n const serialized = JSON.stringify(projection);\n if (serialized === published) return;\n published = serialized;\n pi.appendEntry(DOOM_MINOR_MODE_ENTRY_TYPE, projection);\n };\n const unsubscribe = catalog.subscribe(() => {\n settle ??= setTimeout(publish, PROJECTION_SETTLE_MS);\n });\n activeCatalog.republish = () => {\n published = undefined;\n publish();\n };\n\n return () => {\n if (settle) clearTimeout(settle);\n unsubscribe();\n activeCatalog.republish = undefined;\n activeCatalog.current = undefined;\n catalog.dispose();\n };\n });\n}\n\nexport default modeCatalogExtension;\n"],"mappings":"2bA+CA,SAAS,EAAO,EAAiB,EAA2B,EAAc,EAAoC,CAC5G,IAAM,GAAA,EAAUA,EAAAA,4BAAAA,CAA4B,CAAM,EAClD,GAAI,EAAS,CACX,GAAI,CACF,QAAa,QAAQ,EAAQ,QAAQ,CAAE,OAAM,OAAM,CAAC,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,CAC9E,MAAQ,CAER,CACA,MACF,CACA,EAAQ,GAAG,OAAO,EAAM,CAAK,CAC/B,CAEA,SAAS,EAAiB,EAA2C,CAInE,OAHI,EAAgB,SAAS,OAAO,EAAU,QAC1C,EAAgB,SAAS,QAAQ,EAAU,SAC3C,EAAgB,SAAS,IAAI,EAAU,KACpC,QACT,CAEA,eAAsB,EAAqB,EAAiC,CAG1E,IAAM,EAAgC,CAAE,QAAS,IAAA,EAAU,EAC3D,EAAA,yBAAyB,MAAU,EAAc,OAAO,EACxD,EAAG,GAAG,oBAAuB,CAC3B,eAAiB,EAAc,YAAY,EAAG,GAAqB,CACrE,CAAC,EACD,IAAM,EAAa,MAAA,EAAMC,EAAAA,sBAAAA,CAAsB,EAAI,gCAAc,EAC3D,EAAQ,EAAW,KAAK,OAAQ,GAAoB,CACxD,EAAkB,EAAQ,EAAI,CAAa,CAC7C,CAAC,EACD,GAAI,CACF,MAAM,CACR,OAAS,EAAO,CAGd,MAFA,MAAM,EAAM,QAAQ,EACpB,MAAM,EAAW,QAAQ,EACnB,CACR,CAC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M,aAAc,OAAQ,EAAS,iBAAgB,CACjE,EACA,UACE,EAAW,MAAM,EAAO,EACjB,UAEX,EACA,GAAI,EAAO,UAAY,WAAa,CAAC,EACnC,MAAU,MAAM,6BAA6B,EAAO,QAAQ,IAAI,EAAO,YAAY,KAAK,IAAI,GAAG,EAEjG,OAAO,CACT,CACF,CAAC,EACD,EAAe,QAAQC,EAAAA,gCAAiC,CAAO,EAC/D,EAAc,QAAU,EAIxB,IAAI,EACA,EACE,MAAsB,CAC1B,EAAS,IAAA,GACT,IAAM,EAAaC,EAAAA,kBAAkB,EAAQ,YAAY,EAAG,CAAW,EACjE,EAAa,KAAK,UAAU,CAAU,EACxC,IAAe,IACnB,EAAY,EACZ,EAAG,YAAYC,EAAAA,2BAA4B,CAAU,EACvD,EACM,EAAc,EAAQ,cAAgB,CAC1C,IAAW,WAAW,EAAS,EAAoB,CACrD,CAAC,EAMD,MALA,GAAc,cAAkB,CAC9B,EAAY,IAAA,GACZ,EAAQ,CACV,MAEa,CACP,GAAQ,aAAa,CAAM,EAC/B,EAAY,EACZ,EAAc,UAAY,IAAA,GAC1B,EAAc,QAAU,IAAA,GACxB,EAAQ,QAAQ,CAClB,CACF,CAAC,CACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"modeCatalog.d.cts","names":[],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"mappings":";;iBAkDsB,qBAAqB,IAAI,eAAe"}
1
+ {"version":3,"file":"modeCatalog.d.cts","names":[],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"mappings":";;iBAmEsB,qBAAqB,IAAI,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"modeCatalog.d.mts","names":[],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"mappings":";;iBAkDsB,qBAAqB,IAAI,eAAe"}
1
+ {"version":3,"file":"modeCatalog.d.mts","names":[],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"mappings":";;iBAmEsB,qBAAqB,IAAI,eAAe"}
@@ -1,2 +1,2 @@
1
- import{createMinorModeCatalogHost as e}from"../../services/modeCatalog.mjs";import{projectMinorModes as t}from"../../services/minorModeProjection.mjs";import{registerMinorModeCommand as n}from"./minorModeCommand.mjs";import{DOOM_CORDIS_SESSION_SERVICE as r,connectDoomCordisHost as i}from"@agimon-ai/doompi-extension-contracts/cordis-host";import{DOOM_MINOR_MODE_CATALOG_SERVICE as a,DOOM_MINOR_MODE_ENTRY_TYPE as o}from"@agimon-ai/doompi-extension-contracts/mode";import{DOOM_HELP_SERVICE as s,requireDoomHelpService as c}from"@agimon-ai/doompi-extension-contracts/help";import{DOOM_TRANSITION_SERVICE as l,consumeMinorModeReloadHandoff as u,discardMinorModeReloadHandoff as d,requireDoomTransitionCoordinator as f}from"@agimon-ai/doompi-extension-contracts/transition";function p(e){return e.includes(`voice`)?`voice`:e.includes(`leader`)?`leader`:e.includes(`ui`)?`ui`:`system`}async function m(e){let t={current:void 0};n(e,()=>t.current),e.on(`session_start`,()=>{setTimeout(()=>t.republish?.(),500)});let r=await i(e,`@agimon-ai/doompi/mode-catalog`),a=r.root.plugin(n=>{h(n,e,t)});try{await a}catch(e){throw await a.dispose(),await r.dispose(),e}let o;e.on(`session_shutdown`,()=>o??=(async()=>{try{await a.dispose()}finally{await r.dispose()}})())}function h(n,i,m){n.inject([s],e=>{let t=c(e).register({source:`@agimon-ai/doompi`,moduleUrl:import.meta.url,skills:[{name:`doompi-author-extension`,description:`Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.`}]});return()=>t.dispose()}),n.inject([r,l],n=>{let s=n.get(r),c=s.context,l=f(n),h=s.reason===`reload`,g=s.sessionId,_=h?u(g):void 0;h||d(g);let v=c.hasUI&&c.mode===`tui`?`tui`:`headless`,y=e({sessionKind:v,context:c,restoreSnapshot:_,onRestorationError(e){c.ui.notify(`Could not restore a minor mode after reload: ${e instanceof Error?e.message:String(e)}`,`warning`)},async routeInvocation(e,t,n){let r,i=await l.execute({sessionId:c.sessionManager.getSessionId(),hostGeneration:l.hostGeneration,operationId:e.operationId,source:p(t),target:{axis:`minor-mode`,action:e,requesterSource:t}},async()=>(r=await n(),`applied`));if(i.outcome!==`applied`||!r)throw Error(`Minor-mode transition was ${i.outcome}: ${i.diagnostics.join(`, `)}`);return r}});n.provide(a,y),m.current=y;let b,x,S=()=>{x=void 0;let e=t(y.getSnapshot(),v),n=JSON.stringify(e);n!==b&&(b=n,i.appendEntry(o,e))},C=y.subscribe(()=>{x??=setTimeout(S,50)});return m.republish=()=>{b=void 0,S()},()=>{x&&clearTimeout(x),C(),m.republish=void 0,m.current=void 0,y.dispose()}})}export{m as default,m as modeCatalogExtension};
1
+ import{createMinorModeCatalogHost as e}from"../../services/modeCatalog.mjs";import{projectMinorModes as t}from"../../services/minorModeProjection.mjs";import{registerMinorModeCommand as n}from"./minorModeCommand.mjs";import{DOOM_CORDIS_SESSION_SERVICE as r,connectDoomCordisHost as i}from"@agimon-ai/doompi-extension-contracts/cordis-host";import{DOOM_MINOR_MODE_CATALOG_SERVICE as a,DOOM_MINOR_MODE_ENTRY_TYPE as o}from"@agimon-ai/doompi-extension-contracts/mode";import{DOOM_HELP_SERVICE as s,requireDoomHelpService as c}from"@agimon-ai/doompi-extension-contracts/help";import{readDoomNotificationService as l}from"@agimon-ai/doompi-extension-contracts/notification";import{DOOM_TRANSITION_SERVICE as u,consumeMinorModeReloadHandoff as d,discardMinorModeReloadHandoff as f,requireDoomTransitionCoordinator as p}from"@agimon-ai/doompi-extension-contracts/transition";function m(e,t,n,r){let i=l(e);if(i){try{Promise.resolve(i.request({body:n,level:r})).catch(()=>void 0)}catch{}return}t.ui.notify(n,r)}function h(e){return e.includes(`voice`)?`voice`:e.includes(`leader`)?`leader`:e.includes(`ui`)?`ui`:`system`}async function g(e){let t={current:void 0};n(e,()=>t.current),e.on(`session_start`,()=>{setTimeout(()=>t.republish?.(),500)});let r=await i(e,`@agimon-ai/doompi/mode-catalog`),a=r.root.plugin(n=>{_(n,e,t)});try{await a}catch(e){throw await a.dispose(),await r.dispose(),e}let o;e.on(`session_shutdown`,()=>o??=(async()=>{try{await a.dispose()}finally{await r.dispose()}})())}function _(n,i,l){n.inject([s],e=>{let t=c(e).register({source:`@agimon-ai/doompi`,moduleUrl:import.meta.url,skills:[{name:`doompi-author-extension`,description:`Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.`}]});return()=>t.dispose()}),n.inject([r,u],n=>{let s=n.get(r),c=s.context,u=p(n),g=s.reason===`reload`,_=s.sessionId,v=g?d(_):void 0;g||f(_);let y=c.hasUI&&c.mode===`tui`?`tui`:`headless`,b=e({sessionKind:y,context:c,restoreSnapshot:v,onRestorationError(e){m(n,c,`Could not restore a minor mode after reload: ${e instanceof Error?e.message:String(e)}`,`warning`)},async routeInvocation(e,t,n){let r,i=await u.execute({sessionId:c.sessionManager.getSessionId(),hostGeneration:u.hostGeneration,operationId:e.operationId,source:h(t),target:{axis:`minor-mode`,action:e,requesterSource:t}},async()=>(r=await n(),`applied`));if(i.outcome!==`applied`||!r)throw Error(`Minor-mode transition was ${i.outcome}: ${i.diagnostics.join(`, `)}`);return r}});n.provide(a,b),l.current=b;let x,S,C=()=>{S=void 0;let e=t(b.getSnapshot(),y),n=JSON.stringify(e);n!==x&&(x=n,i.appendEntry(o,e))},w=b.subscribe(()=>{S??=setTimeout(C,50)});return l.republish=()=>{x=void 0,C()},()=>{S&&clearTimeout(S),w(),l.republish=void 0,l.current=void 0,b.dispose()}})}export{g as default,g as modeCatalogExtension};
2
2
  //# sourceMappingURL=modeCatalog.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"modeCatalog.mjs","names":[],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"sourcesContent":["import {\n DOOM_MINOR_MODE_CATALOG_SERVICE,\n DOOM_MINOR_MODE_ENTRY_TYPE,\n type MinorModeActionResponse,\n type MinorModeCatalogService,\n} from '@agimon-ai/doompi-extension-contracts/mode';\nimport {\n connectDoomCordisHost,\n DOOM_CORDIS_SESSION_SERVICE,\n type DoomCordisSessionService,\n} from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { DOOM_HELP_SERVICE, requireDoomHelpService } from '@agimon-ai/doompi-extension-contracts/help';\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport {\n consumeMinorModeReloadHandoff,\n discardMinorModeReloadHandoff,\n type MinorModeCatalogHost,\n DOOM_TRANSITION_SERVICE,\n requireDoomTransitionCoordinator,\n type TransitionSource,\n} from '@agimon-ai/doompi-extension-contracts/transition';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { projectMinorModes } from '../../services/minorModeProjection.ts';\nimport { createMinorModeCatalogHost } from '../../services/modeCatalog.ts';\nimport { registerMinorModeCommand } from './minorModeCommand.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi/mode-catalog';\nconst HELP_CONTRIBUTION_SOURCE = '@agimon-ai/doompi';\n/** Registrations and state flips arrive in bursts; one entry covers a burst. */\nconst PROJECTION_SETTLE_MS = 50;\n/**\n * Pi's rpc mode subscribes to session events only after bindExtensions()\n * returns, which is after session_start has run, so an entry journaled during\n * startup never reaches a client. A publish deferred past that point does.\n */\nconst BOOT_PUBLISH_DELAY_MS = 500;\n\ninterface CatalogBinding {\n current: MinorModeCatalogService | undefined;\n /** Journals the projection even if unchanged; set while a session is bound. */\n republish?: () => void;\n}\n\nfunction transitionSource(requesterSource: string): TransitionSource {\n if (requesterSource.includes('voice')) return 'voice';\n if (requesterSource.includes('leader')) return 'leader';\n if (requesterSource.includes('ui')) return 'ui';\n return 'system';\n}\n\nexport async function modeCatalogExtension(pi: ExtensionAPI): Promise<void> {\n // The command outlives any one session: it is registered once and reads the\n // catalog binding the session-scoped inject below sets and clears.\n const activeCatalog: CatalogBinding = { current: undefined };\n registerMinorModeCommand(pi, () => activeCatalog.current);\n pi.on('session_start', () => {\n setTimeout(() => activeCatalog.republish?.(), BOOT_PUBLISH_DELAY_MS);\n });\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin((cordis: Context) => {\n modeCatalogPlugin(cordis, pi, activeCatalog);\n });\n try {\n await fiber;\n } catch (error) {\n await fiber.dispose();\n await connection.dispose();\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\nfunction modeCatalogPlugin(\n cordis: Context,\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n activeCatalog: CatalogBinding,\n): void {\n cordis.inject([DOOM_HELP_SERVICE], (helpContext) => {\n const contribution = requireDoomHelpService(helpContext).register({\n source: HELP_CONTRIBUTION_SOURCE,\n moduleUrl: import.meta.url,\n skills: [\n {\n name: 'doompi-author-extension',\n description:\n 'Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.',\n },\n ],\n });\n return () => contribution.dispose();\n });\n\n cordis.inject([DOOM_CORDIS_SESSION_SERVICE, DOOM_TRANSITION_SERVICE], (sessionContext) => {\n const session = sessionContext.get(DOOM_CORDIS_SESSION_SERVICE) as DoomCordisSessionService;\n const context = session.context;\n const coordinator = requireDoomTransitionCoordinator(sessionContext);\n const reloadSession = session.reason === 'reload';\n const sessionId = session.sessionId;\n const restoreSnapshot = reloadSession ? consumeMinorModeReloadHandoff(sessionId) : undefined;\n if (!reloadSession) discardMinorModeReloadHandoff(sessionId);\n const sessionKind = context.hasUI && context.mode === 'tui' ? 'tui' : 'headless';\n const catalog: MinorModeCatalogHost = createMinorModeCatalogHost({\n sessionKind,\n context,\n restoreSnapshot,\n onRestorationError(error) {\n context.ui.notify(\n `Could not restore a minor mode after reload: ${error instanceof Error ? error.message : String(error)}`,\n 'warning',\n );\n },\n async routeInvocation(request, requesterSource, invoke) {\n let response: MinorModeActionResponse | undefined;\n const result = await coordinator.execute(\n {\n sessionId: context.sessionManager.getSessionId(),\n hostGeneration: coordinator.hostGeneration,\n operationId: request.operationId,\n source: transitionSource(requesterSource),\n target: { axis: 'minor-mode', action: request, requesterSource },\n },\n async () => {\n response = await invoke();\n return 'applied';\n },\n );\n if (result.outcome !== 'applied' || !response) {\n throw new Error(`Minor-mode transition was ${result.outcome}: ${result.diagnostics.join(', ')}`);\n }\n return response;\n },\n });\n sessionContext.provide(DOOM_MINOR_MODE_CATALOG_SERVICE, catalog);\n activeCatalog.current = catalog;\n\n // Journal the projection so RPC clients see catalog state live and on\n // replay; identical projections are skipped so detail churn stays cheap.\n let published: string | undefined;\n let settle: NodeJS.Timeout | undefined;\n const publish = (): void => {\n settle = undefined;\n const projection = projectMinorModes(catalog.getSnapshot(), sessionKind);\n const serialized = JSON.stringify(projection);\n if (serialized === published) return;\n published = serialized;\n pi.appendEntry(DOOM_MINOR_MODE_ENTRY_TYPE, projection);\n };\n const unsubscribe = catalog.subscribe(() => {\n settle ??= setTimeout(publish, PROJECTION_SETTLE_MS);\n });\n activeCatalog.republish = () => {\n published = undefined;\n publish();\n };\n\n return () => {\n if (settle) clearTimeout(settle);\n unsubscribe();\n activeCatalog.republish = undefined;\n activeCatalog.current = undefined;\n catalog.dispose();\n };\n });\n}\n\nexport default modeCatalogExtension;\n"],"mappings":"mwBA2CA,SAAS,EAAiB,EAA2C,CAInE,OAHI,EAAgB,SAAS,OAAO,EAAU,QAC1C,EAAgB,SAAS,QAAQ,EAAU,SAC3C,EAAgB,SAAS,IAAI,EAAU,KACpC,QACT,CAEA,eAAsB,EAAqB,EAAiC,CAG1E,IAAM,EAAgC,CAAE,QAAS,IAAA,EAAU,EAC3D,EAAyB,MAAU,EAAc,OAAO,EACxD,EAAG,GAAG,oBAAuB,CAC3B,eAAiB,EAAc,YAAY,EAAG,GAAqB,CACrE,CAAC,EACD,IAAM,EAAa,MAAM,EAA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AAQ,EAAiB,CAAe,EACxC,OAAQ,CAAE,KAAM,aAAc,OAAQ,EAAS,iBAAgB,CACjE,EACA,UACE,EAAW,MAAM,EAAO,EACjB,UAEX,EACA,GAAI,EAAO,UAAY,WAAa,CAAC,EACnC,MAAU,MAAM,6BAA6B,EAAO,QAAQ,IAAI,EAAO,YAAY,KAAK,IAAI,GAAG,EAEjG,OAAO,CACT,CACF,CAAC,EACD,EAAe,QAAQ,EAAiC,CAAO,EAC/D,EAAc,QAAU,EAIxB,IAAI,EACA,EACE,MAAsB,CAC1B,EAAS,IAAA,GACT,IAAM,EAAa,EAAkB,EAAQ,YAAY,EAAG,CAAW,EACjE,EAAa,KAAK,UAAU,CAAU,EACxC,IAAe,IACnB,EAAY,EACZ,EAAG,YAAY,EAA4B,CAAU,EACvD,EACM,EAAc,EAAQ,cAAgB,CAC1C,IAAW,WAAW,EAAS,EAAoB,CACrD,CAAC,EAMD,MALA,GAAc,cAAkB,CAC9B,EAAY,IAAA,GACZ,EAAQ,CACV,MAEa,CACP,GAAQ,aAAa,CAAM,EAC/B,EAAY,EACZ,EAAc,UAAY,IAAA,GAC1B,EAAc,QAAU,IAAA,GACxB,EAAQ,QAAQ,CAClB,CACF,CAAC,CACH"}
1
+ {"version":3,"file":"modeCatalog.mjs","names":[],"sources":["../../../../src/extensions/entries/modeCatalog.ts"],"sourcesContent":["import {\n DOOM_MINOR_MODE_CATALOG_SERVICE,\n DOOM_MINOR_MODE_ENTRY_TYPE,\n type MinorModeActionResponse,\n type MinorModeCatalogService,\n} from '@agimon-ai/doompi-extension-contracts/mode';\nimport {\n connectDoomCordisHost,\n DOOM_CORDIS_SESSION_SERVICE,\n type DoomCordisSessionService,\n} from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport { DOOM_HELP_SERVICE, requireDoomHelpService } from '@agimon-ai/doompi-extension-contracts/help';\nimport {\n type DoomNotificationLevel,\n readDoomNotificationService,\n} from '@agimon-ai/doompi-extension-contracts/notification';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport {\n consumeMinorModeReloadHandoff,\n discardMinorModeReloadHandoff,\n type MinorModeCatalogHost,\n DOOM_TRANSITION_SERVICE,\n requireDoomTransitionCoordinator,\n type TransitionSource,\n} from '@agimon-ai/doompi-extension-contracts/transition';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { projectMinorModes } from '../../services/minorModeProjection.ts';\nimport { createMinorModeCatalogHost } from '../../services/modeCatalog.ts';\nimport { registerMinorModeCommand } from './minorModeCommand.ts';\n\nconst PACKAGE_SOURCE = '@agimon-ai/doompi/mode-catalog';\nconst HELP_CONTRIBUTION_SOURCE = '@agimon-ai/doompi';\n/** Registrations and state flips arrive in bursts; one entry covers a burst. */\nconst PROJECTION_SETTLE_MS = 50;\n/**\n * Pi's rpc mode subscribes to session events only after bindExtensions()\n * returns, which is after session_start has run, so an entry journaled during\n * startup never reaches a client. A publish deferred past that point does.\n */\nconst BOOT_PUBLISH_DELAY_MS = 500;\n\ninterface CatalogBinding {\n current: MinorModeCatalogService | undefined;\n /** Journals the projection even if unchanged; set while a session is bound. */\n republish?: () => void;\n}\n\nfunction notify(cordis: Context, context: ExtensionContext, body: string, level: DoomNotificationLevel): void {\n const service = readDoomNotificationService(cordis);\n if (service) {\n try {\n void Promise.resolve(service.request({ body, level })).catch(() => undefined);\n } catch {\n // Notification delivery is best effort and does not fall back after routing.\n }\n return;\n }\n context.ui.notify(body, level);\n}\n\nfunction transitionSource(requesterSource: string): TransitionSource {\n if (requesterSource.includes('voice')) return 'voice';\n if (requesterSource.includes('leader')) return 'leader';\n if (requesterSource.includes('ui')) return 'ui';\n return 'system';\n}\n\nexport async function modeCatalogExtension(pi: ExtensionAPI): Promise<void> {\n // The command outlives any one session: it is registered once and reads the\n // catalog binding the session-scoped inject below sets and clears.\n const activeCatalog: CatalogBinding = { current: undefined };\n registerMinorModeCommand(pi, () => activeCatalog.current);\n pi.on('session_start', () => {\n setTimeout(() => activeCatalog.republish?.(), BOOT_PUBLISH_DELAY_MS);\n });\n const connection = await connectDoomCordisHost(pi, PACKAGE_SOURCE);\n const fiber = connection.root.plugin((cordis: Context) => {\n modeCatalogPlugin(cordis, pi, activeCatalog);\n });\n try {\n await fiber;\n } catch (error) {\n await fiber.dispose();\n await connection.dispose();\n throw error;\n }\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n\nfunction modeCatalogPlugin(\n cordis: Context,\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n activeCatalog: CatalogBinding,\n): void {\n cordis.inject([DOOM_HELP_SERVICE], (helpContext) => {\n const contribution = requireDoomHelpService(helpContext).register({\n source: HELP_CONTRIBUTION_SOURCE,\n moduleUrl: import.meta.url,\n skills: [\n {\n name: 'doompi-author-extension',\n description:\n 'Create or update a DoomPi extension package inside the DoomPi monorepo or as an external npm package. Use for package layout, Pi discovery entries, shared Cordis lifecycle, package-owned Help, and extension verification.',\n },\n ],\n });\n return () => contribution.dispose();\n });\n\n cordis.inject([DOOM_CORDIS_SESSION_SERVICE, DOOM_TRANSITION_SERVICE], (sessionContext) => {\n const session = sessionContext.get(DOOM_CORDIS_SESSION_SERVICE) as DoomCordisSessionService;\n const context = session.context;\n const coordinator = requireDoomTransitionCoordinator(sessionContext);\n const reloadSession = session.reason === 'reload';\n const sessionId = session.sessionId;\n const restoreSnapshot = reloadSession ? consumeMinorModeReloadHandoff(sessionId) : undefined;\n if (!reloadSession) discardMinorModeReloadHandoff(sessionId);\n const sessionKind = context.hasUI && context.mode === 'tui' ? 'tui' : 'headless';\n const catalog: MinorModeCatalogHost = createMinorModeCatalogHost({\n sessionKind,\n context,\n restoreSnapshot,\n onRestorationError(error) {\n notify(\n sessionContext,\n context,\n `Could not restore a minor mode after reload: ${error instanceof Error ? error.message : String(error)}`,\n 'warning',\n );\n },\n async routeInvocation(request, requesterSource, invoke) {\n let response: MinorModeActionResponse | undefined;\n const result = await coordinator.execute(\n {\n sessionId: context.sessionManager.getSessionId(),\n hostGeneration: coordinator.hostGeneration,\n operationId: request.operationId,\n source: transitionSource(requesterSource),\n target: { axis: 'minor-mode', action: request, requesterSource },\n },\n async () => {\n response = await invoke();\n return 'applied';\n },\n );\n if (result.outcome !== 'applied' || !response) {\n throw new Error(`Minor-mode transition was ${result.outcome}: ${result.diagnostics.join(', ')}`);\n }\n return response;\n },\n });\n sessionContext.provide(DOOM_MINOR_MODE_CATALOG_SERVICE, catalog);\n activeCatalog.current = catalog;\n\n // Journal the projection so RPC clients see catalog state live and on\n // replay; identical projections are skipped so detail churn stays cheap.\n let published: string | undefined;\n let settle: NodeJS.Timeout | undefined;\n const publish = (): void => {\n settle = undefined;\n const projection = projectMinorModes(catalog.getSnapshot(), sessionKind);\n const serialized = JSON.stringify(projection);\n if (serialized === published) return;\n published = serialized;\n pi.appendEntry(DOOM_MINOR_MODE_ENTRY_TYPE, projection);\n };\n const unsubscribe = catalog.subscribe(() => {\n settle ??= setTimeout(publish, PROJECTION_SETTLE_MS);\n });\n activeCatalog.republish = () => {\n published = undefined;\n publish();\n };\n\n return () => {\n if (settle) clearTimeout(settle);\n unsubscribe();\n activeCatalog.republish = undefined;\n activeCatalog.current = undefined;\n catalog.dispose();\n };\n });\n}\n\nexport default modeCatalogExtension;\n"],"mappings":"o2BA+CA,SAAS,EAAO,EAAiB,EAA2B,EAAc,EAAoC,CAC5G,IAAM,EAAU,EAA4B,CAAM,EAClD,GAAI,EAAS,CACX,GAAI,CACF,QAAa,QAAQ,EAAQ,QAAQ,CAAE,OAAM,OAAM,CAAC,CAAC,CAAC,CAAC,UAAY,IAAA,EAAS,CAC9E,MAAQ,CAER,CACA,MACF,CACA,EAAQ,GAAG,OAAO,EAAM,CAAK,CAC/B,CAEA,SAAS,EAAiB,EAA2C,CAInE,OAHI,EAAgB,SAAS,OAAO,EAAU,QAC1C,EAAgB,SAAS,QAAQ,EAAU,S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AAO,CACxB,EACE,EACA,EACA,gDAAgD,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,IACrG,SACF,CACF,EACA,MAAM,gBAAgB,EAAS,EAAiB,EAAQ,CACtD,IAAI,EACE,EAAS,MAAM,EAAY,QAC/B,CACE,UAAW,EAAQ,eAAe,aAAa,EAC/C,eAAgB,EAAY,eAC5B,YAAa,EAAQ,YACrB,OAAQ,EAAiB,CAAe,EACxC,OAAQ,CAAE,KAAM,aAAc,OAAQ,EAAS,iBAAgB,CACjE,EACA,UACE,EAAW,MAAM,EAAO,EACjB,UAEX,EACA,GAAI,EAAO,UAAY,WAAa,CAAC,EACnC,MAAU,MAAM,6BAA6B,EAAO,QAAQ,IAAI,EAAO,YAAY,KAAK,IAAI,GAAG,EAEjG,OAAO,CACT,CACF,CAAC,EACD,EAAe,QAAQ,EAAiC,CAAO,EAC/D,EAAc,QAAU,EAIxB,IAAI,EACA,EACE,MAAsB,CAC1B,EAAS,IAAA,GACT,IAAM,EAAa,EAAkB,EAAQ,YAAY,EAAG,CAAW,EACjE,EAAa,KAAK,UAAU,CAAU,EACxC,IAAe,IACnB,EAAY,EACZ,EAAG,YAAY,EAA4B,CAAU,EACvD,EACM,EAAc,EAAQ,cAAgB,CAC1C,IAAW,WAAW,EAAS,EAAoB,CACrD,CAAC,EAMD,MALA,GAAc,cAAkB,CAC9B,EAAY,IAAA,GACZ,EAAQ,CACV,MAEa,CACP,GAAQ,aAAa,CAAM,EAC/B,EAAY,EACZ,EAAc,UAAY,IAAA,GAC1B,EAAc,QAAU,IAAA,GACxB,EAAQ,QAAQ,CAClB,CACF,CAAC,CACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/doompi",
3
- "version": "0.0.1-alpha.39",
3
+ "version": "0.0.1-alpha.40",
4
4
  "description": "Opinionated, composable Pi distribution for scoped agent tools, skills, MCP servers, and developer workflows.",
5
5
  "keywords": [
6
6
  "ai",
@@ -309,17 +309,17 @@
309
309
  "rolldown": "1.2.5",
310
310
  "typebox": "1.3.16",
311
311
  "yaml": "2.9.0",
312
- "@agimon-ai/doompi-autostop": "0.0.1-alpha.17",
313
- "@agimon-ai/doompi-cache": "0.0.1-alpha.6",
314
- "@agimon-ai/doompi-config": "0.0.1-alpha.39",
315
- "@agimon-ai/doompi-domain": "0.0.1-alpha.17",
316
- "@agimon-ai/doompi-extension-contracts": "0.0.1-alpha.39",
317
- "@agimon-ai/doompi-notification": "0.0.1-alpha.17",
318
- "@agimon-ai/doompi-profile": "0.0.1-alpha.17",
319
- "@agimon-ai/doompi-major-mode": "0.0.1-alpha.17",
320
- "@agimon-ai/doompi-telemetry": "0.0.1-alpha.39",
321
- "@agimon-ai/doompi-ui": "0.0.1-alpha.39",
322
- "@agimon-ai/doompi-skill": "0.0.1-alpha.17"
312
+ "@agimon-ai/doompi-autostop": "0.0.1-alpha.18",
313
+ "@agimon-ai/doompi-config": "0.0.1-alpha.40",
314
+ "@agimon-ai/doompi-extension-contracts": "0.0.1-alpha.40",
315
+ "@agimon-ai/doompi-domain": "0.0.1-alpha.18",
316
+ "@agimon-ai/doompi-major-mode": "0.0.1-alpha.18",
317
+ "@agimon-ai/doompi-notification": "0.0.1-alpha.18",
318
+ "@agimon-ai/doompi-skill": "0.0.1-alpha.18",
319
+ "@agimon-ai/doompi-telemetry": "0.0.1-alpha.40",
320
+ "@agimon-ai/doompi-profile": "0.0.1-alpha.18",
321
+ "@agimon-ai/doompi-ui": "0.0.1-alpha.40",
322
+ "@agimon-ai/doompi-cache": "0.0.1-alpha.7"
323
323
  },
324
324
  "devDependencies": {
325
325
  "@earendil-works/pi-ai": "0.84.3",
@@ -329,7 +329,7 @@
329
329
  "@vitest/coverage-v8": "4.1.11",
330
330
  "typescript": "7.0.2",
331
331
  "vitest": "4.1.11",
332
- "@agimon-ai/doompi-runner": "0.0.1-alpha.39"
332
+ "@agimon-ai/doompi-runner": "0.0.1-alpha.40"
333
333
  },
334
334
  "peerDependencies": {
335
335
  "@earendil-works/pi-tui": "0.84.3"