@rainmanhhh/pi-web 0.29.9 → 0.29.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server.mjs +3 -3
- package/dist/static/assets/{CodeMirrorEditor-CK8t1OmY.js → CodeMirrorEditor-Ca7fRlGs.js} +1 -1
- package/dist/static/assets/{abnfDiagram-VCTEODGH-Dj0m7weO.js → abnfDiagram-VCTEODGH-SH118qIb.js} +1 -1
- package/dist/static/assets/architecture-7GRP2DOG-C6cAxhEr.js +1 -0
- package/dist/static/assets/{architectureDiagram-5GKGNRK7-DYXWhkhH.js → architectureDiagram-5GKGNRK7-DzrshpoO.js} +1 -1
- package/dist/static/assets/{blockDiagram-I7D4REHJ-DpCJaj50.js → blockDiagram-I7D4REHJ-BJ4cPNuA.js} +1 -1
- package/dist/static/assets/{c4Diagram-7LVT6UL2-SyBJx2NN.js → c4Diagram-7LVT6UL2-DknC4VHB.js} +1 -1
- package/dist/static/assets/channel-BfBLWUue.js +1 -0
- package/dist/static/assets/{chunk-4HAMMTFA-CVrpWEpV.js → chunk-4HAMMTFA-DgjhaGuf.js} +1 -1
- package/dist/static/assets/{chunk-75Z2AOVW-BnlAQDN9.js → chunk-75Z2AOVW-B_HR8qEk.js} +1 -1
- package/dist/static/assets/{chunk-DU6HZSFF-B-FmhRJ0.js → chunk-DU6HZSFF-bLqPZUBY.js} +1 -1
- package/dist/static/assets/{chunk-F27PBJKO-CJ9znU6N.js → chunk-F27PBJKO-BWdmohoF.js} +1 -1
- package/dist/static/assets/{chunk-GMAD6QVW-D3ZsfImt.js → chunk-GMAD6QVW-BFPL0Zep.js} +1 -1
- package/dist/static/assets/{chunk-GVQU2GXP-Bi4zm-Fu.js → chunk-GVQU2GXP-Dj2nm7Qh.js} +1 -1
- package/dist/static/assets/{chunk-IMKFNOWR-BwmXvoRI.js → chunk-IMKFNOWR-WPZQvCx-.js} +1 -1
- package/dist/static/assets/{chunk-L3NEJ4N5-DgXJcES-.js → chunk-L3NEJ4N5-CkiEJlFj.js} +1 -1
- package/dist/static/assets/{chunk-OSK3NFVY-D9gf70hT.js → chunk-OSK3NFVY-CrOZX_TW.js} +1 -1
- package/dist/static/assets/{chunk-P2QGCYS3-DqaqJsHA.js → chunk-P2QGCYS3-C_KXTV9A.js} +1 -1
- package/dist/static/assets/{chunk-POPQ4Y6H-yrfwFJwv.js → chunk-POPQ4Y6H-9ACR4iPi.js} +1 -1
- package/dist/static/assets/{chunk-PWAF6VOD-Bd471q4e.js → chunk-PWAF6VOD-CcvuQZL3.js} +1 -1
- package/dist/static/assets/{chunk-SHT3W25Y-B2jl9QqN.js → chunk-SHT3W25Y-Bq8SMK5j.js} +1 -1
- package/dist/static/assets/{chunk-SVP7TREG-D6yLxjiJ.js → chunk-SVP7TREG-CCilJIJJ.js} +1 -1
- package/dist/static/assets/{chunk-TICWLB2K-C9pK3GQm.js → chunk-TICWLB2K-2p1n3f-O.js} +1 -1
- package/dist/static/assets/classDiagram-ZZMXUADV-CbyDIc49.js +1 -0
- package/dist/static/assets/classDiagram-v2-VYDZK3BY-CbyDIc49.js +1 -0
- package/dist/static/assets/{cynefin-OW5HDTMX-DgXPJMog.js → cynefin-OW5HDTMX-CBxAo2Z6.js} +1 -1
- package/dist/static/assets/{cynefinDiagram-5FMLGOSQ-CVaMoJEy.js → cynefinDiagram-5FMLGOSQ-fRkKU4Gl.js} +1 -1
- package/dist/static/assets/{dagre-GXQ25YYZ-3faqjinl.js → dagre-GXQ25YYZ-CcATVyUZ.js} +1 -1
- package/dist/static/assets/{diagram-S7CK7UJ4-Bsi4L1E9.js → diagram-S7CK7UJ4-BwHvR14i.js} +1 -1
- package/dist/static/assets/{diagram-UQ7AKVKN-Be2ObPS6.js → diagram-UQ7AKVKN-BP1T3z6z.js} +1 -1
- package/dist/static/assets/{diagram-VSXAHHWV-BXDpLNS7.js → diagram-VSXAHHWV-YT6MjgFM.js} +1 -1
- package/dist/static/assets/{diagram-VX7I27RA-D4tifvwv.js → diagram-VX7I27RA-D_7J2TDq.js} +1 -1
- package/dist/static/assets/{diagram-Z3DM3KII-Df26iPL4.js → diagram-Z3DM3KII-DAdsZjK1.js} +1 -1
- package/dist/static/assets/{ebnfDiagram-PWID7BFC-Dyla5Dkm.js → ebnfDiagram-PWID7BFC-BtD1n9Hu.js} +1 -1
- package/dist/static/assets/{erDiagram-RLTQ6QDP-BLvyhNBO.js → erDiagram-RLTQ6QDP-PQshZ6Yl.js} +1 -1
- package/dist/static/assets/eventmodeling-NTZA5JFV-BhrCp_nt.js +1 -0
- package/dist/static/assets/flowDiagram-HODETNUW-D4OdXGQh.js +1 -0
- package/dist/static/assets/{ganttDiagram-EL5Y4UJY-C-0TGa3M.js → ganttDiagram-EL5Y4UJY-QdSkZehk.js} +1 -1
- package/dist/static/assets/{gitGraph-4MIJSDKK-DAURot41.js → gitGraph-4MIJSDKK-BvXSTIf2.js} +1 -1
- package/dist/static/assets/{gitGraphDiagram-WWUBYQGX-BfoP0TNh.js → gitGraphDiagram-WWUBYQGX-Bz00NHv2.js} +1 -1
- package/dist/static/assets/{highlighted-body-KPVGNVTW-D_dQt-dG.js → highlighted-body-KPVGNVTW-CCvJfjDn.js} +1 -1
- package/dist/static/assets/index-DFqQ5Zwn.js +506 -0
- package/dist/static/assets/{info-A6RAGUB7-BE2rRbV9.js → info-A6RAGUB7-BYwzACMW.js} +1 -1
- package/dist/static/assets/{infoDiagram-27XIBGKW-Bw5qS021.js → infoDiagram-27XIBGKW-DtkzCE6b.js} +1 -1
- package/dist/static/assets/{ishikawaDiagram-5VMMS53U-CB3EXwSt.js → ishikawaDiagram-5VMMS53U-BMxP6sCu.js} +1 -1
- package/dist/static/assets/{journeyDiagram-3NMN7TZE-B_rR09k9.js → journeyDiagram-3NMN7TZE-D5WqlnYu.js} +1 -1
- package/dist/static/assets/{kanban-definition-UXKFOSKX-CVDNPGGv.js → kanban-definition-UXKFOSKX-B9XXMVHI.js} +1 -1
- package/dist/static/assets/{line-xiMNdYAV.js → line-Cc-RoUXu.js} +1 -1
- package/dist/static/assets/mermaid-HWGCJPDP-B72xQAHx.js +1 -0
- package/dist/static/assets/{mermaid-parser.core-BZ1obL-j.js → mermaid-parser.core-Dsr8dklE.js} +3 -3
- package/dist/static/assets/{mermaid.core-BHLJ6Gh9.js → mermaid.core-BvIy2RJD.js} +4 -4
- package/dist/static/assets/{mindmap-definition-YA3MSWOX-CiB8vRDR.js → mindmap-definition-YA3MSWOX-DtAorrBk.js} +1 -1
- package/dist/static/assets/{packet-AYTQ26CC-CKRdwR9S.js → packet-AYTQ26CC-BjFV-AAP.js} +1 -1
- package/dist/static/assets/{pegDiagram-XKGWAZYB-BqxLuclk.js → pegDiagram-XKGWAZYB-DSlW7GuO.js} +1 -1
- package/dist/static/assets/{pie-WAS4IAKB-D41U5wL5.js → pie-WAS4IAKB-B8A-Ncug.js} +1 -1
- package/dist/static/assets/{pieDiagram-E7YTZNPT-C_EhHkAi.js → pieDiagram-E7YTZNPT-4wrljEaR.js} +1 -1
- package/dist/static/assets/{quadrantDiagram-AXDQQJYC-_o1ra1k3.js → quadrantDiagram-AXDQQJYC-CGupd6Wi.js} +1 -1
- package/dist/static/assets/{radar-RG4KPBEZ-91iI6W75.js → radar-RG4KPBEZ-vgI1ahhz.js} +1 -1
- package/dist/static/assets/{railroad-74A4TZTK-CeivAIFT.js → railroad-74A4TZTK-DxFHrSu1.js} +1 -1
- package/dist/static/assets/railroad-abnf-HS5TGJTU-DjnLDep7.js +1 -0
- package/dist/static/assets/railroad-ebnf-LZEXJU2U-BczDnU3f.js +1 -0
- package/dist/static/assets/railroad-peg-WCYAUIDC-stWqA5PS.js +1 -0
- package/dist/static/assets/{railroadDiagram-O6MQD6OU-ISMDy-7Q.js → railroadDiagram-O6MQD6OU-DevvPuJ4.js} +1 -1
- package/dist/static/assets/{requirementDiagram-BXWQKSXE-Bzmt5K35.js → requirementDiagram-BXWQKSXE-BnaL-MkB.js} +1 -1
- package/dist/static/assets/{sankeyDiagram-P5KCCOFB-BOI6K8H2.js → sankeyDiagram-P5KCCOFB-Bk4gj2ya.js} +1 -1
- package/dist/static/assets/{sequenceDiagram-WJ2MYXX4-GrFsoi-i.js → sequenceDiagram-WJ2MYXX4-BcZvO65Z.js} +1 -1
- package/dist/static/assets/{stateDiagram-D77RDMKH-gg-7v9ES.js → stateDiagram-D77RDMKH-DqKd5JBe.js} +1 -1
- package/dist/static/assets/stateDiagram-v2-MP3YSRHH-CBmWYISc.js +1 -0
- package/dist/static/assets/{swimlanes-42K2YHIH-DA31lhfr.js → swimlanes-42K2YHIH-DMQ5HQIl.js} +1 -1
- package/dist/static/assets/swimlanesDiagram-VR7AAH4N-DWbg2rsQ.js +8 -0
- package/dist/static/assets/{timeline-definition-24CTP7MA-CKye69j-.js → timeline-definition-24CTP7MA-BuqQxVB3.js} +1 -1
- package/dist/static/assets/{treeView-Q6P3EWNA-NLBibjJF.js → treeView-Q6P3EWNA-DlkcpR0Z.js} +1 -1
- package/dist/static/assets/{treemap-WGGIJYW6-BT-lbqmk.js → treemap-WGGIJYW6-ClRO6lZO.js} +1 -1
- package/dist/static/assets/{vennDiagram-4TSXK5OY-DS1ezfoi.js → vennDiagram-4TSXK5OY-Dsq9apVZ.js} +1 -1
- package/dist/static/assets/{wardley-WFR3VGLG-BNnXFNIL.js → wardley-WFR3VGLG-DKTPXn6A.js} +1 -1
- package/dist/static/assets/{wardleyDiagram-VM6X3IG4-CNeaVsz_.js → wardleyDiagram-VM6X3IG4-DMnOMAhu.js} +1 -1
- package/dist/static/assets/{xychartDiagram-S5SC5T6Z-Cb-mEOOA.js → xychartDiagram-S5SC5T6Z-Cu0gs0q6.js} +1 -1
- package/dist/static/index.html +1 -1
- package/package.json +1 -1
- package/dist/static/assets/architecture-7GRP2DOG-BY9eEVgv.js +0 -1
- package/dist/static/assets/channel-D0AFjrVm.js +0 -1
- package/dist/static/assets/classDiagram-ZZMXUADV-Ry3s-yrx.js +0 -1
- package/dist/static/assets/classDiagram-v2-VYDZK3BY-Ry3s-yrx.js +0 -1
- package/dist/static/assets/eventmodeling-NTZA5JFV-CqogPHhP.js +0 -1
- package/dist/static/assets/flowDiagram-HODETNUW-DDSWQTG2.js +0 -1
- package/dist/static/assets/index-B3LLJ-oN.js +0 -506
- package/dist/static/assets/mermaid-HWGCJPDP-BKdAOwHm.js +0 -1
- package/dist/static/assets/railroad-abnf-HS5TGJTU-CnfWKQhp.js +0 -1
- package/dist/static/assets/railroad-ebnf-LZEXJU2U-Clr3Evrd.js +0 -1
- package/dist/static/assets/railroad-peg-WCYAUIDC-DpOAgbk0.js +0 -1
- package/dist/static/assets/stateDiagram-v2-MP3YSRHH-DhHraFZd.js +0 -1
- package/dist/static/assets/swimlanesDiagram-VR7AAH4N-Cer3aG7J.js +0 -8
package/dist/server.mjs
CHANGED
|
@@ -257,7 +257,7 @@ Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycl
|
|
|
257
257
|
`),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,i=n.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in me.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,me.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new fh(this.options),t=(n)=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter((n)=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach((n)=>{Object.keys(n.implied).filter((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=(o)=>{let s=o.attributeName(),a=this.getOptionValue(s),c=this.options.find((d)=>d.negate&&s===d.attributeName()),u=this.options.find((d)=>!d.negate&&s===d.attributeName());if(c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg))return c;return u||o},r=(o)=>{let s=n(o),a=s.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${s.envVar}'`;return`option '${s.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter((s)=>s.long).map((s)=>s.long);r=r.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=ph(e,r)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",r=e.length,i=this.parent?` for '${this.name()}'`:"",o=e.join(", "),s=`error: too many arguments${i}. Expected ${t} argument${n} but got ${r}: ${o}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach((i)=>{if(r.push(i.name()),i.alias())r.push(i.alias())}),t=ph(e,r)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
258
258
|
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((n)=>Pu(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}helpGroup(e){if(e===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=e,this}commandsGroup(e){if(e===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=e,this}optionsGroup(e){if(e===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=e,this}_initOptionGroup(e){if(this._defaultOptionGroup&&!e.helpGroupHeading)e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){if(this._defaultCommandGroup&&!e.helpGroup())e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=Vn.basename(e,Vn.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let r=t.formatHelp(this,t);if(n.hasColors)return r;return this._outputConfiguration.stripColor(r)}_getOutputContext(e){e=e||{};let t=!!e.error,n,r,i;if(t)n=(s)=>this._outputConfiguration.writeErr(s),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth();else n=(s)=>this._outputConfiguration.writeOut(s),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth();return{error:t,write:(s)=>{if(!r)s=this._outputConfiguration.stripColor(s);return n(s)},hasColors:r,helpWidth:i}}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getOutputContext(e),r={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach((o)=>o.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let i=this.helpInformation({error:n.error});if(t){if(i=t(i),typeof i!=="string"&&!Buffer.isBuffer(i))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(i),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",r),this._getCommandAndAncestors().forEach((o)=>o.emit("afterAllHelp",r))}helpOption(e,t){if(typeof e==="boolean"){if(e){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),e||t)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(me.exitCode??0);if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
259
259
|
Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,(i)=>{let o;if(typeof t==="function")o=t({error:i.error,command:i.command});else o=t;if(o)i.write(`${o}
|
|
260
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function w2(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",i="9229",o;if((o=t.match(/^(--inspect(-brk)?)$/))!==null)n=o[1];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=o[1],/^\d+$/.test(o[3]))i=o[3];else r=o[3];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=o[1],r=o[3],i=o[4];if(n&&i!=="0")return`${n}=${r}:${parseInt(i)+1}`;return t})}function _2(){if(me.env.NO_COLOR||me.env.FORCE_COLOR==="0"||me.env.FORCE_COLOR==="false")return!1;if(me.env.FORCE_COLOR||me.env.CLICOLOR_FORCE!==void 0)return!0;return}var eme=new lo;var oa={name:"@rainmanhhh/pi-web",version:"0.29.9",description:"Web UI for the pi coding agent (fork of @agegr/pi-web)",homepage:"https://gitee.com/dsxbygzzl/pi-web#readme",repository:{type:"git",url:"git+https://gitee.com/dsxbygzzl/pi-web.git"},bugs:{url:"https://gitee.com/dsxbygzzl/pi-web/issues"},author:"rainmanhhh",license:"MIT",publishConfig:{access:"public",registry:"https://registry.npmjs.org"},engines:{node:">=24.0.0"},files:["dist","public","extensions","package.json"],bin:{"pi-web":"dist/server.mjs"},scripts:{dev:"vite","dev:lan":"vite --host 0.0.0.0",mb:"bun run --env-file=.env.manual api",mf:"bun run --env-file=.env.manual dev -- --port 3001",api:"bun run server/main.ts","api:node":"bun run build:server && node dist/server.mjs","build:server":'bun build server/main.ts --target node --outfile dist/server.mjs --minify --external "@earendil-works/*" --define "process.env.PI_WEB_PACKAGED=1"',"e2e:stop":"bun run scripts/e2e-stop.mjs","e2e:prepare":"bun run scripts/e2e-prepare.mjs",build:"vite build && bun run scripts/prune-fonts.mjs","build:analyze":"vite build --config scripts/analyze-bundle.config.ts && bun run scripts/prune-fonts.mjs",lint:"oxlint --fix",fta:"bun scripts/fta-gate.mjs . --output-limit 15",jscpd:"jscpd --config .jscpd.json",check:"tsc --noEmit",format:"biome check --write .",prepublishOnly:"bun run check && bun run build && bun run build:server","test:e2e":"cross-env CODEBUDDY_SAFE_DELETE_ENABLED=0 bun run e2e:stop && playwright test","test:unit":"vitest run","test:unit:bun":"bun --bun run test:unit",prepare:"husky || true"},dependencies:{"@codemirror/commands":"^6.11.0","@codemirror/lang-css":"^6.3.1","@codemirror/lang-html":"^6.4.12","@codemirror/lang-javascript":"^6.2.5","@codemirror/lang-json":"^6.0.2","@codemirror/lang-markdown":"^6.5.2","@codemirror/lang-yaml":"^6.1.3","@codemirror/language":"^6.12.4","@codemirror/state":"^6.7.1","@codemirror/theme-one-dark":"^6.1.3","@codemirror/view":"^6.43.9","@earendil-works/pi-agent-core":"1.2.0","@earendil-works/pi-ai":"1.2.0","@earendil-works/pi-coding-agent":"1.2.0","@earendil-works/pi-codemode":"1.2.0","@earendil-works/pi-tui":"1.2.0","@hono/node-server":"^2.1.1","class-variance-authority":"^0.7.1",clsx:"^2.1.1",codemirror:"^6.0.2",hono:"^4.13.5","lucide-react":"^1.37.0","p-defer":"^4.0.1",pointrix:"^1.1.0","proper-lockfile":"4.1.2","radix-ui":"^1.6.7",react:"^19.2.8","react-dom":"^19.2.8",shadcn:"^4.19.0",streamdown:"2.6.0","tailwind-merge":"^3.6.0","tw-animate-css":"^1.4.0",virtua:"^0.50.6",ws:"^8.21.3"},devDependencies:{"@biomejs/biome":"^2.5.13","@lobehub/icons":"^5.16.0","@playwright/test":"^1.62.1","@tailwindcss/postcss":"^4.3.3","@testing-library/dom":"^10.4.1","@testing-library/react":"^16.3.3","@types/node":"^25.9.5","@types/proper-lockfile":"4.1.4","@types/react":"^19.2.18","@types/react-dom":"^19.2.5","@types/react-resizable":"^4.0.0","@types/react-syntax-highlighter":"^15.5.13","@types/ws":"^8.18.1","@vitejs/plugin-react":"^6.1.1",commander:"^15.0.0","cross-env":"^10.1.0","fta-cli":"^3.0.1",husky:"^9.1.7",jiti:"^2.7.0",jscpd:"^5.1.0",jsdom:"^30.0.1",katex:"^0.18.4","lint-staged":"^17.4.1",mammoth:"^1.12.2",mermaid:"^11.17.2",oxlint:"^1.80.0",postcss:"^8.5.26","react-markdown":"^10.1.0","react-syntax-highlighter":"^16.1.1","rehype-katex":"^7.0.1","rehype-raw":"^7.0.0","rehype-sanitize":"^6.0.0","remark-gfm":"^4.0.1","remark-math":"^6.0.0",tailwindcss:"^4.3.3",typescript:"^7.0.2",vite:"^8.2.2","vite-plugin-remove-console":"^2.2.0","vite-plugin-svgr":"^5.2.0",vitest:"^4.1.11"},type:"module",overrides:{katex:"^0.18.4"}};var gh=!1,D2=performance.now();function S2(e){if(gh=e,D2=performance.now(),gh)Qe("boot","debug log enabled")}function ze(e){return(t,n)=>Qe(e,t,n)}function Qe(e,t,n){if(!gh)return;let r=performance.now()-D2,i=new Date,o=(a,c=2)=>String(a).padStart(c,"0"),s=`${o(i.getHours())}:${o(i.getMinutes())}:${o(i.getSeconds())}.${o(i.getMilliseconds(),3)}`;console.debug(`[debug][${e}][${s}][+${r.toFixed(1)}ms] ${t}${n?` — ${n}`:""}`)}import{existsSync as jN,mkdirSync as qN,readFileSync as q2,writeFileSync as $N}from"node:fs";import{dirname as HN,join as $2}from"node:path";import{getAgentDir as H2}from"@earendil-works/pi-coding-agent";var C2=[{label:{en:"Explore project","zh-CN":"阅读项目"},message:{en:"Explore the current project and summarize the overall directory structure and responsibilities of core modules.","zh-CN":"阅读当前项目,总结整体目录结构与核心模块的职责。"}},{label:{en:"Review workspace changes","zh-CN":"审查工作区改动"},message:{en:"Review all changes in the current workspace, point out potential issues and improvements.","zh-CN":"审查当前工作区的所有改动,指出潜在问题与改进点。"}},{label:{en:"Find and fix bugs","zh-CN":"寻找并修复bug"},message:{en:"Inspect the current codebase, find and fix existing bugs.","zh-CN":"检查当前代码,寻找并修复其中存在的 bug。"}}];var A2=C2;import{mkdirSync as R2,readFileSync as Wu,writeFileSync as F2}from"node:fs";import{dirname as P2,join as O2}from"node:path";import{getAgentDir as WN}from"@earendil-works/pi-coding-agent";var sa=["off","minimal","low","medium","high","xhigh","max"];var LN=["off","minimal","low","medium","high"];function yh(e){let t={...e??{}};for(let n of LN)if(!(n in t))t[n]=n;return t}function Mu(e){if(!e.reasoning)return;let t=yh(e.thinkingLevelMap);return sa.find((n)=>typeof t[n]==="string")??"low"}function Nu(e){return e==="en"||e==="zh-CN"?e:void 0}function vh(e){return e==="dark"||e==="light"?e:void 0}function xh(e){return typeof e==="string"&&sa.includes(e)?e:void 0}function wh(e){if(typeof e!=="object"||e===null)return;let t=e;if(typeof t.enabled!=="boolean")return;if(typeof t.reserveTokens!=="number"||!Number.isInteger(t.reserveTokens)||t.reserveTokens<=0)return;if(typeof t.keepRecentTokens!=="number"||!Number.isInteger(t.keepRecentTokens)||t.keepRecentTokens<=0)return;return{enabled:t.enabled,reserveTokens:t.reserveTokens,keepRecentTokens:t.keepRecentTokens}}function BN(e){if(typeof e!=="object"||e===null)return;let t=e,n={};if(typeof t.timeoutMs==="number"&&Number.isInteger(t.timeoutMs)&&t.timeoutMs>0)n.timeoutMs=t.timeoutMs;if(typeof t.maxRetries==="number"&&Number.isInteger(t.maxRetries)&&t.maxRetries>0)n.maxRetries=t.maxRetries;if(typeof t.maxRetryDelayMs==="number"&&Number.isInteger(t.maxRetryDelayMs)&&t.maxRetryDelayMs>0)n.maxRetryDelayMs=t.maxRetryDelayMs;return Object.keys(n).length>0?n:void 0}function _h(e){if(typeof e!=="object"||e===null)return;let t=e;if(typeof t.maxRetries!=="number"||!Number.isInteger(t.maxRetries)||t.maxRetries<=0)return;if(typeof t.baseDelayMs!=="number"||!Number.isInteger(t.baseDelayMs)||t.baseDelayMs<=0)return;let n={maxRetries:t.maxRetries,baseDelayMs:t.baseDelayMs};if(typeof t.enabled==="boolean")n.enabled=t.enabled;let r=BN(t.provider);if(r!==void 0)n.provider=r;return n}function Lu(e){if(e==="ask"||e==="always"||e==="never")return e;if(e==="trust")return"always";if(e==="deny")return"never";return}function Bu(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0.85&&e<=1.3?e:void 0}var aa=(e)=>typeof e==="boolean"?e:void 0,bh=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0,k2=(e)=>typeof e==="string"&&e.trim()!==""?e:void 0;function U2(e,t){if(typeof e!=="object"||e===null)return;let n=e,r={};for(let[i,o]of Object.entries(t)){let s=o(n[i]);if(s!==void 0)r[i]=s}return Object.keys(r).length>0?r:void 0}var Xn=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"&&t.length>0)?e:void 0,Dh=[{key:"defaultTools",validate:Xn},{key:"httpProxy",validate:k2},{key:"httpIdleTimeoutMs",validate:bh},{key:"websocketConnectTimeoutMs",validate:bh},{key:"enableAnalytics",validate:aa},{key:"enableInstallTelemetry",validate:aa},{key:"trackingId",validate:k2},{key:"branchSummary",validate:(e)=>U2(e,{reserveTokens:bh,skipPrompt:aa})},{key:"images",validate:(e)=>U2(e,{autoResize:aa,blockImages:aa})}];function Sh(e){return wh(Kn("compaction",e))}function I2(e,t){let n=wh(e);if(!n)return Sh(t);return fo("compaction",n,t),n}function Eh(e){return _h(Kn("retry",e))}function M2(e,t){let n=_h(e);if(!n)return Eh(t);return fo("retry",n,t),n}function Kn(e,t){try{return JSON.parse(Wu(B2(t),"utf8"))[e]}catch{return}}function fo(e,t,n){try{let r=B2(n),i={};try{i=JSON.parse(Wu(r,"utf8"))}catch{i={}}if(t===void 0)delete i[e];else i[e]=t;R2(P2(r),{recursive:!0}),F2(r,JSON.stringify(i,null,2),"utf8")}catch{}}function N2(e){return O2(e,".pi","settings.json")}function ju(e,t){try{return JSON.parse(Wu(N2(e),"utf8"))[t]}catch{return}}function L2(e,t,n){try{let r=N2(e),i={};try{i=JSON.parse(Wu(r,"utf8"))}catch{i={}}if(n===void 0)delete i[t];else i[t]=n;R2(P2(r),{recursive:!0}),F2(r,JSON.stringify(i,null,2),"utf8")}catch{}}function po(e,t){let n=Kn(e,t);return typeof n==="string"?n:void 0}function qu(e,t,n){if(t===void 0)return po(e,n);return fo(e,t,n),t}function B2(e){return O2(e??WN(),"settings.json")}function ca(e){return vh(po("theme",e))??"light"}function W2(e,t){let n=vh(e);if(!n)return ca(t);return qu("theme",n,t),n}function $u(e){let t={};for(let{key:n,validate:r}of Dh){let i=r(Kn(n,e));if(i!==void 0)t[n]=i}return Object.keys(t).length>0?t:void 0}function j2(e,t){for(let{key:n,validate:r}of Dh){if(!(n in e))continue;let i=r(e[n]);if(i===void 0)continue;fo(n,i,t)}return $u(t)}var Hu=new Map;function Th(e){return $2(e??H2(),"pi-web","config.json")}function GN(e){return $2(e??H2(),"pi-web-preferences.json")}function Ch(e){try{if(jN(Th(e)))return;let t=JSON.parse(q2(GN(e),"utf8"));Ah({firstPaint:{locale:Nu(t.firstPaint?.locale),fontScale:Bu(t.firstPaint?.fontScale)},preferences:t.preferences??{}},e)}catch{}}function zN(e){let t=xh(po("defaultThinkingLevel",e)),n=Sh(e),r=Eh(e),i=Lu(po("defaultProjectTrust",e)),o=$u(e);return{theme:ca(e),...t!==void 0?{defaultThinkingLevel:t}:{},...n!==void 0?{compaction:n}:{},...r!==void 0?{retry:r}:{},...i!==void 0?{defaultProjectTrust:i}:{},...o!==void 0?{piSettings:o}:{}}}function Zn(e){let t=e===void 0,n=e??"",r=t?Hu.get(n):void 0;if(!t||r===void 0||r===null)try{let i=q2(Th(e),"utf8"),o=JSON.parse(i);r={firstPaint:{locale:Nu(o.firstPaint?.locale),fontScale:Bu(o.firstPaint?.fontScale)},preferences:o.preferences??{},theme:ca(e)},Hu.set(n,r)}catch{if(r={firstPaint:{},preferences:{},theme:ca(e)},t)Hu.set(n,r)}return{...r,...zN(e)}}function Ah(e,t){try{let n=Th(t);qN(HN(n),{recursive:!0});let r={firstPaint:e.firstPaint,preferences:e.preferences};if($N(n,JSON.stringify(r,null,2),"utf8"),t===void 0)Hu.set("",e)}catch{}}function VN(e,t){return{...e,...t.locale!==void 0?{locale:Nu(t.locale)??e.locale}:{},...t.fontScale!==void 0?{fontScale:Bu(t.fontScale)??e.fontScale}:{}}}function XN(e,t){if(e===void 0)return Lu(po("defaultProjectTrust",t));let n=Lu(e);if(n===void 0)return;return qu("defaultProjectTrust",n,t),n}function kh(e,t){let n=Zn(t),r=VN(n.firstPaint,e),i=n.theme;if(e.theme!==void 0)i=W2(e.theme,t);let o=qu("defaultThinkingLevel",xh(e.defaultThinkingLevel),t),s=I2(e.compaction,t),a=M2(e.retry,t),c=XN(e.defaultProjectTrust,t),u=e.piSettings===void 0?$u(t):j2(e.piSettings,t),d={firstPaint:r,preferences:n.preferences,theme:i,defaultThinkingLevel:o,...s!==void 0?{compaction:s}:{},...a!==void 0?{retry:a}:{},...c!==void 0?{defaultProjectTrust:c}:{},...u!==void 0?{piSettings:u}:{}};return Ah(d,t),d}function Gu(e,t){let n=Zn(t),r={firstPaint:n.firstPaint,preferences:{...n.preferences,...e},theme:n.theme};return Ah(r,t),r}function Uh(e){let{preferences:t}=Zn(e);if(t.startScreenMessages!==void 0)return;Gu({startScreenMessages:A2},e)}import{DefaultResourceLoader as cL,getAgentDir as Y2}from"@earendil-works/pi-coding-agent";import{hasTrustRequiringProjectResources as KN,ProjectTrustStore as Rh}from"@earendil-works/pi-coding-agent";function Oe(e,t){if(!(Boolean(e)&&KN(e)))return{requiresTrust:!1,trusted:!0};return{requiresTrust:!0,trusted:new Rh(t).get(e)===!0}}function G2(e,t){let n=Oe(e,t);if(!n.requiresTrust)return n;return new Rh(t).set(e,!0),{requiresTrust:!0,trusted:!0}}function ho(e,t){if(!Oe(e,t).requiresTrust)return;let r=new Rh(t);return{resolveProjectTrust:async()=>r.get(e)===!0}}import{existsSync as ZN,readFileSync as YN}from"node:fs";import{homedir as JN}from"node:os";import{isAbsolute as QN,join as ua,relative as eL,resolve as z2,sep as tL}from"node:path";function nL({homeDir:e=JN(),xdgStateHome:t=process.env.XDG_STATE_HOME}={}){return t?ua(t,"skills",".skill-lock.json"):ua(e,".agents",".skill-lock.json")}function V2(e){try{let t=JSON.parse(YN(e,"utf8"));return t.skills&&typeof t.skills==="object"?t.skills:{}}catch{return{}}}function X2(e,t){let n=eL(z2(t),z2(e));return n!==""&&n!==".."&&!n.startsWith(`..${tL}`)&&!QN(n)}function rL(e,t){if(e[t])return e[t];let n=t.toLowerCase(),r=Object.keys(e).find((i)=>i.toLowerCase()===n);return r?e[r]:void 0}function iL(e,t){if(t!=="github")return e.replace(/\/$/,"");return e.replace(/^git\+/,"").replace(/^https?:\/\/github\.com\//,"").replace(/^git@github\.com:/,"").replace(/\.git$/,"").replace(/\/$/,"")}function oL(e,t){if(!e||e.includes("://")||e.startsWith("git@"))return;let n=e.split("/").filter(Boolean).map(encodeURIComponent).join("/");if(!n)return;return`https://skills.sh/${n}/${encodeURIComponent(t)}`}function sL(e,t){let n=typeof e.sourceType==="string"?e.sourceType:void 0,r=iL(e.source.trim(),n),i=typeof e.skillPath==="string"?e.skillPath:void 0,o=typeof e.ref==="string"?e.ref:void 0,s=t==="global"?e.skillFolderHash:e.computedHash;return{sourceType:n,source:r,skillPath:i,ref:o,versionHash:typeof s==="string"&&s?s:void 0}}function aL(e,t){let{sourceType:n,source:r,skillPath:i,versionHash:o,ref:s}=e,a=n==="github"&&/^[\w.-]+\/[\w.-]+$/.test(r);return Boolean(a&&i&&o&&(t==="global"||!s))}function K2(e,t,n){let r=rL(e,t);if(!r||typeof r.source!=="string"||!r.source.trim())return;let{sourceType:i,source:o,skillPath:s,ref:a,versionHash:c}=sL(r,n);if(!o)return;return{package:`${o}@${t}`,scope:n,source:o,sourceType:i,skillsShUrl:i==="local"?void 0:oL(o,t),...s&&{skillPath:s},...a&&{ref:a},...c&&{versionHash:c},canCheckForUpdates:aL({sourceType:i,source:o,skillPath:s,versionHash:c,ref:a},n)}}function Z2(e,{cwd:t,agentDir:n,globalLockPath:r=nL(),projectLockPath:i=ua(t,"skills-lock.json")}){let o=V2(r),s=V2(i),a=ua(n,"skills"),c=ua(t,".pi","skills");return e.map((u)=>{if(!ZN(u.filePath))return u;let d=X2(u.filePath,a)?K2(o,u.name,"global"):X2(u.filePath,c)?K2(s,u.name,"project"):void 0;return d?{...u,install:d}:u})}var uL=32,gi=new Map,Fh=new Map;async function cn(e,t){let n=t?.forceFresh??!1,r=e===""?Y2():e;if(!n){let s=gi.get(e);if(s)return{skills:[...s.skills.values()],diagnostics:s.diagnostics,projectResourcesLoaded:s.projectResourcesLoaded}}let i=Fh.get(e);if(i)return i;let o=lL(r,e);Fh.set(e,o);try{return await o}finally{Fh.delete(e)}}async function lL(e,t){let n=Y2(),r=new cL({cwd:e,agentDir:n});await r.reload(ho(e,n));let{skills:i,diagnostics:o}=r.getSkills(),s={skills:Z2(i,{cwd:e,agentDir:n}),diagnostics:o,projectResourcesLoaded:Oe(e,n).trusted},a=new Map;for(let c of s.skills)a.set(c.filePath,c);return gi.set(t,{skills:a,diagnostics:s.diagnostics,projectResourcesLoaded:s.projectResourcesLoaded,loadedAt:Date.now()}),dL(),s}function dL(){while(gi.size>uL){let e=null,t=1/0;for(let[n,r]of gi){if(n==="")continue;if(r.loadedAt<t)t=r.loadedAt,e=n}if(e===null)break;gi.delete(e)}}function J2(e,t,n){let r=gi.get(e);if(!r)return;let i=r.skills.get(t);if(!i){gi.delete(e);return}if(n.disableModelInvocation!==void 0)i.disableModelInvocation=n.disableModelInvocation}var zu=null;function Q2(e){if(zu)return;let t=(async()=>{for(let n of e)await Promise.allSettled([n()])})();zu=t,t.then(()=>{zu=null})}function _n(){return zu??Promise.resolve()}var e1={port:31415};import{getAgentDir as lpe}from"@earendil-works/pi-coding-agent";var Ph=(e,t,n)=>(r,i)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw Error("next() called multiple times");o=a;let c,u=!1,d;if(e[a])d=e[a][0][0],r.req.routeIndex=a;else d=a===e.length&&i||void 0;if(d)try{c=await d(r,()=>s(a+1))}catch(f){if(f instanceof Error&&t)r.error=f,c=await t(f,r),u=!0;else throw f}else if(r.finalized===!1&&n)c=await n(r);if(c&&(r.finalized===!1||u))r.res=c;return r}};var t1=Symbol();var n1=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var r1=32,fL=1e4,Vu=(e)=>("headers"in e),s1=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,s=(Vu(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(s==="multipart/form-data"||s==="application/x-www-form-urlencoded")return pL(e,{all:n,dot:r});return{}};async function pL(e,t){if(!Vu(e)&&e.bodyCache.formData)return i1(await e.bodyCache.formData,t);let n=Vu(e)?e.headers:e.raw.headers,r=await e.arrayBuffer(),i=n1(r,n.get("Content-Type")||"");if(!Vu(e))e.bodyCache.formData=i;let o=await i;if(o)return i1(o,t);return{}}function i1(e,t){let n=Object.create(null),r={count:0};if(e.forEach((i,o)=>{if(!(t.all||o.endsWith("[]")))n[o]=i;else hL(n,o,i)}),t.dot)Object.entries(n).forEach(([i,o])=>{if(i.includes("."))gL(n,i,o,r),delete n[i]});return n}var hL=(e,t,n)=>{if(e[t]!==void 0)if(Array.isArray(e[t]))e[t].push(n);else e[t]=[e[t],n];else if(!t.endsWith("[]"))e[t]=n;else e[t]=[n]},gL=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,o=t.split(".",r1+2);if(o.length>r1+1)o1();o.forEach((s,a)=>{if(a===o.length-1)i[s]=n;else{if(!i[s]||typeof i[s]!=="object"||Array.isArray(i[s])||i[s]instanceof File){if(r.count++>=fL)o1();i[s]=Object.create(null)}i=i[s]}})},o1=()=>{throw Error("Nesting limit exceeded")};mi();var h1=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#o()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&Zu(n)}#o(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let r=this.#i(this.#t[0][this.routeIndex][1][n]);if(r!==void 0)e[n]=Zu(r)}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return f1(this.url,e)}queries(e){return p1(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((n,r)=>{t[r]=n}),t}async parseBody(e){return s1(this,e)}#r=(e)=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let i in t)return t[i].then((o)=>{if(i==="json")o=JSON.stringify(o);return new Response(o)[e]()});return t[e]=n[e]()};json(){return this.#r("text").then((e)=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}bytes(){return this.#r("arrayBuffer").then((e)=>new Uint8Array(e))}blob(){return this.#r("blob")}formData(){return this.#r("formData")}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t1](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};Bh();var vL="text/plain; charset=UTF-8",Wh=(e,t)=>({"Content-Type":e,...t}),la=(e,t)=>new Response(e,t),jh=class{#e;#t;env={};#n;finalized=!1;error;#o;#i;#r;#c;#s;#a;#l;#d;#f;constructor(e,t){if(this.#e=e,t)this.#i=t.executionCtx,this.env=t.env,this.#a=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult}get req(){return this.#t??=new h1(this.#e,this.#f,this.#d),this.#t}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;else throw Error("This context has no ExecutionContext")}get res(){return this.#r||=la(null,{headers:this.#l??=new Headers})}set res(e){if(this.#r&&e){e=la(e.body,e);for(let[t,n]of this.#r.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let i of r)e.headers.append("set-cookie",i)}else e.headers.set(t,n)}}this.#r=e,this.finalized=!0}render=(...e)=>(this.#s??=(t)=>this.html(t),this.#s(...e));setLayout=(e)=>this.#c=e;getLayout=()=>this.#c;setRenderer=(e)=>{this.#s=e};header=(e,t,n)=>{if(this.finalized)this.#r=la(this.#r.body,this.#r);let r=this.#r?this.#r.headers:this.#l??=new Headers;if(t===void 0)r.delete(e);else if(n?.append)r.append(e,t);else r.set(e,t)};status=(e)=>{this.#o=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=(e)=>this.#n?this.#n.get(e):void 0;get var(){if(!this.#n)return{};return Object.fromEntries(this.#n)}#u(e,t,n){let r=this.#r?new Headers(this.#r.headers):this.#l;if(typeof t==="object"&&t.headers){r??=new Headers;for(let[o,s]of new Headers(t.headers))if(o==="set-cookie")r.append(o,s);else r.set(o,s)}if(n){if(!r){let o=0;for(let s in n)if(++o>1||typeof n[s]!=="string"){r=new Headers;break}}if(r)for(let o in n){let s=n[o];if(typeof s==="string")r.set(o,s);else{r.delete(o);for(let a of s)r.append(o,a)}}}let i=typeof t==="number"?t:t?.status??this.#o;return la(e,{status:i,headers:r??n})}newResponse=(...e)=>this.#u(...e);body=(e,t,n)=>this.#u(e,t,n);text=(e,t,n)=>!this.#l&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#u(e,t,Wh(vL,n));json=(e,t,n)=>this.#u(JSON.stringify(e),t,Wh("application/json",n));html=(e,t,n)=>{let r=(i)=>this.#u(i,t,Wh("text/html; charset=UTF-8",n));return typeof e==="object"?Lh(e,g1.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(n)?n:encodeURI(n)),this.newResponse(null,t??302)};notFound=()=>(this.#a??=()=>la(),this.#a(this))};Er();qh();mi();var xL=(e)=>e.text("404 Not Found",404),v1=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},x1=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...b1,y1].forEach((o)=>{this[o]=(s,...a)=>{if(typeof s==="string")this.#e=s;else this.#o(o,this.#e,s);return a.forEach((c)=>{this.#o(o,this.#e,c)}),this}}),this.on=(o,s,...a)=>{for(let c of[s].flat()){this.#e=c;for(let u of[o].flat())a.map((d)=>{this.#o(u.toUpperCase(),this.#e,d)})}return this},this.use=(o,...s)=>{if(typeof o==="string")this.#e=o;else this.#e="*",s.unshift(o);return s.forEach((a)=>{this.#o(Xe,this.#e,a)}),this};let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??Nh:l1}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=xL;errorHandler=v1;route(t,n){let r=this.basePath(t);return n.routes.map((i)=>{let o;if(n.errorHandler===v1)o=i.handler;else o=async(s,a)=>(await Ph([],n.errorHandler)(s,()=>i.handler(s,a))).res,o[da]=i.handler;r.#o(i.method,i.path,o,i.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=Sr(this._basePath,t),n}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#n=t,this);mount(t,n,r){let i,o;if(r)if(typeof r==="function")o=r;else if(o=r.optionHandler,r.replaceRequest===!1)i=(c)=>c;else i=r.replaceRequest;let s=o?(c)=>{let u=o(c);return Array.isArray(u)?u:[u]}:(c)=>{let u=void 0;try{u=c.executionCtx}catch{}return[c.env,u]};i||=(()=>{let c=Sr(this._basePath,t),u=c==="/"?0:c.length;return(d)=>{let f=new URL(d.url);return f.pathname=this.getPath(d).slice(u)||"/",new Request(f,d)}})();let a=async(c,u)=>{let d=await n(i(c.req.raw),...s(c));if(d)return d;await u()};return this.#o(Xe,Sr(t,"*"),a),this}#o(t,n,r,i){t=t.toUpperCase(),n=Sr(this._basePath,n);let o={basePath:i!==void 0?Sr(this._basePath,i):this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,o]),this.routes.push(o)}#i(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,i){if(i==="HEAD")return(async()=>new Response(null,await this.#r(t,n,r,"GET")))();let o=this.getPath(t,{env:r}),s=this.router.match(i,o),a=new jh(t,{path:o,matchResult:s,env:r,executionCtx:n,notFoundHandler:this.#n});if(s[0].length===1){let u;try{u=s[0][0][0][0](a,async()=>{a.res=await this.#n(a)})}catch(d){return this.#i(d,a)}return u instanceof Promise?u.then((d)=>d||(a.finalized?a.res:this.#n(a))).catch((d)=>this.#i(d,a)):u??this.#n(a)}let c=Ph(s[0],this.errorHandler,this.#n);return(async()=>{try{let u=await c(a);if(!u.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#i(u,a)}})()}fetch=(t,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,i)=>{if(t instanceof Request)return this.fetch(n?new Request(t,n):t,r,i);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Sr("/",t)}`,n),r,i)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};Er();mi();var et=()=>Object.create(null);Er();var Qu=[];function $h(e,t){let n=this.buildAllMatchers(),r=(i,o)=>{let s=n[i]||n[Xe],a=s[2][o];if(a)return a;let c=o.match(s[0]);if(!c)return[[],Qu];let u=c.indexOf("",1);return[s[1][u],c]};return this.match=r,r(e,t)}var go="[^/]+",Cr=".*",Yn="(?:|/.*)",Tr=Symbol(),w1=new Set(".\\+*[^]$()");function wL(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===Cr||e===Yn)return t===Yn?-1:1;else if(t===Cr||t===Yn)return-1;if(e===go)return 1;else if(t===go)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var _1=class e{#e;#t;#n=et();insert(t,n,r,i,o){let s=this;for(let a=0,c=t.length;a<c;a++){let u=t[a],d=u.length===1?u==="*"?a===c-1?["","",Cr]:["","",go]:null:u==="/*"?["","",Yn]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),f;if(d){let p=d[1],h=d[2]||go;if(p&&d[2]){if(h===".*")throw Tr;if(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))throw Tr;if(h.length===1&&w1.has(h))throw Tr}if(f=s.#n[h],!f){if(h!==Cr&&h!==Yn){for(let g in s.#n)if((h.length>1||g.length>1)&&g!==Cr&&g!==Yn)throw Tr}f=s.#n[h]=new e}if(p!=="")f.#t??=i.varIndex++,r.push([p,f.#t])}else if(f=s.#n[u],!f){for(let p in s.#n)if(p.length>1&&p!==Cr&&p!==Yn)throw Tr;f=s.#n[u]=new e}s=f}if(s.#e!==void 0)throw Tr;s.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(wL).map((r)=>{let i=this.#n[r],o=i.buildRegExpStr();return o===""?"":(typeof i.#t==="number"?`(${r})@${i.#t}`:w1.has(r)?`\\${r}`:r)+o}).filter(Boolean);if(typeof this.#e==="number"&&this.#e!==-1)n.unshift(`#${this.#e}`);if(n.length===0)return"";if(n.length===1)return n[0];return"(?:"+n.join("|")+")"}};var Hh=class{#e={varIndex:0};#t=new _1;#n=0;paths=et();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let s=0;;){let a=!1;if(i=i.replace(/\{[^}]+\}/g,(c)=>{let u=`@\\${s}`;return r[s]=[u,c],s++,a=!0,u}),!a)break}let o=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=r.length-1;s>=0;s--){let[a]=r[s];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,r[s][1]);break}}this.#t.insert(o,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,o,s)=>{if(o!==void 0)return n[++t]=Number(o),"$()";if(s!==void 0)return r[Number(s)]=++t,"";return""}),[new RegExp(`^${e}`),n,r]}};var D1=et();function S1(e){return D1[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?Yn:t==="*"?Cr:`/:${go}`)}$`)}function el(e,t){for(let n of Object.keys(e).sort((r,i)=>i.length-r.length))if(S1(n).test(t))return[...e[n]];return}var tl=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[Xe]:et()},this.#t={[Xe]:et()},this.#n={[Xe]:new Hh}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===Tr?new Ju(t):n}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(Yu);if(!r[e]){this.#n[e]=new Hh;for(let a of[r,i]){a[e]=et();for(let c in a[Xe])a[e][c]=[...a[Xe][c]],this.#o(e,c)}}if(t==="/*")t="*";let o=e===Xe?Object.keys(r):[e];if(/\*$/.test(t)){let a=S1(t);for(let c of o)if(!r[c][t])this.#o(c,t),r[c][t]=el(r[c],t)||el(r[Xe],t)||[];for(let c of[r,i])for(let u of o)for(let d in c[u])a.test(d)&&c[u][d].push([n,t]);return}let s=Ku(t)||[t];for(let a of s)for(let c of o){if(!i[c][a])this.#o(c,a),i[c][a]=el(r[c],a)||el(r[Xe],a)||[];i[c][a].push([n,a])}}match=$h;buildAllMatchers(){let e=et();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,D1=et(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=et(),o=[],[s,a,c]=r.buildRegExp();for(let u of[t,n])for(let d in u){let f=u[d],p=r.paths[d];if(!p){i[d]=[f.map(([h])=>[h,et()]),Qu];continue}o[p[0]]=f.map(([h,g])=>[h,r.paths[g][1].reduceRight((b,[v],y)=>(b[v]=c[p[1][y][1]],b),et())])}return[s,a.map((u)=>o[u]),i]}};Er();Er();var Gh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(Yu);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error("Fatal error");let n=this.#e,r=this.#t,i=n.length,o=0,s;for(;o<i;o++){let a=n[o];try{for(let c=0,u=r.length;c<u;c++)a.add(...r[c]);s=a.match(e,t)}catch(c){if(c instanceof Ju)continue;throw c}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(o===i)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error("No active router has been determined yet.");return this.#e[0]}};mi();Er();mi();var zh=et(),_L=0,E1=class e{#e=[];#t=et();#n=[];#o;#i=zh;insert(t,n,r){let i=this,o=a1(n),s=new Set,a=0;for(let c of o){let u=o[++a],d=c1(c,u)||(u===void 0&&c&&c.indexOf("*")===c.length-1?c:null),f=Array.isArray(d),p=f?d[0]:d||c,h=i.#t[p]||=new e;if(d&&!h.#o)h.#o=d,i.#n.push(h);if(i=h,f)s.add(d[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...s],score:++_L}})}#r(t,n,r,i,o){for(let s=0,a=n.#e.length;s<a;s++){let c=n.#e[s],u=c[r]||c[Xe];if(u){u.params=et(),t.push(u);for(let d=0,f=u.possibleKeys.length;d<f;d++){let p=u.possibleKeys[d];u.params[p]=o?.[p]&&!d?o[p]:i[p]??o?.[p]}}}}search(t,n){let r=[];this.#i=zh;let o=[this],s=Ih(n),a=[],c=s.length,u=null;for(let d=0;d<c;d++){let f=s[d],p=d===c-1,h=[];for(let b=0,v=o.length;b<v;b++){let y=o[b],x=y.#t[f];if(x)if(x.#i=y.#i,p){if(x.#t["*"])this.#r(r,x.#t["*"],t,y.#i);this.#r(r,x,t,y.#i)}else h.push(x);for(let m of y.#n){let w=m.#o,D=y.#i===zh?{}:{...y.#i};if(typeof w==="string"){if(w==="*"||f.startsWith(w.slice(0,-1))){if(this.#r(r,m,t,y.#i),w==="*")m.#i=D,h.push(m)}continue}let[,T,_]=w;if(!f&&_===!0)continue;if(_!==!0){if(!u){u=[];let M=n[0]==="/"?1:0;for(let P=0;P<c;P++)u[P]=M,M+=s[P].length+1}let A=n.slice(u[d]),E=_.exec(A);if(E){if(D[T]=E[0],this.#r(r,m,t,y.#i,D),E[0].length===A.length&&m.#t["*"])this.#r(r,m.#t["*"],t,y.#i,D);for(let M in m.#t){m.#i=D;let P=E[0].match(/\//g)?.length??0;(a[P]||=[]).push(m);break}continue}}if(_===!0||_.test(f))if(D[T]=f,p){if(this.#r(r,m,t,D,y.#i),m.#t["*"])this.#r(r,m.#t["*"],t,D,y.#i)}else m.#i=D,h.push(m)}}let g=a.shift();o=g?h.concat(g):h}if(r[1])r.sort((d,f)=>d.score-f.score);return[r.map(({handler:d,params:f})=>[d,f])]}};var Vh=class{name="TrieRouter";#e=new E1;add(e,t,n){for(let r of Ku(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}};var Xh=class extends x1{constructor(e={}){super(e);this.router=e.router??new Gh({routers:[new tl,new Vh]})}};function Kh(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}import{execFile as DL}from"node:child_process";import mo from"node:path";import{promisify as SL}from"node:util";var fa=SL(DL),nl=1e4,T1=120000,pa=8388608;async function wt(e,t,n=pa,r=nl){let{stdout:i}=await fa("git",["-C",e,...t],{timeout:r,maxBuffer:n,env:{...process.env,LC_ALL:"C"}});return i}async function Ut(e){try{return(await wt(e,["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}function yi(e,t){let n=mo.relative(mo.resolve(e),mo.resolve(t));return n===""||!n.startsWith(`..${mo.sep}`)&&n!==".."&&!mo.isAbsolute(n)}function Ar(e){return e.split(mo.sep).join("/")}function rl(e){return e.includes(0)}import{lstat as OL,readFile as IL}from"node:fs/promises";import F1 from"node:path";var bi=262144,C1=10485760,A1=10485760,EL={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},TL={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm",webm:"audio/webm"},CL={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function AL(e){return e.replace(/\\/g,"/").split("/").pop()??""}function yo(e){return AL(e).toLowerCase().split(".").pop()??""}function il(e){return EL[yo(e)]??null}function ol(e){return TL[yo(e)]??null}function sl(e){return CL[yo(e)]??null}function k1(e){let t=yo(e);if(t==="pdf"||t==="docx")return t;return null}function kL(e,t){return e==="R"||e==="C"||t==="R"||t==="C"}function U1(e){let t=e.split("\x00"),n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!i||i.length<4||i[2]!==" ")continue;let o=i[0],s=i[1],a={path:i.slice(3),indexStatus:o,worktreeStatus:s};if(kL(o,s))a.originalPath=t[++r]||void 0;n.push(a)}return n}var UL=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function al(e){let t=`${e.indexStatus}${e.worktreeStatus}`;if(t==="??")return{status:"untracked",code:"U"};if(UL.has(t)||t.includes("U"))return{status:"conflict",code:"C"};if(t.includes("D"))return{status:"deleted",code:"D"};if(t.includes("R")||t.includes("C"))return{status:"renamed",code:"R"};if(t.includes("A"))return{status:"added",code:"A"};return{status:"modified",code:"M"}}import{lstat as RL,readFile as FL}from"node:fs/promises";import Zh from"node:path";async function Yh(e){let t=await wt(e,["status","--porcelain=v1","-z","--untracked-files=all"]);return U1(t)}async function R1(e,t,n){let i=Ar(Zh.relative(e,t))||".";try{let o=await wt(e,["diff","--no-color","--no-ext-diff","--numstat",...n,"--",i]),s=new Map;for(let a of o.split(/\r?\n/)){if(!a)continue;let[c,u,...d]=a.split("\t");if(d.length===0)continue;let f=Number(c),p=Number(u);if(!Number.isInteger(f)||!Number.isInteger(p))continue;let h=d.join("\t"),g=h.indexOf(" => ");if(g!==-1)h=h.slice(g+4);s.set(Ar(h.trim()),{additions:f,deletions:p})}return s}catch{return new Map}}async function PL(e){try{let t=await RL(e);if(!t.isFile()||t.size>bi)return 0;let n=await FL(e);if(rl(n)||n.length===0)return 0;let r=n.toString("utf8");return r.endsWith(`
|
|
260
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function w2(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",i="9229",o;if((o=t.match(/^(--inspect(-brk)?)$/))!==null)n=o[1];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=o[1],/^\d+$/.test(o[3]))i=o[3];else r=o[3];else if((o=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=o[1],r=o[3],i=o[4];if(n&&i!=="0")return`${n}=${r}:${parseInt(i)+1}`;return t})}function _2(){if(me.env.NO_COLOR||me.env.FORCE_COLOR==="0"||me.env.FORCE_COLOR==="false")return!1;if(me.env.FORCE_COLOR||me.env.CLICOLOR_FORCE!==void 0)return!0;return}var eme=new lo;var oa={name:"@rainmanhhh/pi-web",version:"0.29.11",description:"Web UI for the pi coding agent (fork of @agegr/pi-web)",homepage:"https://gitee.com/dsxbygzzl/pi-web#readme",repository:{type:"git",url:"git+https://gitee.com/dsxbygzzl/pi-web.git"},bugs:{url:"https://gitee.com/dsxbygzzl/pi-web/issues"},author:"rainmanhhh",license:"MIT",publishConfig:{access:"public",registry:"https://registry.npmjs.org"},engines:{node:">=24.0.0"},files:["dist","public","extensions","package.json"],bin:{"pi-web":"dist/server.mjs"},scripts:{dev:"vite","dev:lan":"vite --host 0.0.0.0",mb:"bun run --env-file=.env.manual api",mf:"bun run --env-file=.env.manual dev -- --port 3001",api:"bun run server/main.ts","api:node":"bun run build:server && node dist/server.mjs","build:server":'bun build server/main.ts --target node --outfile dist/server.mjs --minify --external "@earendil-works/*" --define "process.env.PI_WEB_PACKAGED=1"',"e2e:stop":"bun run scripts/e2e-stop.mjs","e2e:prepare":"bun run scripts/e2e-prepare.mjs",build:"vite build && bun run scripts/prune-fonts.mjs","build:analyze":"vite build --config scripts/analyze-bundle.config.ts && bun run scripts/prune-fonts.mjs",lint:"oxlint --fix",fta:"bun scripts/fta-gate.mjs . --output-limit 15",jscpd:"jscpd --config .jscpd.json",check:"tsc --noEmit",format:"biome check --write .",prepublishOnly:"bun run check && bun run build && bun run build:server","test:e2e":"cross-env CODEBUDDY_SAFE_DELETE_ENABLED=0 bun run e2e:stop && playwright test","test:unit":"vitest run","test:unit:bun":"bun --bun run test:unit",prepare:"husky || true"},dependencies:{"@codemirror/commands":"^6.11.0","@codemirror/lang-css":"^6.3.1","@codemirror/lang-html":"^6.4.12","@codemirror/lang-javascript":"^6.2.5","@codemirror/lang-json":"^6.0.2","@codemirror/lang-markdown":"^6.5.2","@codemirror/lang-yaml":"^6.1.3","@codemirror/language":"^6.12.4","@codemirror/state":"^6.7.1","@codemirror/theme-one-dark":"^6.1.3","@codemirror/view":"^6.43.9","@earendil-works/pi-agent-core":"1.2.0","@earendil-works/pi-ai":"1.2.0","@earendil-works/pi-coding-agent":"1.2.0","@earendil-works/pi-codemode":"1.2.0","@earendil-works/pi-tui":"1.2.0","@hono/node-server":"^2.1.1","class-variance-authority":"^0.7.1",clsx:"^2.1.1",codemirror:"^6.0.2",hono:"^4.13.5","lucide-react":"^1.37.0","p-defer":"^4.0.1",pointrix:"^1.1.0","proper-lockfile":"4.1.2","radix-ui":"^1.6.7",react:"^19.2.8","react-dom":"^19.2.8",shadcn:"^4.19.0",streamdown:"2.6.0","tailwind-merge":"^3.6.0","tw-animate-css":"^1.4.0",virtua:"^0.50.6",ws:"^8.21.3"},devDependencies:{"@biomejs/biome":"^2.5.13","@lobehub/icons":"^5.16.0","@playwright/test":"^1.62.1","@tailwindcss/postcss":"^4.3.3","@testing-library/dom":"^10.4.1","@testing-library/react":"^16.3.3","@types/node":"^25.9.5","@types/proper-lockfile":"4.1.4","@types/react":"^19.2.18","@types/react-dom":"^19.2.5","@types/react-resizable":"^4.0.0","@types/react-syntax-highlighter":"^15.5.13","@types/ws":"^8.18.1","@vitejs/plugin-react":"^6.1.1",commander:"^15.0.0","cross-env":"^10.1.0","fta-cli":"^3.0.1",husky:"^9.1.7",jiti:"^2.7.0",jscpd:"^5.1.0",jsdom:"^30.0.1",katex:"^0.18.4","lint-staged":"^17.4.1",mammoth:"^1.12.2",mermaid:"^11.17.2",oxlint:"^1.80.0",postcss:"^8.5.26","react-markdown":"^10.1.0","react-syntax-highlighter":"^16.1.1","rehype-katex":"^7.0.1","rehype-raw":"^7.0.0","rehype-sanitize":"^6.0.0","remark-gfm":"^4.0.1","remark-math":"^6.0.0",tailwindcss:"^4.3.3",typescript:"^7.0.2",vite:"^8.2.2","vite-plugin-remove-console":"^2.2.0","vite-plugin-svgr":"^5.2.0",vitest:"^4.1.11"},type:"module",overrides:{katex:"^0.18.4"}};var gh=!1,D2=performance.now();function S2(e){if(gh=e,D2=performance.now(),gh)Qe("boot","debug log enabled")}function ze(e){return(t,n)=>Qe(e,t,n)}function Qe(e,t,n){if(!gh)return;let r=performance.now()-D2,i=new Date,o=(a,c=2)=>String(a).padStart(c,"0"),s=`${o(i.getHours())}:${o(i.getMinutes())}:${o(i.getSeconds())}.${o(i.getMilliseconds(),3)}`;console.debug(`[debug][${e}][${s}][+${r.toFixed(1)}ms] ${t}${n?` — ${n}`:""}`)}import{existsSync as jN,mkdirSync as qN,readFileSync as q2,writeFileSync as $N}from"node:fs";import{dirname as HN,join as $2}from"node:path";import{getAgentDir as H2}from"@earendil-works/pi-coding-agent";var C2=[{label:{en:"Explore project","zh-CN":"阅读项目"},message:{en:"Explore the current project and summarize the overall directory structure and responsibilities of core modules.","zh-CN":"阅读当前项目,总结整体目录结构与核心模块的职责。"}},{label:{en:"Review workspace changes","zh-CN":"审查工作区改动"},message:{en:"Review all changes in the current workspace, point out potential issues and improvements.","zh-CN":"审查当前工作区的所有改动,指出潜在问题与改进点。"}},{label:{en:"Find and fix bugs","zh-CN":"寻找并修复bug"},message:{en:"Inspect the current codebase, find and fix existing bugs.","zh-CN":"检查当前代码,寻找并修复其中存在的 bug。"}}];var A2=C2;import{mkdirSync as R2,readFileSync as Wu,writeFileSync as F2}from"node:fs";import{dirname as P2,join as O2}from"node:path";import{getAgentDir as WN}from"@earendil-works/pi-coding-agent";var sa=["off","minimal","low","medium","high","xhigh","max"];var LN=["off","minimal","low","medium","high"];function yh(e){let t={...e??{}};for(let n of LN)if(!(n in t))t[n]=n;return t}function Mu(e){if(!e.reasoning)return;let t=yh(e.thinkingLevelMap);return sa.find((n)=>typeof t[n]==="string")??"low"}function Nu(e){return e==="en"||e==="zh-CN"?e:void 0}function vh(e){return e==="dark"||e==="light"?e:void 0}function xh(e){return typeof e==="string"&&sa.includes(e)?e:void 0}function wh(e){if(typeof e!=="object"||e===null)return;let t=e;if(typeof t.enabled!=="boolean")return;if(typeof t.reserveTokens!=="number"||!Number.isInteger(t.reserveTokens)||t.reserveTokens<=0)return;if(typeof t.keepRecentTokens!=="number"||!Number.isInteger(t.keepRecentTokens)||t.keepRecentTokens<=0)return;return{enabled:t.enabled,reserveTokens:t.reserveTokens,keepRecentTokens:t.keepRecentTokens}}function BN(e){if(typeof e!=="object"||e===null)return;let t=e,n={};if(typeof t.timeoutMs==="number"&&Number.isInteger(t.timeoutMs)&&t.timeoutMs>0)n.timeoutMs=t.timeoutMs;if(typeof t.maxRetries==="number"&&Number.isInteger(t.maxRetries)&&t.maxRetries>0)n.maxRetries=t.maxRetries;if(typeof t.maxRetryDelayMs==="number"&&Number.isInteger(t.maxRetryDelayMs)&&t.maxRetryDelayMs>0)n.maxRetryDelayMs=t.maxRetryDelayMs;return Object.keys(n).length>0?n:void 0}function _h(e){if(typeof e!=="object"||e===null)return;let t=e;if(typeof t.maxRetries!=="number"||!Number.isInteger(t.maxRetries)||t.maxRetries<=0)return;if(typeof t.baseDelayMs!=="number"||!Number.isInteger(t.baseDelayMs)||t.baseDelayMs<=0)return;let n={maxRetries:t.maxRetries,baseDelayMs:t.baseDelayMs};if(typeof t.enabled==="boolean")n.enabled=t.enabled;let r=BN(t.provider);if(r!==void 0)n.provider=r;return n}function Lu(e){if(e==="ask"||e==="always"||e==="never")return e;if(e==="trust")return"always";if(e==="deny")return"never";return}function Bu(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0.85&&e<=1.3?e:void 0}var aa=(e)=>typeof e==="boolean"?e:void 0,bh=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0,k2=(e)=>typeof e==="string"&&e.trim()!==""?e:void 0;function U2(e,t){if(typeof e!=="object"||e===null)return;let n=e,r={};for(let[i,o]of Object.entries(t)){let s=o(n[i]);if(s!==void 0)r[i]=s}return Object.keys(r).length>0?r:void 0}var Xn=(e)=>Array.isArray(e)&&e.every((t)=>typeof t==="string"&&t.length>0)?e:void 0,Dh=[{key:"defaultTools",validate:Xn},{key:"httpProxy",validate:k2},{key:"httpIdleTimeoutMs",validate:bh},{key:"websocketConnectTimeoutMs",validate:bh},{key:"enableAnalytics",validate:aa},{key:"enableInstallTelemetry",validate:aa},{key:"trackingId",validate:k2},{key:"branchSummary",validate:(e)=>U2(e,{reserveTokens:bh,skipPrompt:aa})},{key:"images",validate:(e)=>U2(e,{autoResize:aa,blockImages:aa})}];function Sh(e){return wh(Kn("compaction",e))}function I2(e,t){let n=wh(e);if(!n)return Sh(t);return fo("compaction",n,t),n}function Eh(e){return _h(Kn("retry",e))}function M2(e,t){let n=_h(e);if(!n)return Eh(t);return fo("retry",n,t),n}function Kn(e,t){try{return JSON.parse(Wu(B2(t),"utf8"))[e]}catch{return}}function fo(e,t,n){try{let r=B2(n),i={};try{i=JSON.parse(Wu(r,"utf8"))}catch{i={}}if(t===void 0)delete i[e];else i[e]=t;R2(P2(r),{recursive:!0}),F2(r,JSON.stringify(i,null,2),"utf8")}catch{}}function N2(e){return O2(e,".pi","settings.json")}function ju(e,t){try{return JSON.parse(Wu(N2(e),"utf8"))[t]}catch{return}}function L2(e,t,n){try{let r=N2(e),i={};try{i=JSON.parse(Wu(r,"utf8"))}catch{i={}}if(n===void 0)delete i[t];else i[t]=n;R2(P2(r),{recursive:!0}),F2(r,JSON.stringify(i,null,2),"utf8")}catch{}}function po(e,t){let n=Kn(e,t);return typeof n==="string"?n:void 0}function qu(e,t,n){if(t===void 0)return po(e,n);return fo(e,t,n),t}function B2(e){return O2(e??WN(),"settings.json")}function ca(e){return vh(po("theme",e))??"light"}function W2(e,t){let n=vh(e);if(!n)return ca(t);return qu("theme",n,t),n}function $u(e){let t={};for(let{key:n,validate:r}of Dh){let i=r(Kn(n,e));if(i!==void 0)t[n]=i}return Object.keys(t).length>0?t:void 0}function j2(e,t){for(let{key:n,validate:r}of Dh){if(!(n in e))continue;let i=r(e[n]);if(i===void 0)continue;fo(n,i,t)}return $u(t)}var Hu=new Map;function Th(e){return $2(e??H2(),"pi-web","config.json")}function GN(e){return $2(e??H2(),"pi-web-preferences.json")}function Ch(e){try{if(jN(Th(e)))return;let t=JSON.parse(q2(GN(e),"utf8"));Ah({firstPaint:{locale:Nu(t.firstPaint?.locale),fontScale:Bu(t.firstPaint?.fontScale)},preferences:t.preferences??{}},e)}catch{}}function zN(e){let t=xh(po("defaultThinkingLevel",e)),n=Sh(e),r=Eh(e),i=Lu(po("defaultProjectTrust",e)),o=$u(e);return{theme:ca(e),...t!==void 0?{defaultThinkingLevel:t}:{},...n!==void 0?{compaction:n}:{},...r!==void 0?{retry:r}:{},...i!==void 0?{defaultProjectTrust:i}:{},...o!==void 0?{piSettings:o}:{}}}function Zn(e){let t=e===void 0,n=e??"",r=t?Hu.get(n):void 0;if(!t||r===void 0||r===null)try{let i=q2(Th(e),"utf8"),o=JSON.parse(i);r={firstPaint:{locale:Nu(o.firstPaint?.locale),fontScale:Bu(o.firstPaint?.fontScale)},preferences:o.preferences??{},theme:ca(e)},Hu.set(n,r)}catch{if(r={firstPaint:{},preferences:{},theme:ca(e)},t)Hu.set(n,r)}return{...r,...zN(e)}}function Ah(e,t){try{let n=Th(t);qN(HN(n),{recursive:!0});let r={firstPaint:e.firstPaint,preferences:e.preferences};if($N(n,JSON.stringify(r,null,2),"utf8"),t===void 0)Hu.set("",e)}catch{}}function VN(e,t){return{...e,...t.locale!==void 0?{locale:Nu(t.locale)??e.locale}:{},...t.fontScale!==void 0?{fontScale:Bu(t.fontScale)??e.fontScale}:{}}}function XN(e,t){if(e===void 0)return Lu(po("defaultProjectTrust",t));let n=Lu(e);if(n===void 0)return;return qu("defaultProjectTrust",n,t),n}function kh(e,t){let n=Zn(t),r=VN(n.firstPaint,e),i=n.theme;if(e.theme!==void 0)i=W2(e.theme,t);let o=qu("defaultThinkingLevel",xh(e.defaultThinkingLevel),t),s=I2(e.compaction,t),a=M2(e.retry,t),c=XN(e.defaultProjectTrust,t),u=e.piSettings===void 0?$u(t):j2(e.piSettings,t),d={firstPaint:r,preferences:n.preferences,theme:i,defaultThinkingLevel:o,...s!==void 0?{compaction:s}:{},...a!==void 0?{retry:a}:{},...c!==void 0?{defaultProjectTrust:c}:{},...u!==void 0?{piSettings:u}:{}};return Ah(d,t),d}function Gu(e,t){let n=Zn(t),r={firstPaint:n.firstPaint,preferences:{...n.preferences,...e},theme:n.theme};return Ah(r,t),r}function Uh(e){let{preferences:t}=Zn(e);if(t.startScreenMessages!==void 0)return;Gu({startScreenMessages:A2},e)}import{DefaultResourceLoader as cL,getAgentDir as Y2}from"@earendil-works/pi-coding-agent";import{hasTrustRequiringProjectResources as KN,ProjectTrustStore as Rh}from"@earendil-works/pi-coding-agent";function Oe(e,t){if(!(Boolean(e)&&KN(e)))return{requiresTrust:!1,trusted:!0};return{requiresTrust:!0,trusted:new Rh(t).get(e)===!0}}function G2(e,t){let n=Oe(e,t);if(!n.requiresTrust)return n;return new Rh(t).set(e,!0),{requiresTrust:!0,trusted:!0}}function ho(e,t){if(!Oe(e,t).requiresTrust)return;let r=new Rh(t);return{resolveProjectTrust:async()=>r.get(e)===!0}}import{existsSync as ZN,readFileSync as YN}from"node:fs";import{homedir as JN}from"node:os";import{isAbsolute as QN,join as ua,relative as eL,resolve as z2,sep as tL}from"node:path";function nL({homeDir:e=JN(),xdgStateHome:t=process.env.XDG_STATE_HOME}={}){return t?ua(t,"skills",".skill-lock.json"):ua(e,".agents",".skill-lock.json")}function V2(e){try{let t=JSON.parse(YN(e,"utf8"));return t.skills&&typeof t.skills==="object"?t.skills:{}}catch{return{}}}function X2(e,t){let n=eL(z2(t),z2(e));return n!==""&&n!==".."&&!n.startsWith(`..${tL}`)&&!QN(n)}function rL(e,t){if(e[t])return e[t];let n=t.toLowerCase(),r=Object.keys(e).find((i)=>i.toLowerCase()===n);return r?e[r]:void 0}function iL(e,t){if(t!=="github")return e.replace(/\/$/,"");return e.replace(/^git\+/,"").replace(/^https?:\/\/github\.com\//,"").replace(/^git@github\.com:/,"").replace(/\.git$/,"").replace(/\/$/,"")}function oL(e,t){if(!e||e.includes("://")||e.startsWith("git@"))return;let n=e.split("/").filter(Boolean).map(encodeURIComponent).join("/");if(!n)return;return`https://skills.sh/${n}/${encodeURIComponent(t)}`}function sL(e,t){let n=typeof e.sourceType==="string"?e.sourceType:void 0,r=iL(e.source.trim(),n),i=typeof e.skillPath==="string"?e.skillPath:void 0,o=typeof e.ref==="string"?e.ref:void 0,s=t==="global"?e.skillFolderHash:e.computedHash;return{sourceType:n,source:r,skillPath:i,ref:o,versionHash:typeof s==="string"&&s?s:void 0}}function aL(e,t){let{sourceType:n,source:r,skillPath:i,versionHash:o,ref:s}=e,a=n==="github"&&/^[\w.-]+\/[\w.-]+$/.test(r);return Boolean(a&&i&&o&&(t==="global"||!s))}function K2(e,t,n){let r=rL(e,t);if(!r||typeof r.source!=="string"||!r.source.trim())return;let{sourceType:i,source:o,skillPath:s,ref:a,versionHash:c}=sL(r,n);if(!o)return;return{package:`${o}@${t}`,scope:n,source:o,sourceType:i,skillsShUrl:i==="local"?void 0:oL(o,t),...s&&{skillPath:s},...a&&{ref:a},...c&&{versionHash:c},canCheckForUpdates:aL({sourceType:i,source:o,skillPath:s,versionHash:c,ref:a},n)}}function Z2(e,{cwd:t,agentDir:n,globalLockPath:r=nL(),projectLockPath:i=ua(t,"skills-lock.json")}){let o=V2(r),s=V2(i),a=ua(n,"skills"),c=ua(t,".pi","skills");return e.map((u)=>{if(!ZN(u.filePath))return u;let d=X2(u.filePath,a)?K2(o,u.name,"global"):X2(u.filePath,c)?K2(s,u.name,"project"):void 0;return d?{...u,install:d}:u})}var uL=32,gi=new Map,Fh=new Map;async function cn(e,t){let n=t?.forceFresh??!1,r=e===""?Y2():e;if(!n){let s=gi.get(e);if(s)return{skills:[...s.skills.values()],diagnostics:s.diagnostics,projectResourcesLoaded:s.projectResourcesLoaded}}let i=Fh.get(e);if(i)return i;let o=lL(r,e);Fh.set(e,o);try{return await o}finally{Fh.delete(e)}}async function lL(e,t){let n=Y2(),r=new cL({cwd:e,agentDir:n});await r.reload(ho(e,n));let{skills:i,diagnostics:o}=r.getSkills(),s={skills:Z2(i,{cwd:e,agentDir:n}),diagnostics:o,projectResourcesLoaded:Oe(e,n).trusted},a=new Map;for(let c of s.skills)a.set(c.filePath,c);return gi.set(t,{skills:a,diagnostics:s.diagnostics,projectResourcesLoaded:s.projectResourcesLoaded,loadedAt:Date.now()}),dL(),s}function dL(){while(gi.size>uL){let e=null,t=1/0;for(let[n,r]of gi){if(n==="")continue;if(r.loadedAt<t)t=r.loadedAt,e=n}if(e===null)break;gi.delete(e)}}function J2(e,t,n){let r=gi.get(e);if(!r)return;let i=r.skills.get(t);if(!i){gi.delete(e);return}if(n.disableModelInvocation!==void 0)i.disableModelInvocation=n.disableModelInvocation}var zu=null;function Q2(e){if(zu)return;let t=(async()=>{for(let n of e)await Promise.allSettled([n()])})();zu=t,t.then(()=>{zu=null})}function _n(){return zu??Promise.resolve()}var e1={port:31415};import{getAgentDir as lpe}from"@earendil-works/pi-coding-agent";var Ph=(e,t,n)=>(r,i)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw Error("next() called multiple times");o=a;let c,u=!1,d;if(e[a])d=e[a][0][0],r.req.routeIndex=a;else d=a===e.length&&i||void 0;if(d)try{c=await d(r,()=>s(a+1))}catch(f){if(f instanceof Error&&t)r.error=f,c=await t(f,r),u=!0;else throw f}else if(r.finalized===!1&&n)c=await n(r);if(c&&(r.finalized===!1||u))r.res=c;return r}};var t1=Symbol();var n1=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var r1=32,fL=1e4,Vu=(e)=>("headers"in e),s1=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,s=(Vu(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(s==="multipart/form-data"||s==="application/x-www-form-urlencoded")return pL(e,{all:n,dot:r});return{}};async function pL(e,t){if(!Vu(e)&&e.bodyCache.formData)return i1(await e.bodyCache.formData,t);let n=Vu(e)?e.headers:e.raw.headers,r=await e.arrayBuffer(),i=n1(r,n.get("Content-Type")||"");if(!Vu(e))e.bodyCache.formData=i;let o=await i;if(o)return i1(o,t);return{}}function i1(e,t){let n=Object.create(null),r={count:0};if(e.forEach((i,o)=>{if(!(t.all||o.endsWith("[]")))n[o]=i;else hL(n,o,i)}),t.dot)Object.entries(n).forEach(([i,o])=>{if(i.includes("."))gL(n,i,o,r),delete n[i]});return n}var hL=(e,t,n)=>{if(e[t]!==void 0)if(Array.isArray(e[t]))e[t].push(n);else e[t]=[e[t],n];else if(!t.endsWith("[]"))e[t]=n;else e[t]=[n]},gL=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,o=t.split(".",r1+2);if(o.length>r1+1)o1();o.forEach((s,a)=>{if(a===o.length-1)i[s]=n;else{if(!i[s]||typeof i[s]!=="object"||Array.isArray(i[s])||i[s]instanceof File){if(r.count++>=fL)o1();i[s]=Object.create(null)}i=i[s]}})},o1=()=>{throw Error("Nesting limit exceeded")};mi();var h1=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#o()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&Zu(n)}#o(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let r=this.#i(this.#t[0][this.routeIndex][1][n]);if(r!==void 0)e[n]=Zu(r)}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return f1(this.url,e)}queries(e){return p1(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((n,r)=>{t[r]=n}),t}async parseBody(e){return s1(this,e)}#r=(e)=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let i in t)return t[i].then((o)=>{if(i==="json")o=JSON.stringify(o);return new Response(o)[e]()});return t[e]=n[e]()};json(){return this.#r("text").then((e)=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}bytes(){return this.#r("arrayBuffer").then((e)=>new Uint8Array(e))}blob(){return this.#r("blob")}formData(){return this.#r("formData")}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[t1](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};Bh();var vL="text/plain; charset=UTF-8",Wh=(e,t)=>({"Content-Type":e,...t}),la=(e,t)=>new Response(e,t),jh=class{#e;#t;env={};#n;finalized=!1;error;#o;#i;#r;#c;#s;#a;#l;#d;#f;constructor(e,t){if(this.#e=e,t)this.#i=t.executionCtx,this.env=t.env,this.#a=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult}get req(){return this.#t??=new h1(this.#e,this.#f,this.#d),this.#t}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;else throw Error("This context has no ExecutionContext")}get res(){return this.#r||=la(null,{headers:this.#l??=new Headers})}set res(e){if(this.#r&&e){e=la(e.body,e);for(let[t,n]of this.#r.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let i of r)e.headers.append("set-cookie",i)}else e.headers.set(t,n)}}this.#r=e,this.finalized=!0}render=(...e)=>(this.#s??=(t)=>this.html(t),this.#s(...e));setLayout=(e)=>this.#c=e;getLayout=()=>this.#c;setRenderer=(e)=>{this.#s=e};header=(e,t,n)=>{if(this.finalized)this.#r=la(this.#r.body,this.#r);let r=this.#r?this.#r.headers:this.#l??=new Headers;if(t===void 0)r.delete(e);else if(n?.append)r.append(e,t);else r.set(e,t)};status=(e)=>{this.#o=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=(e)=>this.#n?this.#n.get(e):void 0;get var(){if(!this.#n)return{};return Object.fromEntries(this.#n)}#u(e,t,n){let r=this.#r?new Headers(this.#r.headers):this.#l;if(typeof t==="object"&&t.headers){r??=new Headers;for(let[o,s]of new Headers(t.headers))if(o==="set-cookie")r.append(o,s);else r.set(o,s)}if(n){if(!r){let o=0;for(let s in n)if(++o>1||typeof n[s]!=="string"){r=new Headers;break}}if(r)for(let o in n){let s=n[o];if(typeof s==="string")r.set(o,s);else{r.delete(o);for(let a of s)r.append(o,a)}}}let i=typeof t==="number"?t:t?.status??this.#o;return la(e,{status:i,headers:r??n})}newResponse=(...e)=>this.#u(...e);body=(e,t,n)=>this.#u(e,t,n);text=(e,t,n)=>!this.#l&&!this.#o&&!t&&!n&&!this.finalized?new Response(e):this.#u(e,t,Wh(vL,n));json=(e,t,n)=>this.#u(JSON.stringify(e),t,Wh("application/json",n));html=(e,t,n)=>{let r=(i)=>this.#u(i,t,Wh("text/html; charset=UTF-8",n));return typeof e==="object"?Lh(e,g1.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(n)?n:encodeURI(n)),this.newResponse(null,t??302)};notFound=()=>(this.#a??=()=>la(),this.#a(this))};Er();qh();mi();var xL=(e)=>e.text("404 Not Found",404),v1=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},x1=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...b1,y1].forEach((o)=>{this[o]=(s,...a)=>{if(typeof s==="string")this.#e=s;else this.#o(o,this.#e,s);return a.forEach((c)=>{this.#o(o,this.#e,c)}),this}}),this.on=(o,s,...a)=>{for(let c of[s].flat()){this.#e=c;for(let u of[o].flat())a.map((d)=>{this.#o(u.toUpperCase(),this.#e,d)})}return this},this.use=(o,...s)=>{if(typeof o==="string")this.#e=o;else this.#e="*",s.unshift(o);return s.forEach((a)=>{this.#o(Xe,this.#e,a)}),this};let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??Nh:l1}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=xL;errorHandler=v1;route(t,n){let r=this.basePath(t);return n.routes.map((i)=>{let o;if(n.errorHandler===v1)o=i.handler;else o=async(s,a)=>(await Ph([],n.errorHandler)(s,()=>i.handler(s,a))).res,o[da]=i.handler;r.#o(i.method,i.path,o,i.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=Sr(this._basePath,t),n}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#n=t,this);mount(t,n,r){let i,o;if(r)if(typeof r==="function")o=r;else if(o=r.optionHandler,r.replaceRequest===!1)i=(c)=>c;else i=r.replaceRequest;let s=o?(c)=>{let u=o(c);return Array.isArray(u)?u:[u]}:(c)=>{let u=void 0;try{u=c.executionCtx}catch{}return[c.env,u]};i||=(()=>{let c=Sr(this._basePath,t),u=c==="/"?0:c.length;return(d)=>{let f=new URL(d.url);return f.pathname=this.getPath(d).slice(u)||"/",new Request(f,d)}})();let a=async(c,u)=>{let d=await n(i(c.req.raw),...s(c));if(d)return d;await u()};return this.#o(Xe,Sr(t,"*"),a),this}#o(t,n,r,i){t=t.toUpperCase(),n=Sr(this._basePath,n);let o={basePath:i!==void 0?Sr(this._basePath,i):this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,o]),this.routes.push(o)}#i(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,i){if(i==="HEAD")return(async()=>new Response(null,await this.#r(t,n,r,"GET")))();let o=this.getPath(t,{env:r}),s=this.router.match(i,o),a=new jh(t,{path:o,matchResult:s,env:r,executionCtx:n,notFoundHandler:this.#n});if(s[0].length===1){let u;try{u=s[0][0][0][0](a,async()=>{a.res=await this.#n(a)})}catch(d){return this.#i(d,a)}return u instanceof Promise?u.then((d)=>d||(a.finalized?a.res:this.#n(a))).catch((d)=>this.#i(d,a)):u??this.#n(a)}let c=Ph(s[0],this.errorHandler,this.#n);return(async()=>{try{let u=await c(a);if(!u.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#i(u,a)}})()}fetch=(t,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,i)=>{if(t instanceof Request)return this.fetch(n?new Request(t,n):t,r,i);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Sr("/",t)}`,n),r,i)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};Er();mi();var et=()=>Object.create(null);Er();var Qu=[];function $h(e,t){let n=this.buildAllMatchers(),r=(i,o)=>{let s=n[i]||n[Xe],a=s[2][o];if(a)return a;let c=o.match(s[0]);if(!c)return[[],Qu];let u=c.indexOf("",1);return[s[1][u],c]};return this.match=r,r(e,t)}var go="[^/]+",Cr=".*",Yn="(?:|/.*)",Tr=Symbol(),w1=new Set(".\\+*[^]$()");function wL(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===Cr||e===Yn)return t===Yn?-1:1;else if(t===Cr||t===Yn)return-1;if(e===go)return 1;else if(t===go)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var _1=class e{#e;#t;#n=et();insert(t,n,r,i,o){let s=this;for(let a=0,c=t.length;a<c;a++){let u=t[a],d=u.length===1?u==="*"?a===c-1?["","",Cr]:["","",go]:null:u==="/*"?["","",Yn]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),f;if(d){let p=d[1],h=d[2]||go;if(p&&d[2]){if(h===".*")throw Tr;if(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))throw Tr;if(h.length===1&&w1.has(h))throw Tr}if(f=s.#n[h],!f){if(h!==Cr&&h!==Yn){for(let g in s.#n)if((h.length>1||g.length>1)&&g!==Cr&&g!==Yn)throw Tr}f=s.#n[h]=new e}if(p!=="")f.#t??=i.varIndex++,r.push([p,f.#t])}else if(f=s.#n[u],!f){for(let p in s.#n)if(p.length>1&&p!==Cr&&p!==Yn)throw Tr;f=s.#n[u]=new e}s=f}if(s.#e!==void 0)throw Tr;s.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(wL).map((r)=>{let i=this.#n[r],o=i.buildRegExpStr();return o===""?"":(typeof i.#t==="number"?`(${r})@${i.#t}`:w1.has(r)?`\\${r}`:r)+o}).filter(Boolean);if(typeof this.#e==="number"&&this.#e!==-1)n.unshift(`#${this.#e}`);if(n.length===0)return"";if(n.length===1)return n[0];return"(?:"+n.join("|")+")"}};var Hh=class{#e={varIndex:0};#t=new _1;#n=0;paths=et();insert(e,t){if(t){this.#t.insert(e.split(""),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let s=0;;){let a=!1;if(i=i.replace(/\{[^}]+\}/g,(c)=>{let u=`@\\${s}`;return r[s]=[u,c],s++,a=!0,u}),!a)break}let o=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=r.length-1;s>=0;s--){let[a]=r[s];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,r[s][1]);break}}this.#t.insert(o,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(i,o,s)=>{if(o!==void 0)return n[++t]=Number(o),"$()";if(s!==void 0)return r[Number(s)]=++t,"";return""}),[new RegExp(`^${e}`),n,r]}};var D1=et();function S1(e){return D1[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?Yn:t==="*"?Cr:`/:${go}`)}$`)}function el(e,t){for(let n of Object.keys(e).sort((r,i)=>i.length-r.length))if(S1(n).test(t))return[...e[n]];return}var tl=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[Xe]:et()},this.#t={[Xe]:et()},this.#n={[Xe]:new Hh}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===Tr?new Ju(t):n}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(Yu);if(!r[e]){this.#n[e]=new Hh;for(let a of[r,i]){a[e]=et();for(let c in a[Xe])a[e][c]=[...a[Xe][c]],this.#o(e,c)}}if(t==="/*")t="*";let o=e===Xe?Object.keys(r):[e];if(/\*$/.test(t)){let a=S1(t);for(let c of o)if(!r[c][t])this.#o(c,t),r[c][t]=el(r[c],t)||el(r[Xe],t)||[];for(let c of[r,i])for(let u of o)for(let d in c[u])a.test(d)&&c[u][d].push([n,t]);return}let s=Ku(t)||[t];for(let a of s)for(let c of o){if(!i[c][a])this.#o(c,a),i[c][a]=el(r[c],a)||el(r[Xe],a)||[];i[c][a].push([n,a])}}match=$h;buildAllMatchers(){let e=et();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,D1=et(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=et(),o=[],[s,a,c]=r.buildRegExp();for(let u of[t,n])for(let d in u){let f=u[d],p=r.paths[d];if(!p){i[d]=[f.map(([h])=>[h,et()]),Qu];continue}o[p[0]]=f.map(([h,g])=>[h,r.paths[g][1].reduceRight((b,[v],y)=>(b[v]=c[p[1][y][1]],b),et())])}return[s,a.map((u)=>o[u]),i]}};Er();Er();var Gh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(Yu);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error("Fatal error");let n=this.#e,r=this.#t,i=n.length,o=0,s;for(;o<i;o++){let a=n[o];try{for(let c=0,u=r.length;c<u;c++)a.add(...r[c]);s=a.match(e,t)}catch(c){if(c instanceof Ju)continue;throw c}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(o===i)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error("No active router has been determined yet.");return this.#e[0]}};mi();Er();mi();var zh=et(),_L=0,E1=class e{#e=[];#t=et();#n=[];#o;#i=zh;insert(t,n,r){let i=this,o=a1(n),s=new Set,a=0;for(let c of o){let u=o[++a],d=c1(c,u)||(u===void 0&&c&&c.indexOf("*")===c.length-1?c:null),f=Array.isArray(d),p=f?d[0]:d||c,h=i.#t[p]||=new e;if(d&&!h.#o)h.#o=d,i.#n.push(h);if(i=h,f)s.add(d[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...s],score:++_L}})}#r(t,n,r,i,o){for(let s=0,a=n.#e.length;s<a;s++){let c=n.#e[s],u=c[r]||c[Xe];if(u){u.params=et(),t.push(u);for(let d=0,f=u.possibleKeys.length;d<f;d++){let p=u.possibleKeys[d];u.params[p]=o?.[p]&&!d?o[p]:i[p]??o?.[p]}}}}search(t,n){let r=[];this.#i=zh;let o=[this],s=Ih(n),a=[],c=s.length,u=null;for(let d=0;d<c;d++){let f=s[d],p=d===c-1,h=[];for(let b=0,v=o.length;b<v;b++){let y=o[b],x=y.#t[f];if(x)if(x.#i=y.#i,p){if(x.#t["*"])this.#r(r,x.#t["*"],t,y.#i);this.#r(r,x,t,y.#i)}else h.push(x);for(let m of y.#n){let w=m.#o,D=y.#i===zh?{}:{...y.#i};if(typeof w==="string"){if(w==="*"||f.startsWith(w.slice(0,-1))){if(this.#r(r,m,t,y.#i),w==="*")m.#i=D,h.push(m)}continue}let[,T,_]=w;if(!f&&_===!0)continue;if(_!==!0){if(!u){u=[];let M=n[0]==="/"?1:0;for(let P=0;P<c;P++)u[P]=M,M+=s[P].length+1}let A=n.slice(u[d]),E=_.exec(A);if(E){if(D[T]=E[0],this.#r(r,m,t,y.#i,D),E[0].length===A.length&&m.#t["*"])this.#r(r,m.#t["*"],t,y.#i,D);for(let M in m.#t){m.#i=D;let P=E[0].match(/\//g)?.length??0;(a[P]||=[]).push(m);break}continue}}if(_===!0||_.test(f))if(D[T]=f,p){if(this.#r(r,m,t,D,y.#i),m.#t["*"])this.#r(r,m.#t["*"],t,D,y.#i)}else m.#i=D,h.push(m)}}let g=a.shift();o=g?h.concat(g):h}if(r[1])r.sort((d,f)=>d.score-f.score);return[r.map(({handler:d,params:f})=>[d,f])]}};var Vh=class{name="TrieRouter";#e=new E1;add(e,t,n){for(let r of Ku(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}};var Xh=class extends x1{constructor(e={}){super(e);this.router=e.router??new Gh({routers:[new tl,new Vh]})}};function Kh(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}import{execFile as DL}from"node:child_process";import mo from"node:path";import{promisify as SL}from"node:util";var fa=SL(DL),nl=1e4,T1=120000,pa=8388608;async function wt(e,t,n=pa,r=nl){let{stdout:i}=await fa("git",["-C",e,...t],{timeout:r,maxBuffer:n,env:{...process.env,LC_ALL:"C"}});return i}async function Ut(e){try{return(await wt(e,["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}function yi(e,t){let n=mo.relative(mo.resolve(e),mo.resolve(t));return n===""||!n.startsWith(`..${mo.sep}`)&&n!==".."&&!mo.isAbsolute(n)}function Ar(e){return e.split(mo.sep).join("/")}function rl(e){return e.includes(0)}import{lstat as OL,readFile as IL}from"node:fs/promises";import F1 from"node:path";var bi=262144,C1=10485760,A1=10485760,EL={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},TL={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm",webm:"audio/webm"},CL={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function AL(e){return e.replace(/\\/g,"/").split("/").pop()??""}function yo(e){return AL(e).toLowerCase().split(".").pop()??""}function il(e){return EL[yo(e)]??null}function ol(e){return TL[yo(e)]??null}function sl(e){return CL[yo(e)]??null}function k1(e){let t=yo(e);if(t==="pdf"||t==="docx")return t;return null}function kL(e,t){return e==="R"||e==="C"||t==="R"||t==="C"}function U1(e){let t=e.split("\x00"),n=[];for(let r=0;r<t.length;r++){let i=t[r];if(!i||i.length<4||i[2]!==" ")continue;let o=i[0],s=i[1],a={path:i.slice(3),indexStatus:o,worktreeStatus:s};if(kL(o,s))a.originalPath=t[++r]||void 0;n.push(a)}return n}var UL=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function al(e){let t=`${e.indexStatus}${e.worktreeStatus}`;if(t==="??")return{status:"untracked",code:"U"};if(UL.has(t)||t.includes("U"))return{status:"conflict",code:"C"};if(t.includes("D"))return{status:"deleted",code:"D"};if(t.includes("R")||t.includes("C"))return{status:"renamed",code:"R"};if(t.includes("A"))return{status:"added",code:"A"};return{status:"modified",code:"M"}}import{lstat as RL,readFile as FL}from"node:fs/promises";import Zh from"node:path";async function Yh(e){let t=await wt(e,["status","--porcelain=v1","-z","--untracked-files=all"]);return U1(t)}async function R1(e,t,n){let i=Ar(Zh.relative(e,t))||".";try{let o=await wt(e,["diff","--no-color","--no-ext-diff","--numstat",...n,"--",i]),s=new Map;for(let a of o.split(/\r?\n/)){if(!a)continue;let[c,u,...d]=a.split("\t");if(d.length===0)continue;let f=Number(c),p=Number(u);if(!Number.isInteger(f)||!Number.isInteger(p))continue;let h=d.join("\t"),g=h.indexOf(" => ");if(g!==-1)h=h.slice(g+4);s.set(Ar(h.trim()),{additions:f,deletions:p})}return s}catch{return new Map}}async function PL(e){try{let t=await RL(e);if(!t.isFile()||t.size>bi)return 0;let n=await FL(e);if(rl(n)||n.length===0)return 0;let r=n.toString("utf8");return r.endsWith(`
|
|
261
261
|
`)?r.split(`
|
|
262
262
|
`).length-1:r.split(`
|
|
263
263
|
`).length}catch{return 0}}async function cl(e){try{let n=(await wt(e,["rev-parse","--abbrev-ref","HEAD"])).trim()||null;if(!n||n==="HEAD")return{branch:n,upstream:null,ahead:0,behind:0,hasUpstream:!1};let r=null,i=!1;try{r=(await wt(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"])).trim()||null,i=!!r}catch{return{branch:n,upstream:null,ahead:0,behind:0,hasUpstream:!1}}if(!i||!r)return{branch:n,upstream:null,ahead:0,behind:0,hasUpstream:!1};try{let s=(await wt(e,["rev-list","--left-right","--count","HEAD...@{u}"])).trim().split(/\s+/).map((u)=>Number(u)),a=Number.isInteger(s[0])?s[0]:0,c=Number.isInteger(s[1])?s[1]:0;return{branch:n,upstream:r,ahead:a,behind:c,hasUpstream:!0}}catch{return{branch:n,upstream:r,ahead:0,behind:0,hasUpstream:!0}}}catch{return{branch:null,upstream:null,ahead:0,behind:0,hasUpstream:!1}}}async function Jh(e){let t=await Ut(e);if(!t)return{isGitRepository:!1,repositoryRoot:null,files:[],additions:0,deletions:0,stagedFiles:[],stagedAdditions:0,stagedDeletions:0,branch:null,upstream:null,ahead:0,behind:0,hasUpstream:!1};let[n,r,i,o]=await Promise.all([Yh(t),R1(t,e,[]),R1(t,e,["--cached"]),cl(t)]),s=[],a=[];for(let g of n){let b=Zh.resolve(t,g.path);if(!yi(e,b))continue;let v=al(g),y={filePath:b,...v,indexStatus:g.indexStatus,worktreeStatus:g.worktreeStatus},x=g.indexStatus!==" "&&g.indexStatus!=="?",m=g.worktreeStatus!==" ";if(x)a.push({...y,lineStats:i.get(g.path)});if(m)s.push({...y,lineStats:r.get(g.path)})}let c=await Promise.all(s.map(async(g)=>g.status==="untracked"?{filePath:g.filePath,additions:await PL(g.filePath)}:{filePath:g.filePath,additions:0})),u=new Map(c.map((g)=>[g.filePath,g.additions])),d=[...u.values()].reduce((g,b)=>g+b,0);for(let g of s){if(g.status!=="untracked")continue;let b=u.get(g.filePath)??0;if(b>0)g.lineStats={additions:b,deletions:0}}let f=(g)=>{let b=0,v=0;for(let y of g.values())b+=y.additions,v+=y.deletions;return{additions:b,deletions:v}},p=f(r),h=f(i);return{isGitRepository:!0,repositoryRoot:t,files:s,additions:p.additions+d,deletions:p.deletions,stagedFiles:a,stagedAdditions:h.additions,stagedDeletions:h.deletions,...o}}function P1(e,t){let n=t.endsWith(`
|
|
@@ -281,7 +281,7 @@ Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,(i)=>{l
|
|
|
281
281
|
|
|
282
282
|
${e.summary}`,timestamp:fg(e.timestamp)};case"custom_message":return{role:"custom",customType:e.customType,content:e.content,display:e.display,details:e.details,timestamp:fg(e.timestamp)};default:return null}}var AB="@rainmanhhh/pi-web",X1=!1;function K1(){return TB(import.meta.dirname,"..")}function Z1(e,t){return(e??[]).some((n)=>{let r=typeof n==="string"?n:n.source;return r===t||r.includes(AB)})}async function pg(e,t){if(X1)return;if(X1=!0,wi())return;let n=K1();if(!SB(EB(n,"extensions")))return;let r=CB.create(e,t),i=r.getGlobalSettings().packages;if(Z1(i,n))return;r.setPackages([...i??[],n]),console.log(`[pi-web] self-registered as pi package: ${n}`)}var Y1="Compaction cancelled",J1="compaction-disabled-by-extension";import{randomUUID as r_}from"node:crypto";var hg=92;function Q1(e,t=92,n=40){let r=Object.freeze({columns:t,rows:n,kittyProtocolActive:!1});return Object.freeze({terminal:r,requestRender:e})}function e_(e){if(!e||typeof e!=="object")return hg;let t=e.overlayOptions,n=typeof t==="function"?t():t;if(!n||typeof n!=="object")return hg;let r=n.width;return typeof r==="number"&&Number.isFinite(r)?Math.max(40,Math.min(140,Math.round(r))):92}function ba(e,t,n){let r;try{r=n.component.render(n.width)}catch(o){r=[`Extension custom UI render failed: ${o instanceof Error?o.message:String(o)}`]}let i={type:"extension_ui_request",id:t,method:"custom",lines:r};e.pendingUiRequests.set(t,i),e.emit(i)}function vo(e,t,n){let r=e.activeCustomUis.get(t);if(!r||r.settled)return;r.settled=!0,e.activeCustomUis.delete(t),e.pendingUiRequests.delete(t);try{r.component.dispose?.()}catch{}e.emit({type:"extension_ui_request",id:t,method:"custom",lines:[],closed:!0}),r.resolve(n)}function gg(e,t,n){let r=e.activeCustomUis.get(t);if(!r||typeof n!=="string")return;try{if(r.component.handleInput?.(n),e.activeCustomUis.has(t))ba(e,t,r)}catch(i){vo(e,t,void 0),e.emit({type:"extension_error",extensionPath:`custom-ui:${t}`,event:"custom_ui_input",error:i instanceof Error?i.message:String(i)})}}import{Theme as kB}from"@earendil-works/pi-coding-agent";import{TUI_KEYBINDINGS as UB,KeybindingsManager as RB}from"@earendil-works/pi-tui";var FB={accent:"",border:"",borderAccent:"",borderMuted:"",success:"",error:"",warning:"",muted:"",dim:"",text:"",thinkingText:"",userMessageText:"",customMessageText:"",customMessageLabel:"",toolTitle:"",toolOutput:"",mdHeading:"",mdLink:"",mdLinkUrl:"",mdCode:"",mdCodeBlock:"",mdCodeBlockBorder:"",mdQuote:"",mdQuoteBorder:"",mdHr:"",mdListBullet:"",toolDiffAdded:"",toolDiffRemoved:"",toolDiffContext:"",syntaxComment:"",syntaxKeyword:"",syntaxFunction:"",syntaxVariable:"",syntaxString:"",syntaxNumber:"",syntaxType:"",syntaxOperator:"",syntaxPunctuation:"",thinkingOff:"",thinkingMinimal:"",thinkingLow:"",thinkingMedium:"",thinkingHigh:"",thinkingXhigh:"",bashMode:""},PB={selectedBg:"",userMessageBg:"",customMessageBg:"",toolPendingBg:"",toolSuccessBg:"",toolErrorBg:""};class t_ extends kB{constructor(){super(FB,PB,"truecolor")}fg(...[,e]){return e}bg(...[,e]){return e}bold(e){return e}italic(e){return e}underline(e){return e}inverse(e){return e}strikethrough(e){return e}getFgAnsi(){return""}getBgAnsi(){return""}getThinkingBorderColor(){return(e)=>e}getBashModeBorderColor(){return(e)=>e}}var Dl=new t_,n_=new RB(UB);function i_(e,t,n){if(typeof t!=="function")return Promise.resolve(void 0);let r=r_(),i=e_(n);return new Promise((o)=>{let s=!1,a=Q1(()=>{let d=e.activeCustomUis.get(r);if(d)ba(e,r,d)},i),c=(d)=>{if(s)return;s=!0,o(d)},u=(d)=>{if(e.activeCustomUis.has(r))vo(e,r,d);else c(d)};Promise.resolve().then(()=>t(a,Dl,n_,u)).then((d)=>{if(s){try{d?.dispose?.()}catch{}return}if(!d||typeof d!=="object"||typeof d.render!=="function"){c(void 0);return}let f={component:d,width:i,resolve:(p)=>c(p),settled:!1};e.activeCustomUis.set(r,f),ba(e,r,f)}).catch((d)=>{if(s)return;e.emit({type:"extension_error",extensionPath:`custom-ui:${r}`,event:"custom_ui",error:d instanceof Error?d.message:String(d)}),c(void 0)})})}var OB=300000;function va(e,t,n,r,i){let{timeout:o,signal:s}=i??{};if(s?.aborted)return Promise.resolve(n);let a=o??OB,c=r_(),u={type:"extension_ui_request",id:c,...t,...a?{timeout:a,expiresAt:Date.now()+a}:{}};return new Promise((d)=>{let f,p=()=>{if(f)clearTimeout(f);s?.removeEventListener("abort",g),e.pendingUiRequests.delete(c),e.pendingUiResponses.delete(c)},h=(b)=>{p(),d(b)},g=()=>h(n);if(a)f=setTimeout(()=>h(n),a);s?.addEventListener("abort",g,{once:!0}),Qe("ui-chain",`2b ctx.ui.${String(t.method)}`,`id=${c.slice(0,8)} title=${JSON.stringify(t.title??null)} timeout=${a??"-"}`),e.pendingUiRequests.set(c,u),e.pendingUiResponses.set(c,{resolve:(b)=>h(r(b)),cancel:()=>h(n)}),e.emit(u)})}import{randomUUID as xo}from"node:crypto";function xa(e){return{select:(t,n,r)=>va(e,{method:"select",title:t,options:n,...r?.timeout?{timeout:r.timeout}:{}},void 0,(i)=>("value"in i)?i.value:void 0,{timeout:r?.timeout,signal:r?.signal}),confirm:(t,n,r)=>va(e,{method:"confirm",title:t,message:n,...r?.timeout?{timeout:r.timeout}:{}},!1,(i)=>("confirmed"in i)?i.confirmed:!1,{timeout:r?.timeout,signal:r?.signal}),input:(t,n,r)=>va(e,{method:"input",title:t,...n!==void 0?{placeholder:n}:{},...r?.timeout?{timeout:r.timeout}:{}},void 0,(i)=>("value"in i)?i.value:void 0,{timeout:r?.timeout,signal:r?.signal}),editor:(t,n,r)=>va(e,{method:"editor",title:t,...n!==void 0?{prefill:n}:{},...r?.timeout?{timeout:r.timeout}:{}},void 0,(i)=>("value"in i)?i.value:void 0,{timeout:r?.timeout,signal:r?.signal}),notify:(t,n)=>{e.emit({type:"extension_ui_request",id:xo(),method:"notify",message:t,notifyType:n})},onTerminalInput:()=>()=>{},setStatus:(t,n)=>{if(n===void 0)e.extensionStatuses.delete(t);else e.extensionStatuses.set(t,n);e.emit({type:"extension_ui_request",id:xo(),method:"setStatus",statusKey:t,statusText:n})},setWorkingMessage:()=>{},setWorkingVisible:()=>{},setWorkingIndicator:()=>{},setHiddenThinkingLabel:()=>{},setWidget:(t,n,r)=>{if(n!==void 0&&!Array.isArray(n))return;if(n===void 0)e.extensionWidgets.delete(t);else e.extensionWidgets.set(t,{key:t,lines:n,placement:r?.placement??"aboveEditor"});e.emit({type:"extension_ui_request",id:xo(),method:"setWidget",widgetKey:t,widgetLines:n,widgetPlacement:r?.placement})},setFooter:()=>{},setHeader:()=>{},setTitle:(t)=>{e.emit({type:"extension_ui_request",id:xo(),method:"setTitle",title:t})},custom:(t,n)=>i_(e,t,n),pasteToEditor:(t)=>{e.emit({type:"extension_ui_request",id:xo(),method:"set_editor_text",text:t})},setEditorText:(t)=>{e.emit({type:"extension_ui_request",id:xo(),method:"set_editor_text",text:t})},getEditorText:()=>"",addAutocompleteProvider:()=>{},setEditorComponent:()=>{},getEditorComponent:()=>{return},get theme(){return Dl},getAllThemes:()=>[],getTheme:()=>{return},setTheme:()=>({success:!1,error:"Theme switching is not supported in Pi Web extension UI yet"}),getToolsExpanded:()=>!1,setToolsExpanded:()=>{}}}import{existsSync as IB,writeFileSync as MB}from"node:fs";function o_(e){let t=e.sessionManager,n=t.getSessionFile();if(!n||IB(n))return;let r=t.getHeader();if(!r)return;let i=`${[r,...t.getEntries()].map((o)=>JSON.stringify(o)).join(`
|
|
283
283
|
`)}
|
|
284
|
-
`;MB(n,i,{encoding:"utf8",flag:"wx"}),t.flushed=!0,jt(e.sessionId,n)}import{realpathSync as NB}from"node:fs";import{resolve as LB}from"node:path";function Xt(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let e=()=>globalThis.__piSessions?.forEach((t)=>t.destroy());process.once("exit",e),process.once("SIGINT",e),process.once("SIGTERM",e)}return globalThis.__piSessions}function s_(){if(!globalThis.__piStartLocks)globalThis.__piStartLocks=new Map;return globalThis.__piStartLocks}function a_(){if(!globalThis.__piStartLocksAt)globalThis.__piStartLocksAt=new Map;return globalThis.__piStartLocksAt}function Dt(e){let t=LB(e);try{return NB(t)}catch{return t}}function c_(){if(!globalThis.__piStartingSessionCwds)globalThis.__piStartingSessionCwds=new Map;return globalThis.__piStartingSessionCwds}function u_(e){let t=c_(),n=Dt(e);return t.set(n,(t.get(n)??0)+1),()=>{let r=(t.get(n)??1)-1;if(r>0)t.set(n,r);else t.delete(n)}}function Be(e){return Xt().get(e)}function yg(e){let t=Dt(e);for(let[n,r]of Xt()){if(!r.isAlive())continue;if(Dt(r.cwd)!==t)continue;if(r.hasMessages())continue;return n}return}function bg(e){let t=Dt(e);if(c_().has(t))return!0;return Array.from(Xt().values()).some((n)=>Dt(n.cwd)===t&&n.isRunning())}function vg(){let e=new Set,t=[];for(let n of Xt().values()){let r=Dt(n.cwd);if(e.has(r))continue;e.add(r),t.push(r)}return t}function xg(e){let t=Dt(e),n=Array.from(Xt().values()).filter((r)=>Dt(r.cwd)===t);for(let r of n)r.destroy();return n.length}function wa(e,t={}){let n=[],r=[];for(let i of e){let o=Xt().get(i);if(!o)continue;if(t.skipRunning&&o.isRunning()){r.push(o.sessionId||i);continue}o.destroy(),n.push(o.sessionId||i)}return{restarted:n,skipped:r}}function wg(){let e=new Set;for(let[t,n]of Xt())if(n.isRunning())e.add(n.sessionId||t);return[...e]}function wo(){let e=[],t={},n={},r={},i={};for(let[o,s]of Xt())if(s.isRunning()){let a=s.sessionId||o;e.push(a);let c=s.getPhase();if(c){t[a]=c;let d=s.getPhaseStartedAt();if(d!==null)n[a]=d}else{let d=s.getRespondingStartedAt();if(d!==null)r[a]=d}let u=s.getBusyStartedAt();if(u!==null)i[a]=u}return{runningSessionIds:e,phases:t,phaseSince:n,respondingSince:r,busySince:i}}function l_(){if(!globalThis.__piRunningListeners)globalThis.__piRunningListeners=new Set;return globalThis.__piRunningListeners}function _g(e){let t=l_();return t.add(e),()=>{t.delete(e)}}var mg="";function Ft(){let e=l_(),t=wo();if(Qe("running-snapshot","change",`ids=[${t.runningSessionIds.join(",")}] phases=${JSON.stringify(t.phases)} since=${JSON.stringify(t.phaseSince)} responding=${JSON.stringify(t.respondingSince)}`),e.size===0){mg="";return}let n=JSON.stringify(t);if(n===mg)return;mg=n;for(let r of e)try{r(t)}catch{}}function d_(){if(!globalThis.__piAgentEventListeners)globalThis.__piAgentEventListeners=new Set;return globalThis.__piAgentEventListeners}function Dg(e){let t=d_();return t.add(e),()=>{t.delete(e)}}function Sg(e,t){for(let n of d_())try{n(e,t)}catch{}}async function f_(e,t){if(e.isPromptRunning()||e.inner.isStreaming||e.inner.isCompacting||e.inner.isBashRunning)throw Error("Cannot run a shell command while the session is busy");let n=e.inner.executeBash(t.command,void 0,{excludeFromContext:t.excludeFromContext});e.markBusyStart(!0),e.markLocalDrive(!0),e.setPhase({kind:"running_command"}),Ft();try{let r=await n;return o_(e.inner),r}finally{e.markLocalDrive(!1),e.resetIdleTimer(),qe(),e.emit({type:"prompt_done"}),e.setPhase(null),Ft()}}function p_(e){return e.inner.abortBash(),null}async function h_(e,t){if(e.inner.isBashRunning)throw Error("Cannot send a prompt while a shell command is running");let{images:n,streamingBehavior:r}=t;return Qe("ui-chain","2a sdk prompt",`${JSON.stringify(String(t.message).slice(0,80))} streamingBehavior=${r??"-"}`),e.setPromptRunning(!0),e.markBusyStart(!r),e.setPhase({kind:"waiting_model"}),e.touchPromptActivity(),Ft(),e.inner.prompt(t.message,{...n?.length?{images:n}:{},...r?{streamingBehavior:r}:{},source:"rpc"}).then(()=>{if(Qe("ui-chain","2c prompt done"),e.setPromptRunning(!1),e.resetIdleTimer(),!r)e.emit({type:"prompt_done"});Ft()}).catch((i)=>{if(Qe("ui-chain","2c prompt error",i instanceof Error?i.message:String(i)),e.setPromptRunning(!1),e.resetIdleTimer(),qe(),e.emit({type:"prompt_error",errorMessage:i instanceof Error?i.message:String(i)}),!r)e.emit({type:"prompt_done"});Ft()}),null}function BB(e){if(!e.inner.model)return;let n=e.inner.getContextUsage();if(!n||n.tokens==null||n.contextWindow<=0||n.tokens<=n.contextWindow)return n;let r=e.inner.sessionManager.buildSessionProjection(),i=e.inner.sessionManager.getBranch(),o=null;if(r.messages.forEach((u,d)=>{if(u.role!=="assistant")return;let f=u;if(!f.usage||f.stopReason==="aborted"||f.stopReason==="error")return;let p=f.usage;if((p.totalTokens??(p.input??0)+(p.output??0)+(p.cacheRead??0)+(p.cacheWrite??0))>0)o=d}),o==null)return{...n,tokens:null,percent:null};let s=-1,a=0;for(let u of r.entries){let d=a+u.messages.length;if(o<d){s=i.findIndex((f)=>f.id===u.sourceEntry.id);break}a=d}let c=-1;for(let u=i.length-1;u>=0;u--){let d=i[u].type;if(d==="context_edit"||d==="compaction"){c=u;break}}if(s>c)return n;return{...n,tokens:null,percent:null}}function g_(e){let t=e.inner.model,n=BB(e);return{sessionId:e.inner.sessionId,sessionFile:e.inner.sessionFile??"",isStreaming:e.inner.isStreaming,isPromptRunning:e.isPromptRunning(),isBashRunning:e.inner.isBashRunning,isCompacting:e.inner.isCompacting,autoCompactionEnabled:e.inner.autoCompactionEnabled,autoRetryEnabled:e.inner.autoRetryEnabled,model:t?{id:t.id,provider:t.provider}:void 0,messageCount:0,pendingMessageCount:e.inner.pendingMessageCount,queuedMessages:{steering:[...e.inner.getSteeringMessages()],followUp:[...e.inner.getFollowUpMessages()]},contextUsage:n?{percent:n.percent,contextWindow:n.contextWindow,tokens:n.tokens}:null,systemPrompt:e.inner.agent.state?.systemPrompt??"",thinkingLevel:e.inner.agent.state?.thinkingLevel??"off",extensionStatuses:e.getExtensionStatuses(),extensionWidgets:e.getExtensionWidgets()}}var WB=["read","bash","edit","write","grep","find","ls"];function Sl(e,t){if(t.length===0)return[];let n=new Set(WB),r=new Set(e.getActiveToolNames()),i=e.getAllTools().map((o)=>o.name).filter((o)=>!n.has(o)&&(o!=="codemode"||r.has("codemode")));return[...new Set([...t,...i])]}function m_(e){let t=e.inner.getAllTools(),n=new Set(e.inner.getActiveToolNames());return t.map((r)=>({name:r.name,description:r.description,active:n.has(r.name)}))}function y_(e){let t=[];for(let n of e.inner.extensionRunner.getRegisteredCommands())t.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(let n of e.inner.promptTemplates)t.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(let n of e.inner.resourceLoader.getSkills().skills)t.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return{commands:t}}function b_(e,t){let n=t.toolNames;return e.setForceEmptySystemPrompt(n.length===0),e.inner.setActiveToolsByName(Sl(e.inner,n)),e.applyForcedEmptySystemPrompt(),null}import{SessionManager as Tg}from"@earendil-works/pi-coding-agent";import{copyFileSync as jB,readdirSync as qB,statSync as $B,unlinkSync as HB}from"node:fs";import{basename as GB,dirname as _a,join as El}from"node:path";function Tl(e){let t=GB(e);return t.endsWith(".jsonl")?t.slice(0,-6):t}function Eg(e,t){if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))return!1;let n=Tl(e);if(t===`${n}.jsonl`)return!1;return t.startsWith(`${n}.`)}function Cl(e){let t=Tl(e);try{return qB(_a(e)).filter((n)=>{if(!n.startsWith(`${t}.`)||n===`${t}.jsonl`)return!1;return Eg(e,n)}).map((n)=>{let r=$B(El(_a(e),n));return{name:n,size:r.size,modified:r.mtime.toISOString()}}).sort((n,r)=>n.name.localeCompare(r.name))}catch{return[]}}function v_(e,t,n){let r=Tl(e),i=Tl(t);for(let o of n){if(!Eg(e,o))continue;let s=o.slice(r.length);try{jB(El(_a(e),o),El(_a(t),`${i}${s}`))}catch{}}}function x_(e,t){for(let n of t){if(!Eg(e,n))continue;try{HB(El(_a(e),n))}catch{}}}async function w_(e,t){if(e.inner.isBashRunning)throw Error("Cannot fork while a shell command is running");let n=t.entryId,r=e.inner.sessionManager,i=e.inner.sessionFile;if(!r.isPersisted())return{cancelled:!0};if(!i)throw Error("Persisted session is missing a session file");let o=r.getEntry(n);if(!o)throw Error("Invalid entry ID for forking");let s=r.getSessionDir(),a;if(!o.parentId){let d=Tg.create(r.getCwd(),s);d.newSession({parentSession:i}),a=d.getSessionFile()}else{let f=Tg.open(i,s).createBranchedSession(o.parentId);if(!f)throw Error("Failed to create forked session");a=f}let c=Tg.open(a,s).getSessionId(),u=t.copyAuxFiles;if(Array.isArray(u)&&u.every((d)=>typeof d==="string"))v_(i,a,u);return jt(c,a),qe(),e.destroy(),{cancelled:!1,newSessionId:c}}async function __(e,t){if(e.inner.isBashRunning)throw Error("Cannot navigate while a shell command is running");return{cancelled:(await e.inner.navigateTree(t.targetId,{})).cancelled}}class _o extends Error{}function D_(e){return e instanceof _o||e instanceof Error&&/cannot be queued|while a shell command is running/.test(e.message)}async function zB(e,t){let{provider:n,modelId:r}=t,i=e.inner.modelRuntime.getModel(n,r);if(!i)await e.inner.modelRuntime.refresh({allowNetwork:!1}),i=e.inner.modelRuntime.getModel(n,r);if(!i)throw Error(`Model not found: ${n}/${r}`);return await e.inner.setModel(i),Ce(),qe(),{id:i.id,provider:i.provider}}async function VB(e,t){let n=t.level;if(e.inner.setThinkingLevel(n),n==="xhigh"&&e.inner.model?.compat?.thinkingFormat==="deepseek"&&e.inner.agent?.state)e.inner.agent.state.thinkingLevel="xhigh";return qe(),null}async function XB(e,t){try{return await e.withFinalRunningNotification(()=>e.inner.compact(t.customInstructions))}catch(n){if(n instanceof Error&&n.message.includes(Y1))throw Error(J1,{cause:n});throw n}finally{qe()}}async function KB(e,t){let n=t.name?.trim();if(!n)throw Error("Session name cannot be empty");return e.inner.setSessionName(n),qe(),null}async function ZB(e){return{...e.inner.getSessionStats(),sessionName:e.inner.sessionManager.getSessionName()}}async function YB(e,t){return e.inner.setAutoCompactionEnabled(t.enabled),null}async function JB(e,t){let n=t.images;try{await e.inner.steer(t.message,n?.length?n:void 0)}catch(r){if(D_(r))throw new _o(r instanceof Error?r.message:String(r));throw r}return null}async function QB(e,t){let n=t.images;return await e.inner.followUp(t.message,n?.length?n:void 0),null}async function e9(e){if(await e.waitForExtensionsBound(),e.clearExtensionUiState(),e.syncProjectTrust(),await e.inner.reload(),typeof e.inner.bindExtensions!=="function")e.inner.extensionRunner.setUIContext?.(xa(e.extensionUiHost()),"rpc");return e.applyForcedEmptySystemPrompt(),Ce(),{success:!0}}var t9={prompt:h_,abort:(e)=>e.withFinalRunningNotification(()=>e.inner.abort()),get_state:g_,set_model:zB,fork:w_,navigate_tree:__,set_thinking_level:VB,compact:XB,set_session_name:KB,get_session_stats:ZB,get_last_assistant_text:(e)=>({text:e.inner.getLastAssistantText()??""}),set_auto_compaction:YB,clear_queue:(e)=>e.inner.clearQueue(),steer:JB,follow_up:QB,get_tools:m_,get_commands:y_,set_tools:b_,reload:e9,abort_compaction:(e)=>e.inner.abortCompaction(),extension_ui_response:(e,t)=>(e.resolveExtensionUiResponse(t),null),extension_ui_input:(e,t)=>(gg(e.extensionUiHost(),t.id,t.data),null),set_auto_retry:(e,t)=>(e.inner.setAutoRetryEnabled(t.enabled),null),bash:f_,abort_bash:p_};function S_(e){async function t(n,r){let i=t9[n];if(!i)throw Error(`Unsupported command: ${n}`);return i(e,r)}return{dispatch:t}}import{getAgentDir as l9}from"@earendil-works/pi-coding-agent";function n9(e){if(typeof e!=="string")return null;if(e.startsWith("image/"))return"image";return null}function r9(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47}function i9(e){if(!e||e.length%4!==0)return null;let t=e.endsWith("==")?2:e.endsWith("=")?1:0,n=e.length-t;for(let r=0;r<n;r+=1)if(!r9(e.charCodeAt(r)))return null;for(let r=n;r<e.length;r+=1)if(e[r]!=="=")return null;return e.length/4*3-t}function o9(e){if(!e||typeof e!=="object")return!1;let t=e;if(typeof t.data!=="string"||typeof t.mimeType!=="string"||n9(t.mimeType)===null)return!1;let n=i9(t.data);return n!==null&&n<=10485760}function E_(e){if(e===void 0)return null;if(!Array.isArray(e))return"images must be an array";if(e.length>10)return"A message can include at most 10 attachments";for(let t of e){if(!t||typeof t!=="object"||t.type!=="image")return"Each attachment must use the image content block type";if(!o9(t))return"Each attachment must be valid base64 image data of 10MB or smaller"}return null}import{randomUUID as Cg}from"node:crypto";class Ag{deps;pendingUiResponses=new Map;pendingUiRequests=new Map;activeCustomUis=new Map;extensionStatuses=new Map;extensionWidgets=new Map;extensionsBound=!1;extensionBindingPromise=null;extensionBindingError=null;constructor(e){this.deps=e}beginBinding(e={}){this.ensureBound(e).catch((t)=>{console.error("[pi-web] failed to dispatch session_start to extensions:",t instanceof Error?t.message:t)})}async waitUntilReady(){await this.waitForBound()}shouldWaitForExtensions(e){return e==="prompt"||e==="steer"||e==="follow_up"||e==="get_commands"}uiDiagnostics(){return[...this.pendingUiRequests.values()]}cancelPendingUiResponses(){for(let e of this.pendingUiResponses.values())e.cancel();this.pendingUiResponses.clear(),this.pendingUiRequests.clear()}destroyUiState(){this.cancelPendingUiResponses();let e=this.uiHost();for(let t of Array.from(this.activeCustomUis.keys()))vo(e,t,void 0);this.pendingUiResponses.clear(),this.pendingUiRequests.clear()}clearUiState(){this.extensionStatuses.clear(),this.extensionWidgets.clear()}getPendingUiRequests(){return Array.from(this.pendingUiRequests.values())}hasPendingUiRequests(){return this.pendingUiRequests.size>0}resolveExtensionUiResponse(e){let t=this.pendingUiResponses.get(e.id);if(!t){Qe("ui-chain",`4b ui response DROPPED (no pending) id=${e.id.slice(0,8)}`,JSON.stringify(e).slice(0,200));return}Qe("ui-chain",`4 ui response id=${e.id.slice(0,8)}`,JSON.stringify(e).slice(0,200)),t.resolve(e)}getExtensionStatuses(){return Array.from(this.extensionStatuses,([e,t])=>({key:e,text:t}))}getExtensionWidgets(){return Array.from(this.extensionWidgets.values())}replayInto(e){for(let t of this.pendingUiRequests.values())e(t);for(let t of this.extensionWidgets.values())e({type:"extension_ui_request",id:Cg(),method:"setWidget",widgetKey:t.key,widgetLines:t.lines,widgetPlacement:t.placement});for(let[t,n]of this.extensionStatuses)e({type:"extension_ui_request",id:Cg(),method:"setStatus",statusKey:t,statusText:n})}uiHost(){return{activeCustomUis:this.activeCustomUis,pendingUiRequests:this.pendingUiRequests,pendingUiResponses:this.pendingUiResponses,extensionStatuses:this.extensionStatuses,extensionWidgets:this.extensionWidgets,emit:(e)=>this.deps.emit(e)}}ensureBound(e={}){if(e.forceEmptySystemPrompt)this.deps.markForceEmptySystemPrompt();if(this.extensionsBound)return this.deps.applyForcedEmptySystemPrompt(),Promise.resolve();if(this.extensionBindingPromise)return this.extensionBindingPromise;return this.extensionBindingError=null,this.extensionBindingPromise=(async()=>{if(!this.deps.isAlive())return;let t=xa(this.uiHost());if(typeof this.deps.inner.bindExtensions==="function")await this.deps.inner.bindExtensions.call(this.deps.inner,{uiContext:t,mode:"rpc",commandContextActions:this.createCommandContextActions(),shutdownHandler:()=>this.deps.emit({type:"extension_ui_request",id:Cg(),method:"notify",notifyType:"warning",message:"Extension requested shutdown, but shutdown is not supported in Pi Web."}),onError:(r)=>this.deps.emit({type:"extension_error",extensionPath:r.extensionPath,event:r.event,error:r.error})});else this.deps.inner.extensionRunner.setUIContext?.(t,"rpc");this.extensionsBound=!0,this.deps.applyForcedEmptySystemPrompt(),console.log(`[pi-web] session_start dispatched to extensions for session ${this.deps.inner.sessionId}`)})().catch((t)=>{throw this.extensionBindingError=t,t}),this.extensionBindingPromise}async waitForBound(){try{if(this.extensionBindingPromise)await this.extensionBindingPromise}catch(e){throw e instanceof Error?e:Error(String(e))}if(this.extensionBindingError)throw this.extensionBindingError instanceof Error?this.extensionBindingError:Error(String(this.extensionBindingError))}createCommandContextActions(){return{waitForIdle:async()=>{await this.deps.inner.agent.waitForIdle?.()},newSession:async()=>({cancelled:!0}),fork:async()=>({cancelled:!0}),navigateTree:async(e,t)=>({cancelled:(await this.deps.inner.navigateTree(e,{summarize:t?.summarize})).cancelled}),switchSession:async()=>({cancelled:!0}),reload:async()=>{this.extensionStatuses.clear(),this.extensionWidgets.clear(),this.deps.syncProjectTrust(),await this.deps.inner.reload({beforeSessionStart:()=>{this.deps.inner.extensionRunner.setUIContext?.(xa(this.uiHost()),"rpc")}}),this.deps.applyForcedEmptySystemPrompt()}}}}import{existsSync as s9}from"node:fs";var T_=(()=>{if(process.env.PI_WEB_E2E!=="1")return 600000;let e=Number(process.env.PI_SESSION_IDLE_MS);return Number.isFinite(e)&&e>0?e:600000})();class kg{idleTimer=null;deps;constructor(e){this.deps=e}reset(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=setTimeout(()=>{if(this.deps.isRunning()){if(this.deps.isPromptRunning()&&Date.now()-this.deps.getLastPromptActivityAt()>=T_){if(this.deps.isBashRunning()||this.deps.hasPendingUiRequests()){this.reset();return}this.settleStalledRun();return}this.reset();return}let e=this.deps.sessionFile();if(e&&!s9(e)){this.reset();return}this.deps.destroy()},T_)}stop(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=null}settleStalledRun(){try{this.deps.unlockStall()}catch{}this.deps.setPromptRunning(!1),this.deps.emit({type:"prompt_error",errorMessage:"Agent run stalled (no activity for 10 minutes) — reset to idle. "+"If this keeps happening, restart the pi-web server."}),this.deps.emit({type:"prompt_done"}),this.reset(),this.deps.notifyRunningChange()}}function C_(e){let t=e?.contentIndex;if(typeof t!=="number")return null;let n=e?.partial?.content?.[t];if(n?.type!=="toolCall")return null;let r=n;if(typeof r.id!=="string"||!r.id)return null;return{id:r.id,name:typeof r.name==="string"&&r.name?r.name:r.id}}var a9=120000,c9=5000,u9=new Set(["agent_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end","bash_execution_update","auto_compaction_start","compaction_start"]);class Ug{phase=null;phaseStartedAt=null;respondingStartedAt=null;busyStartedAt=null;runningToolNames=new Map;promptRunning=!1;lastPromptActivityAt=0;externalActivityAt=null;localDriveActive=!1;localDriveEndedAt=null;getPhase(){return this.phase}getPhaseStartedAt(){return this.phaseStartedAt}getRespondingStartedAt(){return this.respondingStartedAt}getBusyStartedAt(){return this.busyStartedAt}isPromptRunning(){return this.promptRunning}isExternalActivityFresh(){return this.externalActivityAt!==null&&Date.now()-this.externalActivityAt<a9}setPromptRunning(e){if(this.promptRunning=e,e)this.localDriveActive=!0,this.localDriveEndedAt=null;else this.localDriveActive=!1,this.localDriveEndedAt=Date.now()}markLocalDrive(e){if(e)this.localDriveActive=!0,this.localDriveEndedAt=null;else this.localDriveActive=!1,this.localDriveEndedAt=Date.now()}isLocallyDriven(){return this.localDriveActive||this.localDriveEndedAt!==null&&Date.now()-this.localDriveEndedAt<c9}markBusyStart(e){if(this.busyStartedAt===null||e)this.busyStartedAt=Date.now()}touchPromptActivity(){this.lastPromptActivityAt=Date.now()}getLastPromptActivityAt(){return this.lastPromptActivityAt}setPhase(e){let t=(this.phase?.kind??null)!==(e?.kind??null);if(this.phase=e,!e){if(this.phaseStartedAt=null,this.busyStartedAt!==null)this.respondingStartedAt=Math.max(this.respondingStartedAt??Date.now(),this.busyStartedAt);return}this.respondingStartedAt=null;let n=t||this.phaseStartedAt===null?Date.now():this.phaseStartedAt;this.phaseStartedAt=this.busyStartedAt!==null?Math.max(n,this.busyStartedAt):n}updatePhaseFromEvent(e){if(!this.promptRunning&&!this.isLocallyDriven()&&u9.has(e.type))this.externalActivityAt=Date.now();switch(e.type){case"agent_start":this.onAgentStart();break;case"agent_end":this.onAgentEnd();break;case"message_update":this.onMessageUpdate(e);break;case"auto_retry_start":this.onAutoRetryStart(e);break;case"auto_retry_end":this.onAutoRetryEnd();break;case"tool_execution_start":this.onToolStart(e);break;case"tool_execution_end":this.onToolEnd(e);break}}onAgentStart(){this.setPhase({kind:"waiting_model"})}onAgentEnd(){this.runningToolNames.clear(),this.setPhase(null)}toolsOrFallback(e){return this.runningToolNames.size>0?{kind:"running_tools",tools:[...this.runningToolNames.entries()].map(([t,n])=>({id:t,name:n}))}:e}onMessageUpdate(e){let t=e.assistantMessageEvent,n=t?.type??"";if(n.startsWith("thinking")){this.setPhase(this.toolsOrFallback({kind:"thinking"}));return}if(n==="toolcall_start"||n==="toolcall_delta"){let r=C_(t);if(r)this.runningToolNames.set(r.id,r.name);this.syncRunningToolsPhase();return}if(n==="toolcall_end")return;this.setPhase(this.toolsOrFallback(null))}onAutoRetryStart(e){let t=e;this.setPhase({kind:"retrying",attempt:t.attempt??1,maxAttempts:t.maxAttempts??1,errorMessage:t.errorMessage})}onAutoRetryEnd(){this.setPhase(null)}onToolStart(e){let t=e.toolCallId;if(t)this.runningToolNames.set(t,e.toolName??t);this.syncRunningToolsPhase()}onToolEnd(e){let t=e.toolCallId;if(t)this.runningToolNames.delete(t);this.syncRunningToolsPhase()}syncRunningToolsPhase(){this.setPhase(this.runningToolNames.size>0?{kind:"running_tools",tools:[...this.runningToolNames.entries()].map(([e,t])=>({id:e,name:t}))}:{kind:"waiting_model"})}}var d9=1000,f9=new Set(["agent_start","agent_end","agent_settled","message_update","tool_execution_start","tool_execution_end","auto_compaction_start","auto_compaction_end","compaction_start","compaction_end","auto_retry_start","auto_retry_end"]),p9=new Set(["agent_end","agent_settled","auto_compaction_end","compaction_end"]),h9=new Set(["agent_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end","bash_execution_update","agent_end","agent_settled","auto_compaction_start","auto_compaction_end","compaction_start","compaction_end","prompt_done","prompt_error"]);class Al{inner;listeners=[];forceEmptySystemPrompt=!1;savedTransformContext;unsubscribe=null;idle=new kg({isRunning:()=>this.isRunning(),isPromptRunning:()=>this.phases.isPromptRunning(),getLastPromptActivityAt:()=>this.phases.getLastPromptActivityAt(),isBashRunning:()=>this.inner.isBashRunning,hasPendingUiRequests:()=>this.extensions.hasPendingUiRequests(),sessionFile:()=>this.sessionFile,setPromptRunning:(e)=>this.phases.setPromptRunning(e),emit:(e)=>this.emit(e),destroy:()=>this.destroy(),notifyRunningChange:()=>Ft(),unlockStall:()=>{this.cancelPendingUiResponses(),this.inner.abort().catch(()=>{})}});onDestroyCallback=null;bufferedEvents=[];lastStreamingUpdate=null;_alive=!0;commands=null;phases=new Ug;extensions;constructor(e){this.inner=e;this.extensions=new Ag({inner:this.inner,isAlive:()=>this._alive,emit:(t)=>this.emit(t),markForceEmptySystemPrompt:()=>{this.forceEmptySystemPrompt=!0},applyForcedEmptySystemPrompt:()=>this.applyForcedEmptySystemPrompt(),syncProjectTrust:()=>this.syncProjectTrust()})}getCommands(){if(!this.commands)this.commands=S_(this.commandDeps());return this.commands}get sessionId(){return this.inner.sessionId}get sessionFile(){return this.inner.sessionFile??""}get cwd(){return this.inner.sessionManager.getCwd()}hasMessages(){return this.inner.sessionManager.getBranch().some((e)=>e.type==="message")}isAlive(){return this._alive}isRunning(){return this._alive&&(this.phases.isPromptRunning()||this.inner.isStreaming||this.inner.isCompacting||this.inner.isBashRunning||this.phases.isExternalActivityFresh())}start(){this.unsubscribe=this.inner.subscribe((e)=>{if(e.type==="agent_end")qe();if(p9.has(e.type))this.idle.reset();if(h9.has(e.type))this.phases.touchPromptActivity();if(this.phases.updatePhaseFromEvent(e),this.emit(e),f9.has(e.type))Ft()}),this.idle.reset(),Ft()}getPhase(){return this.phases.getPhase()}getPhaseStartedAt(){return this.phases.getPhaseStartedAt()}getRespondingStartedAt(){return this.phases.getRespondingStartedAt()}getBusyStartedAt(){return this.phases.getBusyStartedAt()}setPhase(e){this.phases.setPhase(e)}setForceEmptySystemPrompt(e){this.forceEmptySystemPrompt=e,this.applyForcedEmptySystemPrompt()}beginExtensionBinding(e={}){this.extensions.beginBinding(e)}async waitUntilReady(){await this.extensions.waitUntilReady()}shouldWaitForExtensions(e){return this.extensions.shouldWaitForExtensions(e)}async withFinalRunningNotification(e){try{return await e()}finally{this.idle.reset(),Ft()}}applyForcedEmptySystemPrompt(){let e=this.inner.agent;if(!e)return;if(this.forceEmptySystemPrompt){if(this.savedTransformContext!==void 0)return;let t=e.transformContext;this.savedTransformContext=t,e.transformContext=async(n,r)=>{let i=t?await t(n,r):n;return[{role:"system",content:"",timestamp:Date.now()},...i.filter((s)=>s.role!=="system")]}}else if(this.savedTransformContext!==void 0)e.transformContext=this.savedTransformContext,this.savedTransformContext=void 0}getStreamingUpdate(){return this.lastStreamingUpdate}trackStreaming(e){if(e.type==="message_update"){let t=e.message;if(t&&typeof t==="object"&&t.role!=="user"){this.lastStreamingUpdate=e;return}}if(e.type==="message_end"||e.type==="agent_end")this.lastStreamingUpdate=null}emit(e){if(this.trackStreaming(e),Sg(this.sessionId,e),this.listeners.length===0){if(this.bufferedEvents.push(e),this.bufferedEvents.length>d9)this.bufferedEvents.shift();return}for(let t of this.listeners)t(e)}onEvent(e){let t=this.bufferedEvents;this.bufferedEvents=[];for(let n of t)e(n);return this.listeners.push(e),this.extensions.replayInto(e),()=>{let n=this.listeners.indexOf(e);if(n!==-1)this.listeners.splice(n,1)}}onDestroy(e){this.onDestroyCallback=e}commandDeps(){return{inner:this.inner,emit:(e)=>this.emit(e),setPhase:(e)=>this.setPhase(e),resetIdleTimer:()=>this.idle.reset(),isPromptRunning:()=>this.phases.isPromptRunning(),setPromptRunning:(e)=>{this.phases.setPromptRunning(e)},markBusyStart:(e)=>this.phases.markBusyStart(e),markLocalDrive:(e)=>this.phases.markLocalDrive(e),touchPromptActivity:()=>this.phases.touchPromptActivity(),setForceEmptySystemPrompt:(e)=>this.setForceEmptySystemPrompt(e),waitForExtensionsBound:()=>this.extensions.waitUntilReady(),withFinalRunningNotification:(e)=>this.withFinalRunningNotification(e),clearExtensionUiState:()=>this.extensions.clearUiState(),syncProjectTrust:()=>this.syncProjectTrust(),extensionUiHost:()=>this.extensions.uiHost(),resolveExtensionUiResponse:(e)=>this.extensions.resolveExtensionUiResponse(e),applyForcedEmptySystemPrompt:()=>this.applyForcedEmptySystemPrompt(),getExtensionStatuses:()=>this.extensions.getExtensionStatuses(),getExtensionWidgets:()=>this.extensions.getExtensionWidgets(),destroy:()=>this.destroy()}}async send(e){this.idle.reset();let t=e.type;if(this.shouldWaitForExtensions(t))await this.extensions.waitUntilReady();if(t==="prompt"||t==="steer"||t==="follow_up"){let n=E_(e.images);if(n)throw Error(n)}return this.getCommands().dispatch(t,e)}destroy(){if(!this._alive)return;if(this._alive=!1,this.idle.stop(),this.inner.isBashRunning)this.inner.abortBash();this.unsubscribe?.(),this.extensions.destroyUiState(),this.onDestroyCallback?.(),Ft()}cancelPendingUiResponses(){this.extensions.cancelPendingUiResponses()}diagnostics(){return{alive:this._alive,running:this.isRunning(),promptRunning:this.phases.isPromptRunning(),lastPromptActivityAt:this.phases.getLastPromptActivityAt(),lastPromptActivityAgeMs:Date.now()-this.phases.getLastPromptActivityAt(),bufferedEvents:this.bufferedEvents.length,pendingUiRequests:this.extensions.uiDiagnostics()}}getPendingUiRequests(){return this.extensions.getPendingUiRequests()}resolveExtensionUiResponse(e){this.extensions.resolveExtensionUiResponse(e)}getExtensionStatuses(){return this.extensions.getExtensionStatuses()}getExtensionWidgets(){return this.extensions.getExtensionWidgets()}syncProjectTrust(){let e=Oe(this.cwd,l9());this.inner.settingsManager.setProjectTrusted(e.trusted)}}async function A_(e,t,n){if(!t.model&&!t.thinkingLevel)return{modelDefaultChanged:!1};let r=!1;if(t.model&&n.model&&t.model.provider===n.model.provider&&t.model.modelId===n.model.modelId)e.setDefaultModelAndProvider(n.model.provider,n.model.modelId),r=!0;if(t.thinkingLevel&&(n.supportsThinking||n.thinkingLevel!=="off"))e.setDefaultThinkingLevel(n.thinkingLevel);return await e.flush(),{modelDefaultChanged:r}}function _9(e,t,n,r){return{...e?{requestedModel:e}:{},...t&&n?{defaultModel:{provider:t,modelId:n}}:{},...r?{thinkingLevel:r}:{}}}function D9(e){if(e===void 0)return;return e.length===0?[]:void 0}function S9(e,t){return{...e.model?{model:e.model}:{},...e.thinkingLevel?{thinkingLevel:e.thinkingLevel}:{},...e.scopedModels.length>0?{scopedModels:e.scopedModels}:{},...t!==void 0?{tools:t}:{}}}function E9(e,t){return{...e?{model:e}:{},...t?{thinkingLevel:t}:{}}}function T9(e,t,n){return{...e?{model:{provider:e.provider,modelId:e.id}}:{},thinkingLevel:t,supportsThinking:n}}var Rg=ze("rpc-start"),C9=60000;async function Rr(e,t,n,r={}){let{toolNames:i,initialModel:o,thinkingLevel:s}=r,a=Xt(),c=s_(),u=a_(),d=a.get(e);if(d?.isAlive())return{session:d,realSessionId:e};let f=c.get(e);if(f){let x=Date.now()-(u.get(e)??0);if(x<C9)return f;Rg(`stale lock sid=${e} age=${Math.round(x/1000)}s — restarting fresh`),c.delete(e),u.delete(e)}let p;if(t)p=k_.open(t,void 0);else{if(!n)throw Error("cwd is required for a new session");p=k_.create(n,void 0)}let h=p.getCwd(),g=u_(h),b=performance.now(),v=(x)=>Rg(`sid=${e} ${x} +${Math.round(performance.now()-b)}ms`);v("cold start begin");let y=(async()=>{w9();let x=x9();await pg(h,x);let m=D9(i),w=ho(h,x),D=[b9(),y9({}),v9()],T=r.fixtureExtensionPaths??yl(e);v("creating services");let _=await m9({cwd:h,agentDir:x,...w?{resourceLoaderReloadOptions:w}:{},resourceLoaderOptions:{extensionFactories:D,...T.length>0?{additionalExtensionPaths:T}:{}}}),A=await dl(_.modelRuntime,_.settingsManager.getEnabledModels()),E=_.settingsManager.getDefaultProvider(),M=_.settingsManager.getDefaultModel(),C=p.getBranch().some((F)=>F.type==="message")?{scopedModels:[...A.scopedModels]}:fl(A,_9(o,E,M,s));v("services ready — spawning agent session");let{session:L}=await g9({services:_,sessionManager:p,...S9(C,m)});if((await A_(_.settingsManager,E9(o,s),T9(L.model,L.thinkingLevel,L.supportsThinking()))).modelDefaultChanged)Ce();if(i&&i.length>0)L.setActiveToolsByName(Sl(L,i));let H=new Al(L);if(i?.length===0)H.setForceEmptySystemPrompt(!0);H.start();let{sessionId:S,sessionFile:R}=L;if(R)jt(S,R);let k=a.get(S);if(k&&k!==H)throw Rg(`sid=${e} duplicate settle — destroying late instance`),H.destroy(),Error(`session ${e} already registered by a newer instance`);return H.onDestroy(()=>a.delete(S)),a.set(S,H),v("cold start done"),H.beginExtensionBinding({forceEmptySystemPrompt:i?.length===0}),{session:H,realSessionId:S}})().finally(()=>{c.delete(e),g()});return c.set(e,y),u.set(e,Date.now()),y.catch(()=>{}),y}var A9=5000,k9=60,U_=60000,kl=new Map,Ul=new Set,Fg=new Map,Da=new Map;function U9(){let e=Zn().preferences.gitAutoFetchIntervalSec;return typeof e==="number"&&Number.isFinite(e)?e:k9}function R9(e){let t=Fg.get(e);if(t)return t;let n=Kh();Fg.set(e,n.promise);let r;return(async()=>{try{let i=await Promise.race([(async()=>{let o=await og(e);if(!o.ok)return{ok:!1,error:o.error};let s=await cl(e);return{ok:!0,snapshot:{ahead:s.ahead,behind:s.behind,updatedAt:Date.now()}}})(),new Promise((o,s)=>{r=setTimeout(()=>s(Error(`git fetch timeout after ${U_/1000}s`)),U_),r.unref?.()})]);n.resolve(i)}catch(i){n.resolve({ok:!1,error:i instanceof Error?i.message:String(i)})}finally{if(r)clearTimeout(r);Fg.delete(e)}})(),n.promise}async function R_(e){let t=new Map;for(let n of e){let r=null;try{r=await Ut(n)}catch{r=null}if(!r)continue;let i=t.get(r);if(i)i.push(n);else t.set(r,[n])}return t}async function F_(e,t){await Promise.all(Array.from(e,async([n,r])=>{let i=await R9(n);if(!i.ok){console.warn(`[git-autofetch] fetch failed for ${n}: ${i.error}`);return}for(let o of r)kl.set(Dt(o),i.snapshot);Da.set(n,t)}))}function F9(e){let t=new Set(e);for(let n of[...Ul])if(!e.includes(n))Ul.delete(n);for(let n of[...kl.keys()])if(!t.has(n))kl.delete(n)}function P9(e){for(let t of[...Da.keys()])if(!e.has(t))Da.delete(t)}async function O9(e,t){let n=e.filter((i)=>!Ul.has(i));if(n.length===0)return;let r=await R_(n);await F_(r,t);for(let i of n)Ul.add(i)}async function I9(e,t,n){let r=new Map;for(let[i,o]of e){let s=Da.get(i)??0;if(t-s<n*1000)continue;r.set(i,o)}if(r.size===0)return;await F_(r,t)}async function M9(e=Date.now()){let t=vg();if(F9(t),t.length===0){Da.clear();return}let n=U9(),r=await R_(t);if(P9(r),n<=0){await O9(t,e);return}await I9(r,e,n)}function P_(e){return kl.get(Dt(e))??null}function O_(){setInterval(()=>{M9()},A9).unref()}import{isIP as I_}from"node:net";function M_(e){return(e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e).toLowerCase().replace(/\.$/,"")}function N_(e){if(!e||/[\s/@\\]/.test(e))return null;try{let t=new URL(`http://${e}`);if(t.username||t.password||t.pathname!=="/"||t.search||t.hash)return null;return M_(t.hostname)}catch{return null}}function N9(e){let t=e?.trim();if(!t)return null;return I_(t)?M_(t):N_(t)}function L9(e){return e==="localhost"||e.endsWith(".localhost")}function L_(){return[process.env.PI_WEB_HOSTNAME,...process.env.PI_WEB_ALLOWED_HOSTS?.split(",")??[]].filter((e)=>Boolean(e?.trim()))}function B_(e){try{return new URL(e).origin}catch{return null}}function B9(e){let t=new URL(e.url),n=e.headers.get("host");return n?B_(`${t.protocol}//${n}`):null}function W9(e){if(e.method!=="GET"||e.headers.get("sec-fetch-mode")!=="navigate"||e.headers.get("sec-fetch-dest")!=="document"||e.headers.get("sec-fetch-user")!=="?1")return!1;try{return/^\/api\/sessions\/[^/]+\/export$/.test(new URL(e.url).pathname)}catch{return!1}}function Pg(e,t=L_()){let n=e.headers.get("host"),r=n?N_(n):null;if(!r)return!1;if(L9(r)||I_(r))return!0;return t.some((i)=>N9(i)===r)}function j9(e){let t=e.headers.get("origin");if(e.headers.get("sec-fetch-site")==="cross-site")return!1;if(!t)return!0;let r=B9(e);return r!==null&&B_(t)===r}function q9(e){return e.headers.has("origin")||e.headers.has("sec-fetch-site")}function Pt(e,t=L_()){if(!Pg(e,t))return!1;if(W9(e))return!0;return!q9(e)||j9(e)}function Fr(e){let t=e.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||Boolean(t?.startsWith("application/")&&t.endsWith("+json"))}import{createHash as $9,timingSafeEqual as H9}from"node:crypto";var G9="pi";function W_(e){return $9("sha256").update(e,"utf8").digest()}function j_(e,t){return H9(W_(e),W_(t))}function Sa(e=process.env.PI_WEB_PASSWORD){return typeof e==="string"&&e.length>0}function Rl(e,t=process.env.PI_WEB_PASSWORD){if(!Sa(t)||!e)return!1;let n=/^Basic\s+(\S+)$/i.exec(e);if(!n)return!1;let r;try{let u=Buffer.from(n[1],"base64");if(u.toString("base64")!==n[1])return!1;r=new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{return!1}let i=r.indexOf(":");if(i===-1)return!1;let o=r.slice(0,i),s=r.slice(i+1),a=j_(o,G9),c=j_(s,t);return a&&c}var q_=ze("mount"),z9=["GET","POST","PUT","PATCH","DELETE"];function Y(e,t,n){let r=t.split("/").filter(Boolean),i=[],o=new Map;for(let a of r){let c=a.match(/^\[\.\.\.(.+)\]$/),u=a.match(/^\[(.+)\]$/);if(c)i.push(`:${c[1]}{.+}`),o.set(c[1],{hono:c[1],catchAll:!0});else if(u)i.push(`:${u[1]}`),o.set(u[1],{hono:u[1],catchAll:!1});else i.push(a)}let s=`/${i.join("/")}`;for(let a of z9){let c=n[a];if(typeof c!=="function")continue;let u=c;e.on(a,s,async(d)=>{let f=performance.now();q_(`${a} ${d.req.path}`,"received");let p={};for(let[g,{hono:b,catchAll:v}]of o)if(v){let y=d.req.param(b)??"";p[g]=y===""?[]:y.split("/")}else p[g]=d.req.param(b)??"";let h=await u(d.req.raw,{params:Promise.resolve(p)});return q_(`${a} ${d.req.path}`,`${h.status} ${Math.round(performance.now()-f)}ms done`),h})}}var Mg={};Z(Mg,{GET:()=>t6});import{tmpdir as Q9}from"node:os";import{Readable as e6}from"node:stream";import{constants as Og}from"node:fs";import{lstat as V9,open as X9}from"node:fs/promises";import{basename as K9,dirname as Z9,resolve as $_}from"node:path";var Fl=5242880;function H_(e,t){let n=$_(e);if(Z9(n)!==$_(t))return null;if(!/^pi-bash-[A-Za-z0-9_-]+\.log$/.test(K9(n)))return null;return n}async function Ig(e){if(!(await V9(e)).isFile())throw Error("Bash output path is not a regular file");let n=typeof Og.O_NOFOLLOW==="number"?Og.O_NOFOLLOW:0,r=await X9(e,Og.O_RDONLY|n);try{let i=await r.stat();if(!i.isFile())throw Error("Bash output path is not a regular file");return{handle:r,fileInfo:i}}catch(i){throw await r.close(),i}}async function G_(e,t=Fl){let{handle:n,fileInfo:r}=await Ig(e);try{if(r.size>t)return{tooLarge:!0,size:r.size};let i=Buffer.alloc(r.size),o=0;while(o<i.length){let s=await n.read(i,o,i.length-o,o);if(s.bytesRead===0)break;o+=s.bytesRead}return{tooLarge:!1,content:i.subarray(0,o).toString("utf8"),size:o}}finally{await n.close()}}var Y9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function z_(e){return!!e&&Y9.test(e)}function V_(e,t){return t.some((n)=>n.type==="message"&&n.message.role==="bashExecution"&&n.message.fullOutputPath===e)}async function X_(e,t){if(!z_(t))return!1;try{let n=await De(t);if(!n)return!1;return V_(e,wl(n))}catch{return!1}}async function t6(e,{params:t}){let{id:n}=await t,r=null,i=!1;try{let s=new URL(e.url);r=s.searchParams.get("path"),i=s.searchParams.get("download")==="1"}catch{return Response.json({error:"invalid url"},{status:400})}if(!r)return Response.json({error:"path required"},{status:400});let o=H_(r,Q9());if(!o)return Response.json({error:"invalid path"},{status:400});if(!await X_(o,n))return Response.json({error:"forbidden"},{status:403});try{if(i){let{handle:a}=await Ig(o),c=e6.toWeb(a.createReadStream());return new Response(c,{headers:{"Content-Type":"text/plain; charset=utf-8","Content-Disposition":'attachment; filename="bash-output.log"',"Cache-Control":"no-store"}})}let s=await G_(o);if(s.tooLarge)return Response.json({error:`Full output is too large to display (limit ${Fl} bytes)`,data:{size:s.size,maxBytes:Fl}},{status:413});return Response.json({success:!0,data:{output:s.content}})}catch{return Response.json({error:"full output unavailable"},{status:404})}}var Ng={};Z(Ng,{GET:()=>n6});async function n6(e,{params:t}){let{id:n}=await t,r=Be(n);if(!r?.isAlive())return Response.json({error:"Session not found or not alive"},{status:404});return Response.json({success:!0,data:r.diagnostics()})}var Gg={};Z(Gg,{GET:()=>W6,POST:()=>B6,sendWithDeferredModelSwitch:()=>Hg,setFakeBusySession:()=>To});import{resolve as r6}from"node:path";var i6="piE2eFixtureDir",o6="piE2eFixtureDir";function Lg(e){return r6(process.cwd(),e)}function s6(e){if(!e)return{};let t={};for(let n of e.split(";")){let r=n.indexOf("=");if(r===-1)continue;t[n.slice(0,r).trim()]=n.slice(r+1).trim()}return t}function ae(e){let t=s6(e.headers.get("cookie"))[i6];if(t)try{return Lg(decodeURIComponent(t))}catch{return Lg(t)}let n=new URL(e.url).searchParams.get(o6);return n?Lg(n):void 0}So();import{mkdir as g6,readFile as m6,rename as y6,writeFile as b6}from"node:fs/promises";import{dirname as v6,join as x6}from"node:path";import{getAgentDir as w6}from"@earendil-works/pi-coding-agent";var _6=[{name:"readonly",tools:["read","grep","find","ls"],description:{en:"Read-only tools (read/grep/find/ls)","zh-CN":"仅只读工具(read/grep/find/ls)"}},{name:"full",tools:["bash","read","edit","write","grep","find","ls"],description:{en:"All built-in tools enabled (except codemode)","zh-CN":"内置工具全开(codemode除外)"}},{name:"codemode",tools:["codemode"],description:{en:"Codemode only","zh-CN":"仅激活codemode"}}],D6=new Set(["off","default"]),Z_=_6;function Y_(){return x6(w6(),"pi-web","tool-presets.json")}function Bg(e){if(!Array.isArray(e))return null;let t=new Set,n=[];for(let r of e){if(typeof r!=="object"||r===null)return null;let{name:i,tools:o,description:s}=r;if(typeof i!=="string"||i.trim().length===0)return null;let a=i.trim();if(t.has(a))return null;if(!Array.isArray(o)||o.some((u)=>typeof u!=="string"||u.trim()===""))return null;t.add(a);let c=S6(s);n.push({name:a,tools:o.map((u)=>u.trim()),...c?{description:c}:{}})}return n}function S6(e){if(typeof e==="string"){let r=e.trim();return r.length>0?r:void 0}if(typeof e!=="object"||e===null||Array.isArray(e))return;let t=e,n={};for(let r of["en","zh-CN"]){let i=t[r];if(typeof i==="string"&&i.trim().length>0)n[r]=i.trim()}if(Object.keys(n).length===0)return;return n}function J_(e){return e.filter((t)=>!D6.has(t.name))}async function Eo(){try{let e=await m6(Y_(),"utf8"),t=Bg(JSON.parse(e));return t?{presets:J_(t),exists:!0}:{presets:Z_,exists:!1}}catch{return{presets:Z_,exists:!1}}}async function Q_(e){let t=Y_();await g6(v6(t),{recursive:!0});let n=`${t}.tmp`;await b6(n,`${JSON.stringify(J_(e),null,2)}
|
|
284
|
+
`;MB(n,i,{encoding:"utf8",flag:"wx"}),t.flushed=!0,jt(e.sessionId,n)}import{realpathSync as NB}from"node:fs";import{resolve as LB}from"node:path";function Xt(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let e=()=>globalThis.__piSessions?.forEach((t)=>t.destroy());process.once("exit",e),process.once("SIGINT",e),process.once("SIGTERM",e)}return globalThis.__piSessions}function s_(){if(!globalThis.__piStartLocks)globalThis.__piStartLocks=new Map;return globalThis.__piStartLocks}function a_(){if(!globalThis.__piStartLocksAt)globalThis.__piStartLocksAt=new Map;return globalThis.__piStartLocksAt}function Dt(e){let t=LB(e);try{return NB(t)}catch{return t}}function c_(){if(!globalThis.__piStartingSessionCwds)globalThis.__piStartingSessionCwds=new Map;return globalThis.__piStartingSessionCwds}function u_(e){let t=c_(),n=Dt(e);return t.set(n,(t.get(n)??0)+1),()=>{let r=(t.get(n)??1)-1;if(r>0)t.set(n,r);else t.delete(n)}}function Be(e){return Xt().get(e)}function yg(e){let t=Dt(e);for(let[n,r]of Xt()){if(!r.isAlive())continue;if(Dt(r.cwd)!==t)continue;if(r.hasMessages())continue;return n}return}function bg(e){let t=Dt(e);if(c_().has(t))return!0;return Array.from(Xt().values()).some((n)=>Dt(n.cwd)===t&&n.isRunning())}function vg(){let e=new Set,t=[];for(let n of Xt().values()){let r=Dt(n.cwd);if(e.has(r))continue;e.add(r),t.push(r)}return t}function xg(e){let t=Dt(e),n=Array.from(Xt().values()).filter((r)=>Dt(r.cwd)===t);for(let r of n)r.destroy();return n.length}function wa(e,t={}){let n=[],r=[];for(let i of e){let o=Xt().get(i);if(!o)continue;if(t.skipRunning&&o.isRunning()){r.push(o.sessionId||i);continue}o.destroy(),n.push(o.sessionId||i)}return{restarted:n,skipped:r}}function wg(){let e=new Set;for(let[t,n]of Xt())if(n.isRunning())e.add(n.sessionId||t);return[...e]}function wo(){let e=[],t={},n={},r={},i={};for(let[o,s]of Xt())if(s.isRunning()){let a=s.sessionId||o;e.push(a);let c=s.getPhase();if(c){t[a]=c;let d=s.getPhaseStartedAt();if(d!==null)n[a]=d}else{let d=s.getRespondingStartedAt();if(d!==null)r[a]=d}let u=s.getBusyStartedAt();if(u!==null)i[a]=u}return{runningSessionIds:e,phases:t,phaseSince:n,respondingSince:r,busySince:i}}function l_(){if(!globalThis.__piRunningListeners)globalThis.__piRunningListeners=new Set;return globalThis.__piRunningListeners}function _g(e){let t=l_();return t.add(e),()=>{t.delete(e)}}var mg="";function Ft(){let e=l_(),t=wo();if(Qe("running-snapshot","change",`ids=[${t.runningSessionIds.join(",")}] phases=${JSON.stringify(t.phases)} since=${JSON.stringify(t.phaseSince)} responding=${JSON.stringify(t.respondingSince)}`),e.size===0){mg="";return}let n=JSON.stringify(t);if(n===mg)return;mg=n;for(let r of e)try{r(t)}catch{}}function d_(){if(!globalThis.__piAgentEventListeners)globalThis.__piAgentEventListeners=new Set;return globalThis.__piAgentEventListeners}function Dg(e){let t=d_();return t.add(e),()=>{t.delete(e)}}function Sg(e,t){for(let n of d_())try{n(e,t)}catch{}}async function f_(e,t){if(e.isPromptRunning()||e.inner.isStreaming||e.inner.isCompacting||e.inner.isBashRunning)throw Error("Cannot run a shell command while the session is busy");let n=e.inner.executeBash(t.command,void 0,{excludeFromContext:t.excludeFromContext});e.markBusyStart(!0),e.markLocalDrive(!0),e.setPhase({kind:"running_command"}),Ft();try{let r=await n;return o_(e.inner),r}finally{e.markLocalDrive(!1),e.resetIdleTimer(),qe(),e.emit({type:"prompt_done"}),e.setPhase(null),Ft()}}function p_(e){return e.inner.abortBash(),null}async function h_(e,t){if(e.inner.isBashRunning)throw Error("Cannot send a prompt while a shell command is running");let{images:n,streamingBehavior:r}=t;return Qe("ui-chain","2a sdk prompt",`${JSON.stringify(String(t.message).slice(0,80))} streamingBehavior=${r??"-"}`),e.setPromptRunning(!0),e.markBusyStart(!r),e.setPhase({kind:"waiting_model"}),e.touchPromptActivity(),Ft(),e.inner.prompt(t.message,{...n?.length?{images:n}:{},...r?{streamingBehavior:r}:{},source:"rpc"}).then(()=>{if(Qe("ui-chain","2c prompt done"),e.setPromptRunning(!1),e.resetIdleTimer(),!r)e.emit({type:"prompt_done"});Ft()}).catch((i)=>{if(Qe("ui-chain","2c prompt error",i instanceof Error?i.message:String(i)),e.setPromptRunning(!1),e.resetIdleTimer(),qe(),e.emit({type:"prompt_error",errorMessage:i instanceof Error?i.message:String(i)}),!r)e.emit({type:"prompt_done"});Ft()}),null}function BB(e){if(!e.inner.model)return;let n=e.inner.getContextUsage();if(!n||n.tokens==null||n.contextWindow<=0||n.tokens<=n.contextWindow)return n;let r=e.inner.sessionManager.buildSessionProjection(),i=e.inner.sessionManager.getBranch(),o=null;if(r.messages.forEach((u,d)=>{if(u.role!=="assistant")return;let f=u;if(!f.usage||f.stopReason==="aborted"||f.stopReason==="error")return;let p=f.usage;if((p.totalTokens??(p.input??0)+(p.output??0)+(p.cacheRead??0)+(p.cacheWrite??0))>0)o=d}),o==null)return{...n,tokens:null,percent:null};let s=-1,a=0;for(let u of r.entries){let d=a+u.messages.length;if(o<d){s=i.findIndex((f)=>f.id===u.sourceEntry.id);break}a=d}let c=-1;for(let u=i.length-1;u>=0;u--){let d=i[u].type;if(d==="context_edit"||d==="compaction"){c=u;break}}if(s>c)return n;return{...n,tokens:null,percent:null}}function g_(e){let t=e.inner.model,n=BB(e);return{sessionId:e.inner.sessionId,sessionFile:e.inner.sessionFile??"",isStreaming:e.inner.isStreaming,isPromptRunning:e.isPromptRunning(),isBashRunning:e.inner.isBashRunning,isCompacting:e.inner.isCompacting,autoCompactionEnabled:e.inner.autoCompactionEnabled,autoRetryEnabled:e.inner.autoRetryEnabled,model:t?{id:t.id,provider:t.provider}:void 0,messageCount:0,pendingMessageCount:e.inner.pendingMessageCount,queuedMessages:{steering:[...e.inner.getSteeringMessages()],followUp:[...e.inner.getFollowUpMessages()]},contextUsage:n?{percent:n.percent,contextWindow:n.contextWindow,tokens:n.tokens}:null,systemPrompt:e.inner.agent.state?.systemPrompt??"",thinkingLevel:e.inner.agent.state?.thinkingLevel??"off",extensionStatuses:e.getExtensionStatuses(),extensionWidgets:e.getExtensionWidgets()}}var WB=["read","bash","edit","write","grep","find","ls"];function Sl(e,t){if(t.length===0)return[];let n=new Set(WB),r=new Set(e.getActiveToolNames()),i=e.getAllTools().map((o)=>o.name).filter((o)=>!n.has(o)&&(o!=="codemode"||r.has("codemode")));return[...new Set([...t,...i])]}function m_(e){let t=e.inner.getAllTools(),n=new Set(e.inner.getActiveToolNames());return t.map((r)=>({name:r.name,description:r.description,active:n.has(r.name)}))}function y_(e){let t=[];for(let n of e.inner.extensionRunner.getRegisteredCommands())t.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(let n of e.inner.promptTemplates)t.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(let n of e.inner.resourceLoader.getSkills().skills)t.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return{commands:t}}function b_(e,t){let n=t.toolNames;return e.setForceEmptySystemPrompt(n.length===0),e.inner.setActiveToolsByName(Sl(e.inner,n)),e.applyForcedEmptySystemPrompt(),null}import{SessionManager as Tg}from"@earendil-works/pi-coding-agent";import{copyFileSync as jB,readdirSync as qB,statSync as $B,unlinkSync as HB}from"node:fs";import{basename as GB,dirname as _a,join as El}from"node:path";function Tl(e){let t=GB(e);return t.endsWith(".jsonl")?t.slice(0,-6):t}function Eg(e,t){if(!t||t.includes("/")||t.includes("\\")||t.includes(".."))return!1;let n=Tl(e);if(t===`${n}.jsonl`)return!1;return t.startsWith(`${n}.`)}function Cl(e){let t=Tl(e);try{return qB(_a(e)).filter((n)=>{if(!n.startsWith(`${t}.`)||n===`${t}.jsonl`)return!1;return Eg(e,n)}).map((n)=>{let r=$B(El(_a(e),n));return{name:n,size:r.size,modified:r.mtime.toISOString()}}).sort((n,r)=>n.name.localeCompare(r.name))}catch{return[]}}function v_(e,t,n){let r=Tl(e),i=Tl(t);for(let o of n){if(!Eg(e,o))continue;let s=o.slice(r.length);try{jB(El(_a(e),o),El(_a(t),`${i}${s}`))}catch{}}}function x_(e,t){for(let n of t){if(!Eg(e,n))continue;try{HB(El(_a(e),n))}catch{}}}async function w_(e,t){if(e.inner.isBashRunning)throw Error("Cannot fork while a shell command is running");let n=t.entryId,r=e.inner.sessionManager,i=e.inner.sessionFile;if(!r.isPersisted())return{cancelled:!0};if(!i)throw Error("Persisted session is missing a session file");let o=r.getEntry(n);if(!o)throw Error("Invalid entry ID for forking");let s=r.getSessionDir(),a;if(!o.parentId){let d=Tg.create(r.getCwd(),s);d.newSession({parentSession:i}),a=d.getSessionFile()}else{let f=Tg.open(i,s).createBranchedSession(o.parentId);if(!f)throw Error("Failed to create forked session");a=f}let c=Tg.open(a,s).getSessionId(),u=t.copyAuxFiles;if(Array.isArray(u)&&u.every((d)=>typeof d==="string"))v_(i,a,u);return jt(c,a),qe(),e.destroy(),{cancelled:!1,newSessionId:c}}async function __(e,t){if(e.inner.isBashRunning)throw Error("Cannot navigate while a shell command is running");return{cancelled:(await e.inner.navigateTree(t.targetId,{})).cancelled}}class _o extends Error{}function D_(e){return e instanceof _o||e instanceof Error&&/cannot be queued|while a shell command is running/.test(e.message)}async function zB(e,t){let{provider:n,modelId:r}=t,i=e.inner.modelRuntime.getModel(n,r);if(!i)await e.inner.modelRuntime.refresh({allowNetwork:!1}),i=e.inner.modelRuntime.getModel(n,r);if(!i)throw Error(`Model not found: ${n}/${r}`);return await e.inner.setModel(i),Ce(),qe(),{id:i.id,provider:i.provider}}async function VB(e,t){let n=t.level;if(e.inner.setThinkingLevel(n),n==="xhigh"&&e.inner.model?.compat?.thinkingFormat==="deepseek"&&e.inner.agent?.state)e.inner.agent.state.thinkingLevel="xhigh";return qe(),null}async function XB(e,t){try{return await e.withFinalRunningNotification(()=>e.inner.compact(t.customInstructions))}catch(n){if(n instanceof Error&&n.message.includes(Y1))throw Error(J1,{cause:n});throw n}finally{qe()}}async function KB(e,t){let n=t.name?.trim();if(!n)throw Error("Session name cannot be empty");return e.inner.setSessionName(n),qe(),null}async function ZB(e){return{...e.inner.getSessionStats(),sessionName:e.inner.sessionManager.getSessionName()}}async function YB(e,t){return e.inner.setAutoCompactionEnabled(t.enabled),null}async function JB(e,t){let n=t.images;try{await e.inner.steer(t.message,n?.length?n:void 0)}catch(r){if(D_(r))throw new _o(r instanceof Error?r.message:String(r));throw r}return null}async function QB(e,t){let n=t.images;return await e.inner.followUp(t.message,n?.length?n:void 0),null}async function e9(e){if(await e.waitForExtensionsBound(),e.clearExtensionUiState(),e.syncProjectTrust(),await e.inner.reload(),typeof e.inner.bindExtensions!=="function")e.inner.extensionRunner.setUIContext?.(xa(e.extensionUiHost()),"rpc");return e.applyForcedEmptySystemPrompt(),Ce(),{success:!0}}var t9={prompt:h_,abort:(e)=>e.withFinalRunningNotification(()=>e.inner.abort()),get_state:g_,set_model:zB,fork:w_,navigate_tree:__,set_thinking_level:VB,compact:XB,set_session_name:KB,get_session_stats:ZB,get_last_assistant_text:(e)=>({text:e.inner.getLastAssistantText()??""}),set_auto_compaction:YB,clear_queue:(e)=>e.inner.clearQueue(),steer:JB,follow_up:QB,get_tools:m_,get_commands:y_,set_tools:b_,reload:e9,abort_compaction:(e)=>e.inner.abortCompaction(),extension_ui_response:(e,t)=>(e.resolveExtensionUiResponse(t),null),extension_ui_input:(e,t)=>(gg(e.extensionUiHost(),t.id,t.data),null),set_auto_retry:(e,t)=>(e.inner.setAutoRetryEnabled(t.enabled),null),bash:f_,abort_bash:p_};function S_(e){async function t(n,r){let i=t9[n];if(!i)throw Error(`Unsupported command: ${n}`);return i(e,r)}return{dispatch:t}}import{getAgentDir as l9}from"@earendil-works/pi-coding-agent";function n9(e){if(typeof e!=="string")return null;if(e.startsWith("image/"))return"image";return null}function r9(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47}function i9(e){if(!e||e.length%4!==0)return null;let t=e.endsWith("==")?2:e.endsWith("=")?1:0,n=e.length-t;for(let r=0;r<n;r+=1)if(!r9(e.charCodeAt(r)))return null;for(let r=n;r<e.length;r+=1)if(e[r]!=="=")return null;return e.length/4*3-t}function o9(e){if(!e||typeof e!=="object")return!1;let t=e;if(typeof t.data!=="string"||typeof t.mimeType!=="string"||n9(t.mimeType)===null)return!1;let n=i9(t.data);return n!==null&&n<=10485760}function E_(e){if(e===void 0)return null;if(!Array.isArray(e))return"images must be an array";if(e.length>10)return"A message can include at most 10 attachments";for(let t of e){if(!t||typeof t!=="object"||t.type!=="image")return"Each attachment must use the image content block type";if(!o9(t))return"Each attachment must be valid base64 image data of 10MB or smaller"}return null}import{randomUUID as Cg}from"node:crypto";class Ag{deps;pendingUiResponses=new Map;pendingUiRequests=new Map;activeCustomUis=new Map;extensionStatuses=new Map;extensionWidgets=new Map;extensionsBound=!1;extensionBindingPromise=null;extensionBindingError=null;constructor(e){this.deps=e}beginBinding(e={}){this.ensureBound(e).catch((t)=>{console.error("[pi-web] failed to dispatch session_start to extensions:",t instanceof Error?t.message:t)})}async waitUntilReady(){await this.waitForBound()}shouldWaitForExtensions(e){return e==="prompt"||e==="steer"||e==="follow_up"||e==="get_commands"}uiDiagnostics(){return[...this.pendingUiRequests.values()]}cancelPendingUiResponses(){for(let e of this.pendingUiResponses.values())e.cancel();this.pendingUiResponses.clear(),this.pendingUiRequests.clear()}destroyUiState(){this.cancelPendingUiResponses();let e=this.uiHost();for(let t of Array.from(this.activeCustomUis.keys()))vo(e,t,void 0);this.pendingUiResponses.clear(),this.pendingUiRequests.clear()}clearUiState(){this.extensionStatuses.clear(),this.extensionWidgets.clear()}getPendingUiRequests(){return Array.from(this.pendingUiRequests.values())}hasPendingUiRequests(){return this.pendingUiRequests.size>0}resolveExtensionUiResponse(e){let t=this.pendingUiResponses.get(e.id);if(!t){Qe("ui-chain",`4b ui response DROPPED (no pending) id=${e.id.slice(0,8)}`,JSON.stringify(e).slice(0,200));return}Qe("ui-chain",`4 ui response id=${e.id.slice(0,8)}`,JSON.stringify(e).slice(0,200)),t.resolve(e)}getExtensionStatuses(){return Array.from(this.extensionStatuses,([e,t])=>({key:e,text:t}))}getExtensionWidgets(){return Array.from(this.extensionWidgets.values())}replayInto(e){for(let t of this.pendingUiRequests.values())e(t);for(let t of this.extensionWidgets.values())e({type:"extension_ui_request",id:Cg(),method:"setWidget",widgetKey:t.key,widgetLines:t.lines,widgetPlacement:t.placement});for(let[t,n]of this.extensionStatuses)e({type:"extension_ui_request",id:Cg(),method:"setStatus",statusKey:t,statusText:n})}uiHost(){return{activeCustomUis:this.activeCustomUis,pendingUiRequests:this.pendingUiRequests,pendingUiResponses:this.pendingUiResponses,extensionStatuses:this.extensionStatuses,extensionWidgets:this.extensionWidgets,emit:(e)=>this.deps.emit(e)}}ensureBound(e={}){if(e.forceEmptySystemPrompt)this.deps.markForceEmptySystemPrompt();if(this.extensionsBound)return this.deps.applyForcedEmptySystemPrompt(),Promise.resolve();if(this.extensionBindingPromise)return this.extensionBindingPromise;return this.extensionBindingError=null,this.extensionBindingPromise=(async()=>{if(!this.deps.isAlive())return;let t=xa(this.uiHost());if(typeof this.deps.inner.bindExtensions==="function")await this.deps.inner.bindExtensions.call(this.deps.inner,{uiContext:t,mode:"rpc",commandContextActions:this.createCommandContextActions(),shutdownHandler:()=>this.deps.emit({type:"extension_ui_request",id:Cg(),method:"notify",notifyType:"warning",message:"Extension requested shutdown, but shutdown is not supported in Pi Web."}),onError:(r)=>this.deps.emit({type:"extension_error",extensionPath:r.extensionPath,event:r.event,error:r.error})});else this.deps.inner.extensionRunner.setUIContext?.(t,"rpc");this.extensionsBound=!0,this.deps.applyForcedEmptySystemPrompt(),console.log(`[pi-web] session_start dispatched to extensions for session ${this.deps.inner.sessionId}`)})().catch((t)=>{throw this.extensionBindingError=t,t}),this.extensionBindingPromise}async waitForBound(){try{if(this.extensionBindingPromise)await this.extensionBindingPromise}catch(e){throw e instanceof Error?e:Error(String(e))}if(this.extensionBindingError)throw this.extensionBindingError instanceof Error?this.extensionBindingError:Error(String(this.extensionBindingError))}createCommandContextActions(){return{waitForIdle:async()=>{await this.deps.inner.agent.waitForIdle?.()},newSession:async()=>({cancelled:!0}),fork:async()=>({cancelled:!0}),navigateTree:async(e,t)=>({cancelled:(await this.deps.inner.navigateTree(e,{summarize:t?.summarize})).cancelled}),switchSession:async()=>({cancelled:!0}),reload:async()=>{this.extensionStatuses.clear(),this.extensionWidgets.clear(),this.deps.syncProjectTrust(),await this.deps.inner.reload({beforeSessionStart:()=>{this.deps.inner.extensionRunner.setUIContext?.(xa(this.uiHost()),"rpc")}}),this.deps.applyForcedEmptySystemPrompt()}}}}import{existsSync as s9}from"node:fs";var T_=(()=>{if(process.env.PI_WEB_E2E!=="1")return 600000;let e=Number(process.env.PI_SESSION_IDLE_MS);return Number.isFinite(e)&&e>0?e:600000})();class kg{idleTimer=null;deps;constructor(e){this.deps=e}reset(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=setTimeout(()=>{if(this.deps.isRunning()){if(this.deps.isPromptRunning()&&Date.now()-this.deps.getLastPromptActivityAt()>=T_){if(this.deps.isBashRunning()||this.deps.hasPendingUiRequests()){this.reset();return}this.settleStalledRun();return}this.reset();return}let e=this.deps.sessionFile();if(e&&!s9(e)){this.reset();return}this.deps.destroy()},T_)}stop(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=null}settleStalledRun(){try{this.deps.unlockStall()}catch{}this.deps.setPromptRunning(!1),this.deps.emit({type:"prompt_error",errorMessage:"Agent run stalled (no activity for 10 minutes) — reset to idle. "+"If this keeps happening, restart the pi-web server."}),this.deps.emit({type:"prompt_done"}),this.reset(),this.deps.notifyRunningChange()}}function C_(e){let t=e?.contentIndex;if(typeof t!=="number")return null;let n=e?.partial?.content?.[t];if(n?.type!=="toolCall")return null;let r=n;if(typeof r.id!=="string"||!r.id)return null;return{id:r.id,name:typeof r.name==="string"&&r.name?r.name:r.id}}var a9=120000,c9=5000,u9=new Set(["agent_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end","bash_execution_update","auto_compaction_start","compaction_start"]);class Ug{phase=null;phaseStartedAt=null;respondingStartedAt=null;busyStartedAt=null;runningToolNames=new Map;promptRunning=!1;lastPromptActivityAt=0;externalActivityAt=null;roundActive=!1;localDriveActive=!1;localDriveEndedAt=null;getPhase(){return this.phase}getPhaseStartedAt(){return this.phaseStartedAt}getRespondingStartedAt(){return this.respondingStartedAt}getBusyStartedAt(){return this.busyStartedAt}isPromptRunning(){return this.promptRunning}isExternalActivityFresh(){return this.externalActivityAt!==null&&Date.now()-this.externalActivityAt<a9}isRoundActive(){return this.roundActive}setPromptRunning(e){if(this.promptRunning=e,e)this.localDriveActive=!0,this.localDriveEndedAt=null;else this.localDriveActive=!1,this.localDriveEndedAt=Date.now()}markLocalDrive(e){if(e)this.localDriveActive=!0,this.localDriveEndedAt=null;else this.localDriveActive=!1,this.localDriveEndedAt=Date.now()}isLocallyDriven(){return this.localDriveActive||this.localDriveEndedAt!==null&&Date.now()-this.localDriveEndedAt<c9}markBusyStart(e){if(this.busyStartedAt===null||e)this.busyStartedAt=Date.now()}touchPromptActivity(){this.lastPromptActivityAt=Date.now()}getLastPromptActivityAt(){return this.lastPromptActivityAt}setPhase(e){let t=(this.phase?.kind??null)!==(e?.kind??null);if(this.phase=e,!e){if(this.phaseStartedAt=null,this.busyStartedAt!==null)this.respondingStartedAt=Math.max(this.respondingStartedAt??Date.now(),this.busyStartedAt);return}this.respondingStartedAt=null;let n=t||this.phaseStartedAt===null?Date.now():this.phaseStartedAt;this.phaseStartedAt=this.busyStartedAt!==null?Math.max(n,this.busyStartedAt):n}updatePhaseFromEvent(e){if(!this.promptRunning&&!this.isLocallyDriven()&&u9.has(e.type))this.externalActivityAt=Date.now();switch(e.type){case"agent_start":this.onAgentStart();break;case"agent_end":this.onAgentEnd();break;case"message_update":this.onMessageUpdate(e);break;case"auto_retry_start":this.onAutoRetryStart(e);break;case"auto_retry_end":this.onAutoRetryEnd();break;case"tool_execution_start":this.onToolStart(e);break;case"tool_execution_end":this.onToolEnd(e);break}}onAgentStart(){this.roundActive=!0,this.setPhase({kind:"waiting_model"})}onAgentEnd(){this.roundActive=!1,this.externalActivityAt=null,this.runningToolNames.clear(),this.setPhase(null)}toolsOrFallback(e){return this.runningToolNames.size>0?{kind:"running_tools",tools:[...this.runningToolNames.entries()].map(([t,n])=>({id:t,name:n}))}:e}onMessageUpdate(e){let t=e.assistantMessageEvent,n=t?.type??"";if(n.startsWith("thinking")){this.setPhase(this.toolsOrFallback({kind:"thinking"}));return}if(n==="toolcall_start"||n==="toolcall_delta"){let r=C_(t);if(r)this.runningToolNames.set(r.id,r.name);this.syncRunningToolsPhase();return}if(n==="toolcall_end")return;this.setPhase(this.toolsOrFallback(null))}onAutoRetryStart(e){let t=e;this.setPhase({kind:"retrying",attempt:t.attempt??1,maxAttempts:t.maxAttempts??1,errorMessage:t.errorMessage})}onAutoRetryEnd(){this.setPhase(null)}onToolStart(e){let t=e.toolCallId;if(t)this.runningToolNames.set(t,e.toolName??t);this.syncRunningToolsPhase()}onToolEnd(e){let t=e.toolCallId;if(t)this.runningToolNames.delete(t);this.syncRunningToolsPhase()}syncRunningToolsPhase(){this.setPhase(this.runningToolNames.size>0?{kind:"running_tools",tools:[...this.runningToolNames.entries()].map(([e,t])=>({id:e,name:t}))}:{kind:"waiting_model"})}}var d9=1000,f9=new Set(["agent_start","agent_end","agent_settled","message_update","tool_execution_start","tool_execution_end","auto_compaction_start","auto_compaction_end","compaction_start","compaction_end","auto_retry_start","auto_retry_end"]),p9=new Set(["agent_end","agent_settled","auto_compaction_end","compaction_end"]),h9=new Set(["agent_start","message_update","message_end","tool_execution_start","tool_execution_update","tool_execution_end","bash_execution_update","agent_end","agent_settled","auto_compaction_start","auto_compaction_end","compaction_start","compaction_end","prompt_done","prompt_error"]);class Al{inner;listeners=[];forceEmptySystemPrompt=!1;savedTransformContext;unsubscribe=null;idle=new kg({isRunning:()=>this.isRunning(),isPromptRunning:()=>this.phases.isPromptRunning(),getLastPromptActivityAt:()=>this.phases.getLastPromptActivityAt(),isBashRunning:()=>this.inner.isBashRunning,hasPendingUiRequests:()=>this.extensions.hasPendingUiRequests(),sessionFile:()=>this.sessionFile,setPromptRunning:(e)=>this.phases.setPromptRunning(e),emit:(e)=>this.emit(e),destroy:()=>this.destroy(),notifyRunningChange:()=>Ft(),unlockStall:()=>{this.cancelPendingUiResponses(),this.inner.abort().catch(()=>{})}});onDestroyCallback=null;bufferedEvents=[];lastStreamingUpdate=null;_alive=!0;commands=null;phases=new Ug;extensions;constructor(e){this.inner=e;this.extensions=new Ag({inner:this.inner,isAlive:()=>this._alive,emit:(t)=>this.emit(t),markForceEmptySystemPrompt:()=>{this.forceEmptySystemPrompt=!0},applyForcedEmptySystemPrompt:()=>this.applyForcedEmptySystemPrompt(),syncProjectTrust:()=>this.syncProjectTrust()})}getCommands(){if(!this.commands)this.commands=S_(this.commandDeps());return this.commands}get sessionId(){return this.inner.sessionId}get sessionFile(){return this.inner.sessionFile??""}get cwd(){return this.inner.sessionManager.getCwd()}hasMessages(){return this.inner.sessionManager.getBranch().some((e)=>e.type==="message")}isAlive(){return this._alive}isRunning(){return this._alive&&(this.phases.isPromptRunning()||this.inner.isStreaming||this.inner.isCompacting||this.inner.isBashRunning||this.phases.isRoundActive()||this.phases.isExternalActivityFresh())}start(){this.unsubscribe=this.inner.subscribe((e)=>{if(e.type==="agent_end")qe();if(p9.has(e.type))this.idle.reset();if(h9.has(e.type))this.phases.touchPromptActivity();if(this.phases.updatePhaseFromEvent(e),this.emit(e),f9.has(e.type))Ft()}),this.idle.reset(),Ft()}getPhase(){return this.phases.getPhase()}getPhaseStartedAt(){return this.phases.getPhaseStartedAt()}getRespondingStartedAt(){return this.phases.getRespondingStartedAt()}getBusyStartedAt(){return this.phases.getBusyStartedAt()}setPhase(e){this.phases.setPhase(e)}setForceEmptySystemPrompt(e){this.forceEmptySystemPrompt=e,this.applyForcedEmptySystemPrompt()}beginExtensionBinding(e={}){this.extensions.beginBinding(e)}async waitUntilReady(){await this.extensions.waitUntilReady()}shouldWaitForExtensions(e){return this.extensions.shouldWaitForExtensions(e)}async withFinalRunningNotification(e){try{return await e()}finally{this.idle.reset(),Ft()}}applyForcedEmptySystemPrompt(){let e=this.inner.agent;if(!e)return;if(this.forceEmptySystemPrompt){if(this.savedTransformContext!==void 0)return;let t=e.transformContext;this.savedTransformContext=t,e.transformContext=async(n,r)=>{let i=t?await t(n,r):n;return[{role:"system",content:"",timestamp:Date.now()},...i.filter((s)=>s.role!=="system")]}}else if(this.savedTransformContext!==void 0)e.transformContext=this.savedTransformContext,this.savedTransformContext=void 0}getStreamingUpdate(){return this.lastStreamingUpdate}trackStreaming(e){if(e.type==="message_update"){let t=e.message;if(t&&typeof t==="object"&&t.role!=="user"){this.lastStreamingUpdate=e;return}}if(e.type==="message_end"||e.type==="agent_end")this.lastStreamingUpdate=null}emit(e){if(this.trackStreaming(e),Sg(this.sessionId,e),this.listeners.length===0){if(this.bufferedEvents.push(e),this.bufferedEvents.length>d9)this.bufferedEvents.shift();return}for(let t of this.listeners)t(e)}onEvent(e){let t=this.bufferedEvents;this.bufferedEvents=[];for(let n of t)e(n);return this.listeners.push(e),this.extensions.replayInto(e),()=>{let n=this.listeners.indexOf(e);if(n!==-1)this.listeners.splice(n,1)}}onDestroy(e){this.onDestroyCallback=e}commandDeps(){return{inner:this.inner,emit:(e)=>this.emit(e),setPhase:(e)=>this.setPhase(e),resetIdleTimer:()=>this.idle.reset(),isPromptRunning:()=>this.phases.isPromptRunning(),setPromptRunning:(e)=>{this.phases.setPromptRunning(e)},markBusyStart:(e)=>this.phases.markBusyStart(e),markLocalDrive:(e)=>this.phases.markLocalDrive(e),touchPromptActivity:()=>this.phases.touchPromptActivity(),setForceEmptySystemPrompt:(e)=>this.setForceEmptySystemPrompt(e),waitForExtensionsBound:()=>this.extensions.waitUntilReady(),withFinalRunningNotification:(e)=>this.withFinalRunningNotification(e),clearExtensionUiState:()=>this.extensions.clearUiState(),syncProjectTrust:()=>this.syncProjectTrust(),extensionUiHost:()=>this.extensions.uiHost(),resolveExtensionUiResponse:(e)=>this.extensions.resolveExtensionUiResponse(e),applyForcedEmptySystemPrompt:()=>this.applyForcedEmptySystemPrompt(),getExtensionStatuses:()=>this.extensions.getExtensionStatuses(),getExtensionWidgets:()=>this.extensions.getExtensionWidgets(),destroy:()=>this.destroy()}}async send(e){this.idle.reset();let t=e.type;if(this.shouldWaitForExtensions(t))await this.extensions.waitUntilReady();if(t==="prompt"||t==="steer"||t==="follow_up"){let n=E_(e.images);if(n)throw Error(n)}return this.getCommands().dispatch(t,e)}destroy(){if(!this._alive)return;if(this._alive=!1,this.idle.stop(),this.inner.isBashRunning)this.inner.abortBash();this.unsubscribe?.(),this.extensions.destroyUiState(),this.onDestroyCallback?.(),Ft()}cancelPendingUiResponses(){this.extensions.cancelPendingUiResponses()}diagnostics(){return{alive:this._alive,running:this.isRunning(),promptRunning:this.phases.isPromptRunning(),lastPromptActivityAt:this.phases.getLastPromptActivityAt(),lastPromptActivityAgeMs:Date.now()-this.phases.getLastPromptActivityAt(),bufferedEvents:this.bufferedEvents.length,pendingUiRequests:this.extensions.uiDiagnostics()}}getPendingUiRequests(){return this.extensions.getPendingUiRequests()}resolveExtensionUiResponse(e){this.extensions.resolveExtensionUiResponse(e)}getExtensionStatuses(){return this.extensions.getExtensionStatuses()}getExtensionWidgets(){return this.extensions.getExtensionWidgets()}syncProjectTrust(){let e=Oe(this.cwd,l9());this.inner.settingsManager.setProjectTrusted(e.trusted)}}async function A_(e,t,n){if(!t.model&&!t.thinkingLevel)return{modelDefaultChanged:!1};let r=!1;if(t.model&&n.model&&t.model.provider===n.model.provider&&t.model.modelId===n.model.modelId)e.setDefaultModelAndProvider(n.model.provider,n.model.modelId),r=!0;if(t.thinkingLevel&&(n.supportsThinking||n.thinkingLevel!=="off"))e.setDefaultThinkingLevel(n.thinkingLevel);return await e.flush(),{modelDefaultChanged:r}}function _9(e,t,n,r){return{...e?{requestedModel:e}:{},...t&&n?{defaultModel:{provider:t,modelId:n}}:{},...r?{thinkingLevel:r}:{}}}function D9(e){if(e===void 0)return;return e.length===0?[]:void 0}function S9(e,t){return{...e.model?{model:e.model}:{},...e.thinkingLevel?{thinkingLevel:e.thinkingLevel}:{},...e.scopedModels.length>0?{scopedModels:e.scopedModels}:{},...t!==void 0?{tools:t}:{}}}function E9(e,t){return{...e?{model:e}:{},...t?{thinkingLevel:t}:{}}}function T9(e,t,n){return{...e?{model:{provider:e.provider,modelId:e.id}}:{},thinkingLevel:t,supportsThinking:n}}var Rg=ze("rpc-start"),C9=60000;async function Rr(e,t,n,r={}){let{toolNames:i,initialModel:o,thinkingLevel:s}=r,a=Xt(),c=s_(),u=a_(),d=a.get(e);if(d?.isAlive())return{session:d,realSessionId:e};let f=c.get(e);if(f){let x=Date.now()-(u.get(e)??0);if(x<C9)return f;Rg(`stale lock sid=${e} age=${Math.round(x/1000)}s — restarting fresh`),c.delete(e),u.delete(e)}let p;if(t)p=k_.open(t,void 0);else{if(!n)throw Error("cwd is required for a new session");p=k_.create(n,void 0)}let h=p.getCwd(),g=u_(h),b=performance.now(),v=(x)=>Rg(`sid=${e} ${x} +${Math.round(performance.now()-b)}ms`);v("cold start begin");let y=(async()=>{w9();let x=x9();await pg(h,x);let m=D9(i),w=ho(h,x),D=[b9(),y9({}),v9()],T=r.fixtureExtensionPaths??yl(e);v("creating services");let _=await m9({cwd:h,agentDir:x,...w?{resourceLoaderReloadOptions:w}:{},resourceLoaderOptions:{extensionFactories:D,...T.length>0?{additionalExtensionPaths:T}:{}}}),A=await dl(_.modelRuntime,_.settingsManager.getEnabledModels()),E=_.settingsManager.getDefaultProvider(),M=_.settingsManager.getDefaultModel(),C=p.getBranch().some((F)=>F.type==="message")?{scopedModels:[...A.scopedModels]}:fl(A,_9(o,E,M,s));v("services ready — spawning agent session");let{session:L}=await g9({services:_,sessionManager:p,...S9(C,m)});if((await A_(_.settingsManager,E9(o,s),T9(L.model,L.thinkingLevel,L.supportsThinking()))).modelDefaultChanged)Ce();if(i&&i.length>0)L.setActiveToolsByName(Sl(L,i));let H=new Al(L);if(i?.length===0)H.setForceEmptySystemPrompt(!0);H.start();let{sessionId:S,sessionFile:R}=L;if(R)jt(S,R);let k=a.get(S);if(k&&k!==H)throw Rg(`sid=${e} duplicate settle — destroying late instance`),H.destroy(),Error(`session ${e} already registered by a newer instance`);return H.onDestroy(()=>a.delete(S)),a.set(S,H),v("cold start done"),H.beginExtensionBinding({forceEmptySystemPrompt:i?.length===0}),{session:H,realSessionId:S}})().finally(()=>{c.delete(e),g()});return c.set(e,y),u.set(e,Date.now()),y.catch(()=>{}),y}var A9=5000,k9=60,U_=60000,kl=new Map,Ul=new Set,Fg=new Map,Da=new Map;function U9(){let e=Zn().preferences.gitAutoFetchIntervalSec;return typeof e==="number"&&Number.isFinite(e)?e:k9}function R9(e){let t=Fg.get(e);if(t)return t;let n=Kh();Fg.set(e,n.promise);let r;return(async()=>{try{let i=await Promise.race([(async()=>{let o=await og(e);if(!o.ok)return{ok:!1,error:o.error};let s=await cl(e);return{ok:!0,snapshot:{ahead:s.ahead,behind:s.behind,updatedAt:Date.now()}}})(),new Promise((o,s)=>{r=setTimeout(()=>s(Error(`git fetch timeout after ${U_/1000}s`)),U_),r.unref?.()})]);n.resolve(i)}catch(i){n.resolve({ok:!1,error:i instanceof Error?i.message:String(i)})}finally{if(r)clearTimeout(r);Fg.delete(e)}})(),n.promise}async function R_(e){let t=new Map;for(let n of e){let r=null;try{r=await Ut(n)}catch{r=null}if(!r)continue;let i=t.get(r);if(i)i.push(n);else t.set(r,[n])}return t}async function F_(e,t){await Promise.all(Array.from(e,async([n,r])=>{let i=await R9(n);if(!i.ok){console.warn(`[git-autofetch] fetch failed for ${n}: ${i.error}`);return}for(let o of r)kl.set(Dt(o),i.snapshot);Da.set(n,t)}))}function F9(e){let t=new Set(e);for(let n of[...Ul])if(!e.includes(n))Ul.delete(n);for(let n of[...kl.keys()])if(!t.has(n))kl.delete(n)}function P9(e){for(let t of[...Da.keys()])if(!e.has(t))Da.delete(t)}async function O9(e,t){let n=e.filter((i)=>!Ul.has(i));if(n.length===0)return;let r=await R_(n);await F_(r,t);for(let i of n)Ul.add(i)}async function I9(e,t,n){let r=new Map;for(let[i,o]of e){let s=Da.get(i)??0;if(t-s<n*1000)continue;r.set(i,o)}if(r.size===0)return;await F_(r,t)}async function M9(e=Date.now()){let t=vg();if(F9(t),t.length===0){Da.clear();return}let n=U9(),r=await R_(t);if(P9(r),n<=0){await O9(t,e);return}await I9(r,e,n)}function P_(e){return kl.get(Dt(e))??null}function O_(){setInterval(()=>{M9()},A9).unref()}import{isIP as I_}from"node:net";function M_(e){return(e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e).toLowerCase().replace(/\.$/,"")}function N_(e){if(!e||/[\s/@\\]/.test(e))return null;try{let t=new URL(`http://${e}`);if(t.username||t.password||t.pathname!=="/"||t.search||t.hash)return null;return M_(t.hostname)}catch{return null}}function N9(e){let t=e?.trim();if(!t)return null;return I_(t)?M_(t):N_(t)}function L9(e){return e==="localhost"||e.endsWith(".localhost")}function L_(){return[process.env.PI_WEB_HOSTNAME,...process.env.PI_WEB_ALLOWED_HOSTS?.split(",")??[]].filter((e)=>Boolean(e?.trim()))}function B_(e){try{return new URL(e).origin}catch{return null}}function B9(e){let t=new URL(e.url),n=e.headers.get("host");return n?B_(`${t.protocol}//${n}`):null}function W9(e){if(e.method!=="GET"||e.headers.get("sec-fetch-mode")!=="navigate"||e.headers.get("sec-fetch-dest")!=="document"||e.headers.get("sec-fetch-user")!=="?1")return!1;try{return/^\/api\/sessions\/[^/]+\/export$/.test(new URL(e.url).pathname)}catch{return!1}}function Pg(e,t=L_()){let n=e.headers.get("host"),r=n?N_(n):null;if(!r)return!1;if(L9(r)||I_(r))return!0;return t.some((i)=>N9(i)===r)}function j9(e){let t=e.headers.get("origin");if(e.headers.get("sec-fetch-site")==="cross-site")return!1;if(!t)return!0;let r=B9(e);return r!==null&&B_(t)===r}function q9(e){return e.headers.has("origin")||e.headers.has("sec-fetch-site")}function Pt(e,t=L_()){if(!Pg(e,t))return!1;if(W9(e))return!0;return!q9(e)||j9(e)}function Fr(e){let t=e.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase();return t==="application/json"||Boolean(t?.startsWith("application/")&&t.endsWith("+json"))}import{createHash as $9,timingSafeEqual as H9}from"node:crypto";var G9="pi";function W_(e){return $9("sha256").update(e,"utf8").digest()}function j_(e,t){return H9(W_(e),W_(t))}function Sa(e=process.env.PI_WEB_PASSWORD){return typeof e==="string"&&e.length>0}function Rl(e,t=process.env.PI_WEB_PASSWORD){if(!Sa(t)||!e)return!1;let n=/^Basic\s+(\S+)$/i.exec(e);if(!n)return!1;let r;try{let u=Buffer.from(n[1],"base64");if(u.toString("base64")!==n[1])return!1;r=new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{return!1}let i=r.indexOf(":");if(i===-1)return!1;let o=r.slice(0,i),s=r.slice(i+1),a=j_(o,G9),c=j_(s,t);return a&&c}var q_=ze("mount"),z9=["GET","POST","PUT","PATCH","DELETE"];function Y(e,t,n){let r=t.split("/").filter(Boolean),i=[],o=new Map;for(let a of r){let c=a.match(/^\[\.\.\.(.+)\]$/),u=a.match(/^\[(.+)\]$/);if(c)i.push(`:${c[1]}{.+}`),o.set(c[1],{hono:c[1],catchAll:!0});else if(u)i.push(`:${u[1]}`),o.set(u[1],{hono:u[1],catchAll:!1});else i.push(a)}let s=`/${i.join("/")}`;for(let a of z9){let c=n[a];if(typeof c!=="function")continue;let u=c;e.on(a,s,async(d)=>{let f=performance.now();q_(`${a} ${d.req.path}`,"received");let p={};for(let[g,{hono:b,catchAll:v}]of o)if(v){let y=d.req.param(b)??"";p[g]=y===""?[]:y.split("/")}else p[g]=d.req.param(b)??"";let h=await u(d.req.raw,{params:Promise.resolve(p)});return q_(`${a} ${d.req.path}`,`${h.status} ${Math.round(performance.now()-f)}ms done`),h})}}var Mg={};Z(Mg,{GET:()=>t6});import{tmpdir as Q9}from"node:os";import{Readable as e6}from"node:stream";import{constants as Og}from"node:fs";import{lstat as V9,open as X9}from"node:fs/promises";import{basename as K9,dirname as Z9,resolve as $_}from"node:path";var Fl=5242880;function H_(e,t){let n=$_(e);if(Z9(n)!==$_(t))return null;if(!/^pi-bash-[A-Za-z0-9_-]+\.log$/.test(K9(n)))return null;return n}async function Ig(e){if(!(await V9(e)).isFile())throw Error("Bash output path is not a regular file");let n=typeof Og.O_NOFOLLOW==="number"?Og.O_NOFOLLOW:0,r=await X9(e,Og.O_RDONLY|n);try{let i=await r.stat();if(!i.isFile())throw Error("Bash output path is not a regular file");return{handle:r,fileInfo:i}}catch(i){throw await r.close(),i}}async function G_(e,t=Fl){let{handle:n,fileInfo:r}=await Ig(e);try{if(r.size>t)return{tooLarge:!0,size:r.size};let i=Buffer.alloc(r.size),o=0;while(o<i.length){let s=await n.read(i,o,i.length-o,o);if(s.bytesRead===0)break;o+=s.bytesRead}return{tooLarge:!1,content:i.subarray(0,o).toString("utf8"),size:o}}finally{await n.close()}}var Y9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function z_(e){return!!e&&Y9.test(e)}function V_(e,t){return t.some((n)=>n.type==="message"&&n.message.role==="bashExecution"&&n.message.fullOutputPath===e)}async function X_(e,t){if(!z_(t))return!1;try{let n=await De(t);if(!n)return!1;return V_(e,wl(n))}catch{return!1}}async function t6(e,{params:t}){let{id:n}=await t,r=null,i=!1;try{let s=new URL(e.url);r=s.searchParams.get("path"),i=s.searchParams.get("download")==="1"}catch{return Response.json({error:"invalid url"},{status:400})}if(!r)return Response.json({error:"path required"},{status:400});let o=H_(r,Q9());if(!o)return Response.json({error:"invalid path"},{status:400});if(!await X_(o,n))return Response.json({error:"forbidden"},{status:403});try{if(i){let{handle:a}=await Ig(o),c=e6.toWeb(a.createReadStream());return new Response(c,{headers:{"Content-Type":"text/plain; charset=utf-8","Content-Disposition":'attachment; filename="bash-output.log"',"Cache-Control":"no-store"}})}let s=await G_(o);if(s.tooLarge)return Response.json({error:`Full output is too large to display (limit ${Fl} bytes)`,data:{size:s.size,maxBytes:Fl}},{status:413});return Response.json({success:!0,data:{output:s.content}})}catch{return Response.json({error:"full output unavailable"},{status:404})}}var Ng={};Z(Ng,{GET:()=>n6});async function n6(e,{params:t}){let{id:n}=await t,r=Be(n);if(!r?.isAlive())return Response.json({error:"Session not found or not alive"},{status:404});return Response.json({success:!0,data:r.diagnostics()})}var Gg={};Z(Gg,{GET:()=>W6,POST:()=>B6,sendWithDeferredModelSwitch:()=>Hg,setFakeBusySession:()=>To});import{resolve as r6}from"node:path";var i6="piE2eFixtureDir",o6="piE2eFixtureDir";function Lg(e){return r6(process.cwd(),e)}function s6(e){if(!e)return{};let t={};for(let n of e.split(";")){let r=n.indexOf("=");if(r===-1)continue;t[n.slice(0,r).trim()]=n.slice(r+1).trim()}return t}function ae(e){let t=s6(e.headers.get("cookie"))[i6];if(t)try{return Lg(decodeURIComponent(t))}catch{return Lg(t)}let n=new URL(e.url).searchParams.get(o6);return n?Lg(n):void 0}So();import{mkdir as g6,readFile as m6,rename as y6,writeFile as b6}from"node:fs/promises";import{dirname as v6,join as x6}from"node:path";import{getAgentDir as w6}from"@earendil-works/pi-coding-agent";var _6=[{name:"readonly",tools:["read","grep","find","ls"],description:{en:"Read-only tools (read/grep/find/ls)","zh-CN":"仅只读工具(read/grep/find/ls)"}},{name:"full",tools:["bash","read","edit","write","grep","find","ls"],description:{en:"All built-in tools enabled (except codemode)","zh-CN":"内置工具全开(codemode除外)"}},{name:"codemode",tools:["codemode"],description:{en:"Codemode only","zh-CN":"仅激活codemode"}}],D6=new Set(["off","default"]),Z_=_6;function Y_(){return x6(w6(),"pi-web","tool-presets.json")}function Bg(e){if(!Array.isArray(e))return null;let t=new Set,n=[];for(let r of e){if(typeof r!=="object"||r===null)return null;let{name:i,tools:o,description:s}=r;if(typeof i!=="string"||i.trim().length===0)return null;let a=i.trim();if(t.has(a))return null;if(!Array.isArray(o)||o.some((u)=>typeof u!=="string"||u.trim()===""))return null;t.add(a);let c=S6(s);n.push({name:a,tools:o.map((u)=>u.trim()),...c?{description:c}:{}})}return n}function S6(e){if(typeof e==="string"){let r=e.trim();return r.length>0?r:void 0}if(typeof e!=="object"||e===null||Array.isArray(e))return;let t=e,n={};for(let r of["en","zh-CN"]){let i=t[r];if(typeof i==="string"&&i.trim().length>0)n[r]=i.trim()}if(Object.keys(n).length===0)return;return n}function J_(e){return e.filter((t)=>!D6.has(t.name))}async function Eo(){try{let e=await m6(Y_(),"utf8"),t=Bg(JSON.parse(e));return t?{presets:J_(t),exists:!0}:{presets:Z_,exists:!1}}catch{return{presets:Z_,exists:!1}}}async function Q_(e){let t=Y_();await g6(v6(t),{recursive:!0});let n=`${t}.tmp`;await b6(n,`${JSON.stringify(J_(e),null,2)}
|
|
285
285
|
`,"utf8"),await y6(n,t)}var E6=".pi-web.json";function Ol(e){return e+E6}function Il(e){let t=St(Ol(e));return t?.version===1?t:null}function eD(e,t){un(Ol(e),t)}async function Ml(e,t){let r=Il(t)?.toolPreset;if(!r||typeof r!=="string")return;try{let{presets:i}=await Eo(),o=i.find((s)=>s.name===r);if(!o)return;await e.send({type:"set_tools",toolNames:[...o.tools]})}catch(i){console.warn(`[sidecar] replay toolPreset failed for ${t}:`,i)}}import{randomUUID as R6}from"node:crypto";import{existsSync as F6}from"node:fs";import{readdirSync as A6}from"node:fs";import{homedir as iD}from"node:os";import Nl from"node:path";import{realpathSync as tD}from"node:fs";import Wg from"node:path";var T6=/^[a-zA-Z]:[\\/]/;function nD(e){return T6.test(e)||e.startsWith("\\\\")||e.startsWith("//")}function C6(e,t){for(let n of t){let r=nD(e)||nD(n),i=r?Wg.win32:Wg,o=r?"\\":Wg.sep,s=i.resolve(e),a=i.resolve(n),c=r?s.toLowerCase():s,u=r?a.toLowerCase():a,d=u.endsWith(o)?u:u+o;if(c===u||c.startsWith(d))return!0}return!1}function rD(e,t){let n;try{n=tD(e)}catch{return!1}let r=new Set;for(let i of t)try{r.add(tD(i))}catch{}return C6(n,r)}var k6=5000,U6=/^[a-zA-Z]:[\\/]/;function Ie(e){return U6.test(e)||e.startsWith("\\\\")||e.startsWith("//")}async function oe(){let e=Date.now(),t=globalThis.__piAllowedRootsCache;if(t&&t.expiresAt>e)return t.roots;let n=await Ur(),r=new Set;for(let i of n){if(i.cwd)r.add(Ke(i.cwd));if(i.projectRoot)r.add(Ke(i.projectRoot))}try{for(let i of A6(iD()))if(/^pi-cwd-\d{8}$/.test(i))r.add(Ke(Nl.join(iD(),i)))}catch{}for(let i of cg())r.add(i);return globalThis.__piAllowedRootsCache={roots:r,expiresAt:e+k6},r}function Re(e,t){for(let n of t){let r=Ie(e)||Ie(n),i=r?Nl.win32:Nl,o=r?"\\":Nl.sep,s=i.resolve(e),a=i.resolve(n),c=r?s.toLowerCase():s,u=r?a.toLowerCase():a,d=u.endsWith(o)?u:u+o;if(c===u||c.startsWith(d))return!0}return!1}function ce(e,t){return rD(e,t)}var P6=new Set(["off","minimal","low","medium","high","xhigh","max"]);function O6(e){if(e===void 0)return;if(typeof e==="string"&&P6.has(e))return e;throw Error(`Invalid thinking level: ${String(e)}`)}function jg(e){if(!e||e.id==="unknown"||e.provider==="unknown")return null;return{provider:e.provider,modelId:e.id}}async function I6(e,t,{provider:n,modelId:r,thinkingLevel:i}){if(n&&r)try{await e.send({type:"set_model",provider:n,modelId:r})}catch(o){console.error(`[api] set_model on reused session ${t} failed:`,o)}if(i)try{await e.send({type:"set_thinking_level",level:i})}catch(o){console.error(`[api] set_thinking_level on reused session ${t} failed:`,o)}}async function M6(e,t){let n=yg(e);if(!n)return;let r=Be(n);if(!r?.isAlive())return;await I6(r,n,t);let i=await r.send({type:"get_state"});return Response.json({success:!0,sessionId:n,data:null,model:jg(i.model),thinkingLevel:i.thinkingLevel})}function N6(e,{provider:t,modelId:n,thinkingLevel:r},i){return{...i?{toolNames:i}:{},...t&&n?{initialModel:{provider:t,modelId:n}}:{},...r?{thinkingLevel:r}:{},...e?{fixtureExtensionPaths:ya(e)}:{}}}async function L6(e,{provider:t,modelId:n},r,i){if(t&&n&&r!=="ensure_session"&&(i.model?.provider!==t||i.model?.id!==n))await e.send({type:"set_model",provider:t,modelId:n})}async function oD(e,t){let{cwd:n,...r}=e;if(!n||typeof n!=="string")return Response.json({error:"cwd is required"},{status:400});if(!F6(n))return Response.json({error:`Directory does not exist: ${n}`},{status:400});let{provider:i,modelId:o,toolNames:s,thinkingLevel:a,...c}=r;if(i&&!o||!i&&o)throw Error("provider and modelId must be provided together");let u={provider:i,modelId:o,thinkingLevel:O6(a)};if(c.type==="ensure_session"){let b=await M6(n,u);if(b)return b}let d=`__new__${R6()}`,{session:f,realSessionId:p}=await Rr(d,"",n,N6(t,u,s));_t(n),qe();let h=await f.send({type:"get_state"});if(await L6(f,u,c.type,h),c.type==="ensure_session")return Response.json({success:!0,sessionId:p,data:null,model:jg(h.model),thinkingLevel:h.thinkingLevel});let g=await f.send(c);return Response.json({success:!0,sessionId:p,data:g,model:jg(h.model),thinkingLevel:h.thinkingLevel})}var Ea=ze("oom-debug"),qg=ze("oom-stress");async function sD(e){Ea("oomDebugHandler called",`session ${e}`);let t=30,n=Be(e);if(!n?.isAlive())return Ea("session not alive or not found",`session ${e}`),Response.json({error:"Session not found"},{status:404});return(async()=>{To(e,!0);try{let r=(o)=>{n.emit(o)};r({type:"agent_start"}),await new Promise((o)=>setTimeout(o,t*1000));let i=`✅ OOM debug: fake response after ${t}s wait.`;r({type:"message_start",message:{role:"assistant",content:[]}}),r({type:"message_update",message:{role:"assistant",content:[{type:"text",text:i}]}}),r({type:"message_end",message:{role:"assistant",content:[{type:"text",text:i}]}}),r({type:"agent_end"})}finally{To(e,!1)}})(),Response.json({success:!0,data:null})}async function aD(e){qg("oomStressHandler called",`session ${e}`);let t=5,n=Be(e);if(!n?.isAlive())return Response.json({error:"Session not found"},{status:404});return(async()=>{To(e,!0);try{let r=(d)=>{n.emit(d)};r({type:"agent_start"}),await new Promise((d)=>setTimeout(d,t*1000)),r({type:"message_start",message:{role:"assistant",content:[]}}),r({type:"message_update",assistantMessageEvent:{type:"thinking_start",contentIndex:0}});let i=400,o=500,s=80,a=[];for(let d=0;d<i;d++){let f=`Thinking step ${d+1}: ${"x".repeat(o-40)}
|
|
286
286
|
`;a.push(f),r({type:"message_update",assistantMessageEvent:{type:"thinking_delta",contentIndex:0,delta:f}}),await new Promise((p)=>setTimeout(p,s))}let c=a.join("");r({type:"message_update",assistantMessageEvent:{type:"thinking_end",contentIndex:0,content:c}});let u=`
|
|
287
287
|
Done. Streamed ${i} thinking chunks (${c.length} chars).`;r({type:"message_update",assistantMessageEvent:{type:"text_start",contentIndex:1}}),r({type:"message_update",assistantMessageEvent:{type:"text_delta",contentIndex:1,delta:u}}),r({type:"message_update",assistantMessageEvent:{type:"text_end",contentIndex:1,content:u}}),r({type:"message_end",message:{role:"assistant",content:[{type:"thinking",thinking:c},{type:"text",text:u}]}}),r({type:"agent_end"})}finally{To(e,!1)}})(),Response.json({success:!0,data:null})}var $g=new Set;function To(e,t){if(t)$g.add(e);else $g.delete(e)}async function B6(e,{params:t}){let{id:n}=await t;try{let r=await e.json();if(Ea(`POST /api/agent/${n}`,`type=${r.type} message=${JSON.stringify(r.message)} keys=${Object.keys(r).join(",")}`),r.type==="prompt"&&r.message==="oom debug")return Ea("INTERCEPTED","routing to oomDebugHandler"),sD(n);if(r.type==="prompt"&&r.message==="oom stress")return qg("INTERCEPTED","routing to oomStressHandler"),aD(n);if(n==="new")return oD(r,ae(e));let i=Be(n);if(i?.isAlive()){let c=await Hg(i,r);return Response.json({success:!0,data:c})}let o=await De(n);if(!o)return Response.json({error:"Session not found"},{status:404});let{session:s}=await Rr(n,o,void 0);await Ml(s,o);let a=await Hg(s,r);return Response.json({success:!0,data:a})}catch(r){console.error(`[api] ${new URL(e.url).pathname} failed:`,r);let i=r instanceof _o?400:500;return Response.json({error:String(r)},{status:i})}}async function Hg(e,t){let{provider:n,modelId:r,...i}=t;if(t.type==="prompt"&&n&&r){let o=await e.send({type:"get_state"});if(o.model?.provider!==n||o.model?.id!==r)await e.send({type:"set_model",provider:n,modelId:r});return e.send(i)}return e.send(t)}async function W6(e,{params:t}){let{id:n}=await t;try{let r=Be(n);if(!r?.isAlive())return Response.json({running:!1});if($g.has(n))return Response.json({running:!0,state:{isStreaming:!0,isPromptRunning:!0}});let i=await r.send({type:"get_state"});return Response.json({running:!0,state:i})}catch(r){return console.error(`[api] ${new URL(e.url).pathname} failed:`,r),Response.json({error:String(r)},{status:500})}}var zg={};Z(zg,{GET:()=>j6});async function j6(){return Response.json(wo(),{headers:{"Cache-Control":"no-store"}})}import Xg from"node:fs";var q6=new Set(["select","confirm","input","editor"]),$6=new Set(["agent_settled","prompt_done","prompt_error","extension_error"]);function ft(e,t,n){try{e.ws.send(JSON.stringify({ch:t,data:n}))}catch{}}function cD(e,t,n){if(!e)return;for(let r of e){if(t==="global"){let i=n,o=i.type==="extension_ui_request"&&q6.has(i.method),s=typeof i.type==="string"&&$6.has(i.type);if(o)Qe("ui-chain",`3 ws broadcast ${String(i.method)}`,`id=${String(i.id).slice(0,8)} sid=${String(i.sessionId).slice(0,8)} conns=${e.size}`);if(!s){let a=i.sessionId;if(a&&!r.seenSessions.has(a))continue}ft(r,t,n);continue}if(t==="running"){ft(r,t,{type:"running",...Vg(n,r.seenSessions)});continue}ft(r,t,n)}}function Vg(e,t){let n=e.runningSessionIds.filter((a)=>t.has(a)),r={},i={},o={},s={};for(let a of n){if(e.phases[a]!==void 0)r[a]=e.phases[a];if(e.phaseSince[a]!==void 0)i[a]=e.phaseSince[a];if(e.respondingSince[a]!==void 0)o[a]=e.respondingSince[a];if(e.busySince[a]!==void 0)s[a]=e.busySince[a]}return{runningSessionIds:n,phases:r,phaseSince:i,respondingSince:o,busySince:s}}var H6=new Set(["turn_start","turn_end"]);function uD(e){if(H6.has(e.type))return null;if(e.type==="message_update"){let n=e.assistantMessageEvent;if(!n||typeof n.type!=="string")return e;return{type:"message_update",assistantMessageEvent:G6(n)}}if(e.type==="message_start"||e.type==="message_end")return e;if(e.type==="agent_end")return{type:"agent_end"};return e}function G6(e){let t={type:e.type};if(typeof e.delta==="string")t.delta=e.delta;if(typeof e.contentIndex==="number")t.contentIndex=e.contentIndex;if(e.type==="toolcall_end"&&e.toolCall&&typeof e.toolCall==="object")t.toolCall=e.toolCall;if(e.type==="toolcall_start"&&typeof e.contentIndex==="number"){let r=e.partial?.content?.[e.contentIndex];if(r&&r.type==="toolCall"&&typeof r.name==="string")t.toolCall={type:"toolCall",toolCallId:typeof r.id==="string"?r.id:"",toolName:r.name}}return t}var Ta=ze("ws-agent");var Dn=new Map,Ll=null,Bl=null;function Wl(e,t){cD(Dn.get(e),e,t)}function dD(){let e=new Set;for(let t of Dn.get("global")??[])for(let n of t.seenSessions)e.add(n);return[...e]}function z6(e){if(e==="global"&&!Ll)Ll=Dg((t,n)=>{let r=uD(n);if(r)Wl("global",{sessionId:t,...r})});if(e==="running"&&!Bl)Bl=_g((t)=>Wl("running",t))}function V6(e){if(e==="global"&&Dn.get("global")?.size===0)Ll?.(),Ll=null;if(e==="running"&&Dn.get("running")?.size===0)Bl?.(),Bl=null}function lD(e,t){let n=Dn.get(t);if(!n)n=new Set,Dn.set(t,n);if(n.add(e),!e.channels.has(t))e.channels.set(t,{kind:"passive"});z6(t)}function Aa(e,t){let n=e.channels.get(t);if(!n)return;if(e.channels.delete(t),n.kind==="agent")n.unsubscribe();if(n.kind==="watch")try{n.watcher.close()}catch{}if(Dn.get(t)?.delete(e),n.kind==="passive")V6(t);if(n.kind==="agent"){let r=Dn.get(t);if(!r||r.size===0){let i=t.slice(6);K6(i)}}}var X6=30000,Ca=new Map;function K6(e){let t=Ca.get(e);if(t)clearTimeout(t);Ca.set(e,setTimeout(()=>{Ca.delete(e),Be(e)?.cancelPendingUiResponses()},X6))}async function Z6(e,t){let n=`agent:${t}`,r=performance.now();if(e.seenSessions.add(t),e.channels.has(n))return;let i=Be(t);if(Ta(`sub sid=${t} ${i?.isAlive()?"alive":"cold start"}`),!i?.isAlive()){let c=await De(t);if(!c){Ta(`sub sid=${t} not_found`),ft(e,n,{type:"not_found",sessionId:t});return}try{({session:i}=await Rr(t,c,void 0)),await Ml(i,c)}catch(u){Ta(`sub sid=${t} start_failed +${Math.round(performance.now()-r)}ms: ${String(u)}`),ft(e,n,{type:"start_failed",sessionId:t,message:String(u)});return}}e.channels.set(n,{kind:"agent",unsubscribe:()=>{}}),Dn.get(n)?.add(e);let o=Ca.get(t);if(o)clearTimeout(o),Ca.delete(t);ft(e,n,{type:"connected",sessionId:t}),Ta(`sub sid=${t} connected +${Math.round(performance.now()-r)}ms`);let s=i.getPendingUiRequests();for(let c of s)ft(e,"global",{...c,sessionId:t});let a=i.getStreamingUpdate?.();if(a)ft(e,"global",{...a,sessionId:t}),Ta(`sub sid=${t} streaming anchor resent`)}function Y6(e,t){let n=t,r=`watch:${n}`,i;try{i=Xg.statSync(n)}catch{ft(e,r,{event:"error",message:"Not found"});return}if(!i.isFile()){ft(e,r,{event:"error",message:"Not a file"});return}let o,s=i.mtimeMs,a=i.size;try{o=Xg.watch(n,()=>{try{let c=Xg.statSync(n);if(c.mtimeMs===s&&c.size===a)return;s=c.mtimeMs,a=c.size,ft(e,r,{event:"change",mtime:c.mtime.toISOString(),size:c.size})}catch{ft(e,r,{event:"change",mtime:new Date().toISOString(),size:0})}})}catch{ft(e,r,{event:"error",message:"Failed to watch file"});return}o.on("error",()=>{Aa(e,r)}),e.channels.set(r,{kind:"watch",watcher:o}),Dn.get(r)?.add(e),ft(e,r,{event:"connected",filePath:n})}async function fD(e,t){switch(t.ch){case"global":{lD(e,"global");return}case"running":{lD(e,"running"),ft(e,"running",{type:"running",...Vg(wo(),e.seenSessions)});return}case"agent":{let n=typeof t.sessionId==="string"?t.sessionId:"";if(n)await Z6(e,n);return}case"watch":{if(typeof t.filePath==="string"&&t.filePath)Y6(e,t.filePath);return}default:return}}function pD(e){if(!Pt(e))return!1;let t=process.env.PI_WEB_PASSWORD;if(Sa(t)&&!Rl(e.headers.get("authorization"),t))return!1;return!0}var Kg=ze("api-ws"),Zg=null;function Yg(e){Zg=e((t)=>{if(!pD(t.req.raw))return{onOpen:(o,s)=>s.close(1008,"untrusted")};let n={ws:null,channels:new Map,seenSessions:new Set},r=null,i=!1;return{onOpen:(o,s)=>{n.ws=s,Kg("connected",`${n.channels.size} channels restored`),s.send(JSON.stringify({type:"connected"})),r=setInterval(()=>{try{if(i){Kg("pong-timeout","no pong within one cycle — closing (half-open suspected)"),s.close();return}s.send(JSON.stringify({type:"ping"})),i=!0}catch{}},30000)},onMessage:async(o)=>{if(typeof o.data!=="string")return;let s;try{s=JSON.parse(o.data)}catch{return}if(s.type==="pong")i=!1;else if(s.type==="sub")await fD(n,s);else if(s.type==="unsub"&&typeof s.ch==="string")Aa(n,s.ch);else if(s.type==="unseen"&&typeof s.sessionId==="string"){let a=s.sessionId;n.seenSessions.delete(a);let c=`agent:${a}`;if(n.channels.has(c))Aa(n,c)}},onClose:()=>{if(Kg("closed",`${n.channels.size} channels dropped`),r)clearInterval(r);i=!1;for(let o of[...n.channels.keys()])Aa(n,o)}}})}function hD(e){e.get("/api/ws",(t,n)=>Zg?Zg(t,n):n())}var Jg={};Z(Jg,{DELETE:()=>sW,POST:()=>oW});import{randomUUID as J6}from"node:crypto";import{mkdir as Q6,unlink as eW,writeFile as tW}from"node:fs/promises";import{tmpdir as nW}from"node:os";import Co from"node:path";var gD=209715200,rW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}-[^/\\]+$/;function mD(){return Co.join(nW(),"pi-web-attachments")}function iW(e){let t=Co.basename(e??"");return Array.from(t).filter((i)=>i.charCodeAt(0)>31&&!'<>:"/\\|?*'.includes(i)).join("").replace(/^\.+/,"").slice(0,120)||"attachment"}async function oW(e){let t=iW(new URL(e.url).searchParams.get("name")),n=Buffer.from(await e.arrayBuffer());if(n.byteLength===0)return Response.json({error:"empty body"},{status:400});if(n.byteLength>gD)return Response.json({error:`attachment exceeds ${gD/1048576}MB`},{status:413});let r=mD();await Q6(r,{recursive:!0});let i=Co.join(r,`${J6()}-${t}`);return await tW(i,n),Response.json({path:i,name:t,size:n.byteLength})}async function sW(e){let t=new URL(e.url).searchParams.get("path");if(!t)return Response.json({error:"path is required"},{status:400});let n=Co.resolve(t);if(Co.dirname(n)!==mD()||!rW.test(Co.basename(n)))return Response.json({error:"not an uploaded attachment"},{status:400});try{await eW(n)}catch(r){if(r.code!=="ENOENT")throw r}return Response.json({ok:!0})}var wm={};Z(wm,{GET:()=>Dj});import{ModelRuntime as _j}from"@earendil-works/pi-coding-agent";var aW={"openai-codex":"ChatGPT Plus/Pro","github-copilot":"GitHub Copilot"};function yD(e){let t=new Set,n=[];for(let r of e){if(t.has(r.id))continue;t.add(r.id),n.push(r)}return n}function bD(e){let t=[];for(let n of yD(e)){if(!n.hasApiKeyLogin)continue;if(n.isCustom)continue;let r=n.status.configured&&n.credentialType!=="oauth";t.push({id:n.id,displayName:n.name,configured:r,...r&&n.status.source?{source:n.status.source}:{},modelCount:n.modelCount,modelIds:n.modelIds,reasoningModelIds:n.reasoningModelIds,inputModelIds:n.inputModelIds,supportsOAuth:n.hasOAuth,...n.baseUrl?{baseUrl:n.baseUrl}:{},...n.api?{api:n.api}:{}})}return t}function vD(e){let t=[];for(let n of yD(e)){if(!n.hasOAuth)continue;t.push({id:n.id,name:aW[n.id]??n.oauthName??n.name,usesCallbackServer:!1,loggedIn:n.credentialType==="oauth",modelIds:n.modelIds,reasoningModelIds:n.reasoningModelIds,inputModelIds:n.inputModelIds,supportsApiKey:n.hasApiKeyLogin,...n.baseUrl?{baseUrl:n.baseUrl}:{},...n.api?{api:n.api}:{}})}return t}async function jl(e,t){let n=e.getModels(),r=new Map;for(let s of n){if(!s.reasoning)continue;let a=r.get(s.provider);if(a)a.push(s.id);else r.set(s.provider,[s.id])}let i=new Map;for(let s of n){let a=(Array.isArray(s.input)?s.input:[]).filter((u)=>u!=="text");if(a.length===0)continue;let c=i.get(s.provider);if(!c)c={},i.set(s.provider,c);for(let u of a){let d=c[u]??[];d.push(s.id),c[u]=d}}let o=new Map;try{for(let s of await e.listCredentials())if(s.type==="api_key"||s.type==="oauth")o.set(s.providerId,s.type)}catch{}return e.getProviders().map((s)=>({id:s.id,name:s.name,isCustom:t?.has(s.id)??!1,...typeof s.baseUrl==="string"&&s.baseUrl.trim()?{baseUrl:s.baseUrl}:{},...n.find((a)=>a.provider===s.id)?.api?{api:n.find((a)=>a.provider===s.id).api}:{},hasApiKeyLogin:Boolean(s.auth.apiKey?.login),hasOAuth:Boolean(s.auth.oauth),...s.auth.oauth?.name?{oauthName:s.auth.oauth.name}:{},status:e.getProviderAuthStatus(s.id),...o.has(s.id)?{credentialType:o.get(s.id)}:{},modelCount:n.filter((a)=>a.provider===s.id).length,modelIds:n.filter((a)=>a.provider===s.id).map((a)=>a.id),reasoningModelIds:r.get(s.id)??[],inputModelIds:i.get(s.id)??{}}))}Ao();import{mkdir as cW,readdir as uW,readFile as DD,stat as SD,writeFile as lW}from"node:fs/promises";import{join as Ua}from"node:path";import{getAgentDir as ED}from"@earendil-works/pi-coding-agent";var ql=Ua(ED(),"pi-web","provider");function Mr(e){return/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(e)}async function Di(e){if(!Mr(e))return[];let t=Ua(ql,e,"models.json");try{if(!(await SD(t)).isFile())return[]}catch{return[]}try{let n=await DD(t,"utf-8");return Ir(JSON.parse(n))}catch{return[]}}async function $l(e){let t=[];for(let n of await Di(e)){let r=Or(n);if(r)t.push(r)}return t}function _i(e){let t=typeof e==="string"?Number(e):e;return typeof t==="number"&&Number.isFinite(t)?t:void 0}function dW(e,t){return{contextWindow:_i(e.context_length)??_i(e.context_window)??_i(t?.context_length)??_i(e.max_model_len)??0,maxTokens:_i(e.max_completion_tokens)??_i(e.max_output_tokens)??_i(t?.max_completion_tokens)??0}}function fW(e,t){if(Array.isArray(e.supported_parameters))return e.supported_parameters.some((n)=>n==="reasoning"||n==="thinking");if(e.reasoning!==void 0)return e.reasoning===!0;return t?.reasoning===!0}function pW(e,t){let n=Array.isArray(e.input_modalities)?e.input_modalities:Array.isArray(t?.input_modalities)?t.input_modalities:["text"],r=new Set(["text","image","audio","video","pdf"]),i=n.filter((o)=>typeof o==="string"&&r.has(o));if(i.length===0)i.push("text");return i}function em(e,t){let n=Or(t);if(!n)return null;let r=typeof t==="object"&&t!==null?t:{},i=r.top_provider,o=r.architecture,s=r.pricing,a=r.capabilities,{contextWindow:c,maxTokens:u}=dW(r,i),d=fW(r,a),f=pW(r,o),p=(g)=>{let b=typeof g==="string"?Number(g):g;if(typeof b!=="number"||!Number.isFinite(b))return 0;return Math.abs(b)<1?b*1e6:b},h=s&&typeof s==="object"?{input:p(s.prompt),output:p(s.completion),cacheRead:p(s.input_cache_read),cacheWrite:p(s.input_cache_write)}:{input:0,output:0,cacheRead:0,cacheWrite:0};return{id:n.id,name:n.name??n.id,provider:e,api:"openai-completions",baseUrl:"",reasoning:d,input:f,cost:h,contextWindow:c,maxTokens:u}}function hW(e){if(!e||typeof e!=="object")return new Set;let t=new Set;for(let[n,r]of Object.entries(e)){let i=r&&typeof r==="object"?r:void 0;if(i&&Array.isArray(i.models))t.add(n.toLowerCase())}return t}async function ko(){try{let e=JSON.parse(await DD(Ua(ED(),"models.json"),"utf-8"));return hW(e.providers)}catch{return new Set}}async function Uo(){try{if(!(await SD(ql)).isDirectory())return[]}catch{return[]}return(await uW(ql,{withFileTypes:!0})).filter((t)=>t.isDirectory()).map((t)=>t.name)}var gW=["off","minimal","low","medium","high","xhigh","max"];async function Hl(e,t){if(!Mr(e))return;let n=Ua(ql,e);await cW(n,{recursive:!0}),await lW(Ua(n,"models.json"),`${JSON.stringify(t,null,2)}
|
|
@@ -291,7 +291,7 @@ Done. Streamed ${i} thinking chunks (${c.length} chars).`;r({type:"message_updat
|
|
|
291
291
|
|
|
292
292
|
`)}function US(e,t){ki(e.stream,{id:e.id,object:"chat.completion.chunk",created:e.created,model:e.model,choices:[{index:0,delta:{},finish_reason:t.finishReason}]});let n=Math.max(1,Math.round(e.inputChars/4)),r=Math.max(1,Math.round(t.outputChars/4));ki(e.stream,{id:e.id,object:"chat.completion.chunk",created:e.created,model:e.model,choices:[],usage:{prompt_tokens:n,completion_tokens:r,total_tokens:n+r}}),e.stream.write(`data: [DONE]
|
|
293
293
|
|
|
294
|
-
`)}async function RS(e,t,n){let{stream:r,id:i,model:o,created:s}=e;if(n){let c=Math.ceil(t.length/2);for(let u of[t.slice(0,c),t.slice(c)]){if(ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{content:u},finish_reason:null}]}),u===t.slice(c))break;await No(n)}return}let a=24;for(let c=0;c<t.length;c+=a)ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{content:t.slice(c,c+a)},finish_reason:null}]}),await No(15)}function FS(e){try{let t=JSON.parse(e);if(t&&typeof t==="object"){let n=t.multiEcho;if(typeof n==="number"&&Number.isInteger(n)&&n>0)return n}}catch{}return 3}function c7(e,t){let n=FS(e);return`echo round-${t+1} && sleep 1 && echo total-${n}`}function PS(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!=="object")return null;let n=t.blocks;if(!Array.isArray(n))return null;return n.filter((r)=>{if(!r||typeof r!=="object")return!1;let i=r.type;return i==="thinking"||i==="text"||i==="toolCall"})}function OS(e,t,n){let{stream:r,id:i,model:o,created:s}=e;return(async()=>{let a=t.some((u)=>u.type==="toolCall"),c=0;for(let u=0;u<t.length;u++){let d=t[u];if(d.type==="thinking"){let f=d.thinking??"";c+=f.length;let p=d.thinkingSignature??"reasoning_content";ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{[p]:f.slice(0,64)},finish_reason:null}]}),await No(8);for(let h=64;h<f.length;h+=40)ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{[p]:f.slice(h,h+40)},finish_reason:null}]}),await No(8)}else if(d.type==="text")c+=(d.text??"").length,await RS(e,d.text??"",n);else if(d.type==="toolCall"){let f=JSON.stringify(d.arguments??{});c+=f.length;let p=32;for(let h=0;h<f.length;h+=p)ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{tool_calls:[{index:u,id:d.id??`call_echo_${u+1}`,type:"function",function:{name:d.name??"bash",arguments:f.slice(h,h+p)}}]},finish_reason:null}]}),await No(15)}}US(e,{finishReason:a?"tool_calls":"stop",outputChars:c})})()}function u7(e){try{let t=JSON.parse(e);if(t&&typeof t==="object"){let n=t,r=typeof n.streamMs==="number"&&Number.isFinite(n.streamMs)&&n.streamMs>=0?n.streamMs:void 0,i=typeof n.preStreamMs==="number"&&Number.isFinite(n.preStreamMs)&&n.preStreamMs>=0?n.preStreamMs:void 0;return{streamMs:r,preStreamMs:i}}}catch{}return{}}function Om(e,t,n){return(async()=>{await RS(e,t,n),US(e,{finishReason:"stop",outputChars:t.length})})()}var l7=new TextEncoder;function ad(e,t,n,r,i){let o=new ReadableStream({async start(s){await r({stream:{write:(c)=>s.enqueue(l7.encode(c))},id:e,model:t,created:n,inputChars:i?.inputChars??0}),s.close()}});return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function d7(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;return t.map((r)=>r&&typeof r==="object"&&typeof r.text==="string"?r.text:"").join("")||null}catch{return null}}function f7(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.role!=="user")continue;let r=n.content;if(typeof r==="string")return d7(r)??r;if(Array.isArray(r)){let i=r.map((o)=>o&&typeof o==="object"&&typeof o.text==="string"?o.text:"").join("");if(i)return i}}return""}function p7(e){let t=[e,e.trim().startsWith("{ ")||e.trim().startsWith(`{
|
|
294
|
+
`)}async function RS(e,t,n){let{stream:r,id:i,model:o,created:s}=e;if(n){let c=Math.ceil(t.length/2);for(let u of[t.slice(0,c),t.slice(c)]){if(ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{content:u},finish_reason:null}]}),u===t.slice(c))break;await No(n)}return}let a=24;for(let c=0;c<t.length;c+=a)ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{content:t.slice(c,c+a)},finish_reason:null}]}),await No(15)}function FS(e){try{let t=JSON.parse(e);if(t&&typeof t==="object"){let n=t.multiEcho;if(typeof n==="number"&&Number.isInteger(n)&&n>0)return n}}catch{}return 3}function c7(e,t){let n=FS(e);return`echo round-${t+1} && sleep 1 && echo total-${n}`}function PS(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!=="object")return null;let n=t.blocks;if(!Array.isArray(n))return null;return n.filter((r)=>{if(!r||typeof r!=="object")return!1;let i=r.type;return i==="thinking"||i==="text"||i==="toolCall"})}function OS(e,t,n){let{stream:r,id:i,model:o,created:s}=e;return(async()=>{let a=t.some((u)=>u.type==="toolCall"),c=0;for(let u=0;u<t.length;u++){let d=t[u];if(d.type==="thinking"){let f=d.thinking??"";c+=f.length;let p=d.thinkingSignature??"reasoning_content";ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{[p]:f.slice(0,64)},finish_reason:null}]}),await No(8);for(let h=64;h<f.length;h+=40)ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{[p]:f.slice(h,h+40)},finish_reason:null}]}),await No(8)}else if(d.type==="text")c+=(d.text??"").length,await RS(e,d.text??"",n);else if(d.type==="toolCall"){let f=JSON.stringify(d.arguments??{});c+=f.length;let p=32;for(let h=0;h<f.length;h+=p)ki(r,{id:i,object:"chat.completion.chunk",created:s,model:o,choices:[{index:0,delta:{tool_calls:[{index:u,id:d.id??`call_echo_${u+1}`,type:"function",function:{name:d.name??"bash",arguments:f.slice(h,h+p)}}]},finish_reason:null}]}),await No(n??15)}}US(e,{finishReason:a?"tool_calls":"stop",outputChars:c})})()}function u7(e){try{let t=JSON.parse(e);if(t&&typeof t==="object"){let n=t,r=typeof n.streamMs==="number"&&Number.isFinite(n.streamMs)&&n.streamMs>=0?n.streamMs:void 0,i=typeof n.preStreamMs==="number"&&Number.isFinite(n.preStreamMs)&&n.preStreamMs>=0?n.preStreamMs:void 0;return{streamMs:r,preStreamMs:i}}}catch{}return{}}function Om(e,t,n){return(async()=>{await RS(e,t,n),US(e,{finishReason:"stop",outputChars:t.length})})()}var l7=new TextEncoder;function ad(e,t,n,r,i){let o=new ReadableStream({async start(s){await r({stream:{write:(c)=>s.enqueue(l7.encode(c))},id:e,model:t,created:n,inputChars:i?.inputChars??0}),s.close()}});return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function d7(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;return t.map((r)=>r&&typeof r==="object"&&typeof r.text==="string"?r.text:"").join("")||null}catch{return null}}function f7(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.role!=="user")continue;let r=n.content;if(typeof r==="string")return d7(r)??r;if(Array.isArray(r)){let i=r.map((o)=>o&&typeof o==="object"&&typeof o.text==="string"?o.text:"").join("");if(i)return i}}return""}function p7(e){let t=[e,e.trim().startsWith("{ ")||e.trim().startsWith(`{
|
|
295
295
|
`)?null:`{${e.trim()}}`];for(let n of t){if(!n)continue;try{let r=JSON.parse(n);if(!r||typeof r!=="object")continue;let i=r;if(typeof i.name==="string"&&i.arguments&&typeof i.arguments==="object")return{name:i.name,arguments:i.arguments}}catch{}}return null}function h7(e,t){let n=e.slice(-3).map((r)=>({role:r?.role,c:typeof r?.content==="string"?r.content.slice(0,80):JSON.stringify(r?.content).slice(0,80)}));return`n=${e.length} roles=${e.map((r)=>r?.role).join(",")} lastUser=${JSON.stringify(t.slice(0,160))} tails=${JSON.stringify(n)}`}function g7(e,t,n,r){let i=n?.filter((o)=>o.type==="toolCall").map((o)=>o.id??"<no-id>").join(",");Ai("response",`model=${e} finalKind=${t} toolCalls=${i??"-"} echoText=${n?"-":JSON.stringify(r.slice(0,160))}`)}function m7(e,t,n,r,i){if(t!=="multiEcho")return null;let o=r.filter((c)=>c?.role==="tool").length,s=FS(i);if(o>=s)return ad(e,t,n,(c)=>Om(c,`multiEcho done (${o}/${s} rounds)`),{inputChars:i.length});let a=[{type:"toolCall",id:`call_multiEcho_${o}`,name:"bash",arguments:{command:c7(i,o)}}];return ad(e,t,n,(c)=>OS(c,a),{inputChars:i.length})}function y7(e){let t=p7(e);if(!t){Ai("toolEcho",`no fragment matched; head=${JSON.stringify(e.slice(0,80))}`);return}let n=`${t.name}-${Date.now()}`;return Ai("toolEcho",`fragment toolCall -> id=${n} name=${t.name} args=${JSON.stringify(t.arguments).slice(0,120)}`),[{type:"toolCall",id:n,name:t.name,arguments:t.arguments}]}function b7(e,t,n,r){let i=PS(r)?.filter((o)=>o.type==="text").at(-1)?.text??"All tool calls executed.";return ad(e,t,n,(o)=>Om(o,i),{inputChars:r.length})}async function v7(e){let t={};try{t=await e.json()}catch{return Response.json({error:"Invalid JSON body"},{status:400})}let n=t.model??"echo",r=t.messages??[],o=r[r.length-1]?.role==="tool",s=f7(r);Ai("POST /chat/completions",`model=${n} lastIsToolResult=${o} userTextLen=${s.length}`),Ai("probe",h7(r,s));let a=`chatcmpl-echo-${Date.now()}`,c=Math.floor(Date.now()/1000),u=m7(a,n,c,r,s);if(u)return u;if(o)return b7(a,n,c,s);let d=PS(s);if(Ai("echo-model.decision",`model=${n} blocks=${d?d.length:"null"} userLen=${s.length} userHead=${JSON.stringify(s.slice(0,120))}`),n==="toolEcho"&&!d)d=y7(s)??d;let{streamMs:f,preStreamMs:p}=u7(s),h=n==="echoSlow"?f??1200:f,g=d?d.map((b)=>b.type).join(","):"plain-text";if(h!==void 0)Ai("echo-model.decision",`streamMs=${h}`);return g7(n,g,d,s),ad(a,n,c,async(b)=>{if(p)await No(p);if(d)await OS(b,d,h);else await Om(b,s,h)},{inputChars:s.length})}var Mm={};Z(Mm,{GET:()=>_7,collectEnvView:()=>MS,maskEnvValue:()=>IS});var x7=["KEY","TOKEN","SECRET","PASSWORD","PASSWD","PASS","CREDENTIAL"];function w7(e){if(e.length<20)return"*".repeat(e.length);return`${e.slice(0,2)}${"*".repeat(e.length-4)}${e.slice(-2)}`}function IS(e,t){if(t==="")return{value:"",masked:!1};let n=e.toUpperCase();if(!x7.some((i)=>n.includes(i)))return{value:t,masked:!1};return{value:w7(t),masked:!0}}function MS(){return Object.entries(process.env).map(([e,t])=>{let{value:n,masked:r}=IS(e,t??"");return{name:e,value:n,masked:r}}).sort((e,t)=>e.name.localeCompare(t.name))}async function _7(){return Response.json({vars:MS(),cwd:process.cwd()})}var Bm={};Z(Bm,{GET:()=>k7,PUT:()=>U7});import Na from"node:fs";import La from"node:path";import{getAgentDir as qS}from"@earendil-works/pi-coding-agent";import{readFileSync as D7}from"node:fs";import{dirname as S7,join as NS}from"node:path";import{getAgentDir as E7}from"@earendil-works/pi-coding-agent";var T7="pi-web.json",C7=10,Lm=["node_modules",".git",".next","dist","build","__pycache__",".turbo",".cache","coverage",".pytest_cache",".mypy_cache","target","vendor",".DS_Store","*.pyc"];function Nm(e){let t=new Set,n=[];for(let r of e){if(typeof r!=="string"||r.length===0)continue;if(r.startsWith("*.")&&r.length>2)n.push(r.slice(1));else t.add(r)}return{names:t,suffixes:n}}function LS(e){let t;try{t=D7(e,"utf-8")}catch(n){if(n?.code!=="ENOENT")console.warn(`[file-exclusions] unreadable ${e}:`,n);return null}try{let n=JSON.parse(t).fileExclusions;if(!Array.isArray(n))return console.warn(`[file-exclusions] ${e}: fileExclusions must be an array, ignoring`),null;return n}catch(n){return console.warn(`[file-exclusions] ${e}: invalid JSON, ignoring`,n),null}}function Ma(e){let t=e;for(let r=0;r<=C7;r++){let i=LS(NS(t,".pi",T7));if(i)return Nm(i);let o=S7(t);if(o===t)break;t=o}let n=LS(NS(E7(),"pi-web","file-exclusions.json"));if(n)return Nm(n);return Nm(Lm)}function Lo(e,t){return t.names.has(e)||t.suffixes.some((n)=>e.endsWith(n))}function BS(e,t){return e.split(/[\\/]/).some((n)=>n&&Lo(n,t))}var $S=".pi",HS="pi-web.json",GS="pi-web",zS="file-exclusions.json";function WS(e){let t;try{t=Na.readFileSync(e,"utf-8")}catch{return null}try{let n=JSON.parse(t).fileExclusions;return Array.isArray(n)?n.filter((r)=>typeof r==="string"):null}catch{return null}}function A7(e){if(!Array.isArray(e))return null;let t=new Set;for(let n of e){if(typeof n!=="string")return null;let r=n.trim();if(r)t.add(r)}return[...t]}function jS(e,t){Na.mkdirSync(La.dirname(e),{recursive:!0});let n=`${e}.tmp`;Na.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
296
296
|
`),Na.renameSync(n,e)}async function k7(e){let n=new URL(e.url).searchParams.get("cwd")??"",r=null;if(n){let i=await oe();if(!Re(n,i))return Response.json({error:"Access denied"},{status:403});r=WS(La.join(n,$S,HS))}return Response.json({defaults:[...Lm],global:WS(La.join(qS(),GS,zS)),project:r})}async function U7(e){let t;try{t=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}let n=A7(t.patterns);if(n===null)return Response.json({error:"patterns must be an array of strings"},{status:400});if(t.scope==="global")return jS(La.join(qS(),GS,zS),{fileExclusions:n}),Response.json({ok:!0});if(t.scope==="project"){let r=typeof t.cwd==="string"?t.cwd:"";if(!r||!r.startsWith("/")&&!Ie(r))return Response.json({error:"cwd must be an absolute path"},{status:400});let i=await oe();if(!Re(r,i)||!ce(r,i))return Response.json({error:"Access denied"},{status:403});let o=La.join(r,$S,HS),s={};try{s=JSON.parse(Na.readFileSync(o,"utf-8"))}catch{}return jS(o,{...s,fileExclusions:n}),Response.json({ok:!0})}return Response.json({error:"scope must be global or project"},{status:400})}var Wm={};Z(Wm,{GET:()=>V7});import{execFile as P7}from"node:child_process";import ld from"node:fs";import ud from"node:path";import{promisify as O7}from"node:util";function cd(e){let t=0;for(let n=0;n<e.length;n++)if(e[n]==="/")t++;return t}function VS(e){let t=new Set;for(let r of e){let i=r.indexOf("/");while(i!==-1)t.add(r.slice(0,i)),i=r.indexOf("/",i+1)}let n=[];for(let r of t)n.push({path:r,isDir:!0});for(let r of e){if(!r)continue;n.push({path:r,isDir:!1})}n.sort((r,i)=>cd(r.path)-cd(i.path)||r.path.localeCompare(i.path));for(let r of n){r.lowerPath=r.path.toLowerCase();let i=r.lowerPath.lastIndexOf("/");r.lowerName=i===-1?r.lowerPath:r.lowerPath.slice(i+1)}return n}function R7(e,t){let n=e.lowerPath??e.path.toLowerCase(),r=0;if(t.includes("/")){if(n===t)r=100;else if(n.startsWith(t))r=80;else if(n.includes(t))r=50}else{let i=e.lowerName??(()=>{let o=n.lastIndexOf("/");return o===-1?n:n.slice(o+1)})();if(i===t)r=100;else if(i.startsWith(t))r=80;else if(i.includes(t))r=50;else if(n.includes(t))r=30}if(e.isDir&&r>0)r+=10;return r}var F7=20;function XS(e,t,n=F7){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let o of e){let s=R7(o,r);if(s>0)i.push({entry:o,score:s})}return i.sort((o,s)=>s.score-o.score||cd(o.entry.path)-cd(s.entry.path)||o.entry.path.localeCompare(s.entry.path)),i.slice(0,n).map((o)=>o.entry)}var I7=O7(P7),KS=5000,ZS=200000,M7=50000,N7=8,L7=500,B7=60000,W7=20;function j7(){if(!globalThis.__piFileIndexCache)globalThis.__piFileIndexCache=new Map;return globalThis.__piFileIndexCache}var q7=4,YS=1e4;async function JS(e,t,n,r,i=0){if(i>q7||n.length>=YS)return;let o;try{o=await ld.promises.readdir(e,{withFileTypes:!0})}catch{return}for(let s of o){if(Lo(s.name,r))continue;let a=`${t}/${s.name}`;if(s.isDirectory())await JS(ud.join(e,s.name),a,n,r,i+1);else if(s.isFile()){if(n.push(a),n.length>=YS)return}}}async function $7(e){let t=Ma(e),n=(s,a)=>I7("git",["-C",e,"ls-files",...s,"-z"],{timeout:a,maxBuffer:67108864,env:{...process.env,LC_ALL:"C"}}).then((c)=>c.stdout.split("\x00").filter(Boolean)),r;try{r=await n(["--cached","--others","--exclude-standard"],5000)}catch{return null}let i=[];try{i=await n(["--others","--ignored","--exclude-standard","--directory"],3000)}catch{}let o=[...r];for(let s of i){let a=s.replace(/\/+$/,"");if(!a||BS(a,t))continue;try{if(ld.statSync(ud.join(e,a)).isDirectory())await JS(ud.join(e,a),a,o,t);else o.push(a)}catch{}}if(o.length>ZS)return{files:o.slice(0,ZS),hardTruncated:!0};return{files:o,hardTruncated:!1}}function H7(e){let t=Ma(e),n=[],r=[{abs:e,rel:"",depth:0}];while(r.length>0){let{abs:i,rel:o,depth:s}=r.shift(),a;try{a=ld.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let c of a){if(Lo(c.name,t))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){if(s+1<=N7)r.push({abs:ud.join(i,c.name),rel:u,depth:s+1})}else if(c.isFile()){if(n.length>=M7)return{files:n,hardTruncated:!0};n.push(u)}}}return{files:n,hardTruncated:!1}}async function G7(e,t){if(!e||!e.startsWith("/")&&!Ie(e))return Response.json({error:"cwd must be an absolute path"},{status:400});if(!Re(e,t))return Response.json({error:"Access denied"},{status:403});let n;try{n=ld.statSync(e)}catch{return Response.json({error:"Directory not found"},{status:404})}if(!n.isDirectory())return Response.json({error:"Not a directory"},{status:400});if(!ce(e,t))return Response.json({error:"Access denied"},{status:403});return null}async function z7(e){let t=j7(),n=Date.now(),r=t.get(e);if(!r||r.expiresAt<=n){let i=await $7(e)??H7(e);for(let[o,s]of t)if(s.expiresAt<=n)t.delete(o);if(t.size>=W7)t.clear();r={listing:i,expiresAt:n+B7},t.set(e,r)}return r}async function V7(e){try{let t=new URL(e.url),n=t.searchParams.get("cwd")?.trim()??"",r=t.searchParams.get("q")?.slice(0,L7)??"",i=await oe(),o=await G7(n,i);if(o)return o;let s=await z7(n);if(s.entries??=VS(s.listing.files),r)return Response.json({matches:XS(s.entries,r)});let{files:a,hardTruncated:c}=s.listing;return Response.json({files:a.slice(0,KS),truncated:c||a.length>KS})}catch(t){return Response.json({error:String(t)},{status:500})}}var Hx={};Z(Hx,{GET:()=>Kae,POST:()=>Xae});import Hae from"node:fs";import X7 from"node:fs";import QS from"node:path";var K7=["error","overwrite","skip"],Z7=new Set(K7);function eE(e){let t=e??"error";return Z7.has(t)?t:null}function dd(e){if(e.length===0)return"No files selected";let t=new Set;for(let n of e){if(!n||n==="."||n===".."||n.includes("\x00"))return`Invalid file name: ${n||"(empty)"}`;if(n.includes("/")||n.includes("\\")||QS.basename(n)!==n)return`File names must not contain a path: ${n}`;if(t.has(n))return`Duplicate file name in upload: ${n}`;t.add(n)}return null}function fd(e,t){let n=[],r=[];for(let i of t){let o=QS.join(e,i),s;try{s=X7.lstatSync(o)}catch(a){if(a.code==="ENOENT")continue;throw a}if(n.push(i),!s.isFile()||s.isSymbolicLink())r.push(i)}return{conflicts:n,nonReplaceable:r}}import{spawn as Y7}from"node:child_process";function J7(e,t,n=!1){if(t==="win32"){if(n)return["rundll32","shell32.dll,OpenAs_RunDLL",e];let r=`${process.env.SYSTEMROOT||process.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0`,i=`Start '${e.replace(/'/g,"''")}'`,o=Buffer.from(i,"utf16le").toString("base64");return[`${r}\\powershell`,"-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",o]}if(n)return null;if(t==="darwin")return["open",e];if(t==="linux")return["xdg-open",e];return null}function tE(e,t=process.platform,n=!1){let r=J7(e,t,n);if(!r)return Promise.resolve({ok:!1,error:t==="darwin"||t==="linux"?"No system app-chooser dialog is available on this platform":"System open is not supported on this platform"});return new Promise((i)=>{let o=t==="win32",s=o&&r[0].toLowerCase().replace(/\//g,"\\").endsWith("powershell"),a=Y7(r[0],r.slice(1),{stdio:"ignore",windowsHide:o,...s?{windowsVerbatimArguments:!0}:{}});if(a.unref(),a.once("error",(c)=>{i({ok:!1,error:`Failed to launch opener: ${c.message}`})}),o){a.once("spawn",()=>i({ok:!0,platform:t}));return}a.once("exit",(c)=>{if(c===0){i({ok:!0,platform:t});return}i({ok:!1,error:t==="linux"&&(c===3||c===4)?"No application is associated with this file type":`Opener exited with code ${c}`})})})}import CO from"node:fs";import AO from"node:path";import Q7 from"node:fs";function nE(e,t){if(e.isDirectory())return!0;if(e.isFile())return!1;try{return Q7.statSync(t).isDirectory()}catch{return null}}function eq(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function rE(e,t){return`<!doctype html>
|
|
297
297
|
<html>
|