@rainmanhhh/pi-web 0.15.21 → 0.15.22

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.
Files changed (91) hide show
  1. package/dist/server.mjs +2 -2
  2. package/dist/static/assets/{CodeMirrorEditor-B_uaQIlR.js → CodeMirrorEditor-3VpGw7Cq.js} +1 -1
  3. package/dist/static/assets/{abnfDiagram-VCTEODGH-BTln3J2A.js → abnfDiagram-VCTEODGH-CSFbYHDx.js} +1 -1
  4. package/dist/static/assets/architecture-7GRP2DOG-DRQGfnsi.js +1 -0
  5. package/dist/static/assets/{architectureDiagram-5GKGNRK7-DEh11QP1.js → architectureDiagram-5GKGNRK7-D-c2oP6F.js} +1 -1
  6. package/dist/static/assets/{blockDiagram-I7D4REHJ-DCQC2a1U.js → blockDiagram-I7D4REHJ-BwveQkqM.js} +1 -1
  7. package/dist/static/assets/{c4Diagram-7LVT6UL2-CBilw_gi.js → c4Diagram-7LVT6UL2-DMdAmFQJ.js} +1 -1
  8. package/dist/static/assets/channel-dnXEnN0o.js +1 -0
  9. package/dist/static/assets/{chunk-4HAMMTFA-C_JrskoT.js → chunk-4HAMMTFA-BObUsDjS.js} +1 -1
  10. package/dist/static/assets/{chunk-75Z2AOVW-CfXH2WuR.js → chunk-75Z2AOVW-MVk9-0GX.js} +1 -1
  11. package/dist/static/assets/{chunk-DU6HZSFF-Cok-A1CS.js → chunk-DU6HZSFF-C5NvhurN.js} +3 -3
  12. package/dist/static/assets/{chunk-F27PBJKO-oyC5nnFZ.js → chunk-F27PBJKO-DAJeYYuP.js} +1 -1
  13. package/dist/static/assets/{chunk-GMAD6QVW-Bj9AqLrP.js → chunk-GMAD6QVW-XzJnq9bk.js} +1 -1
  14. package/dist/static/assets/{chunk-GVQU2GXP-ys-ZKoke.js → chunk-GVQU2GXP-dobNjAkv.js} +1 -1
  15. package/dist/static/assets/{chunk-IMKFNOWR-BVv0S1pd.js → chunk-IMKFNOWR-BBP6YfgV.js} +1 -1
  16. package/dist/static/assets/{chunk-L3NEJ4N5-CxaDCiHw.js → chunk-L3NEJ4N5-zxgcfSjy.js} +1 -1
  17. package/dist/static/assets/{chunk-OSK3NFVY-dv1TAbf7.js → chunk-OSK3NFVY-Dn4-fvPg.js} +1 -1
  18. package/dist/static/assets/{chunk-P2QGCYS3-BVE5HEi1.js → chunk-P2QGCYS3-Cf7ROuEa.js} +1 -1
  19. package/dist/static/assets/{chunk-POPQ4Y6H-B1YzfDM8.js → chunk-POPQ4Y6H-BUy_2-Ag.js} +1 -1
  20. package/dist/static/assets/{chunk-PWAF6VOD-gbShORPe.js → chunk-PWAF6VOD-BF825rju.js} +1 -1
  21. package/dist/static/assets/{chunk-SHT3W25Y-BLPZ3pPL.js → chunk-SHT3W25Y-m7wU1_3p.js} +1 -1
  22. package/dist/static/assets/{chunk-SVP7TREG-BCZgT1m2.js → chunk-SVP7TREG-Moh81bMs.js} +1 -1
  23. package/dist/static/assets/{chunk-TICWLB2K-Bnbjrbpv.js → chunk-TICWLB2K-qZS0KGtn.js} +1 -1
  24. package/dist/static/assets/classDiagram-ZZMXUADV-dJhBmJJl.js +1 -0
  25. package/dist/static/assets/classDiagram-v2-VYDZK3BY-dJhBmJJl.js +1 -0
  26. package/dist/static/assets/{cynefin-OW5HDTMX-BCsSPTLm.js → cynefin-OW5HDTMX-DBgK4hLj.js} +1 -1
  27. package/dist/static/assets/{cynefinDiagram-5FMLGOSQ-shk_DUM6.js → cynefinDiagram-5FMLGOSQ-DMfwsybo.js} +1 -1
  28. package/dist/static/assets/{dagre-GXQ25YYZ-B-s10AGN.js → dagre-GXQ25YYZ-DAZA8Fnd.js} +1 -1
  29. package/dist/static/assets/{diagram-S7CK7UJ4-CYbbRvHO.js → diagram-S7CK7UJ4-D38e8SiV.js} +1 -1
  30. package/dist/static/assets/{diagram-UQ7AKVKN-CqCADZ-9.js → diagram-UQ7AKVKN-DBTA-pO5.js} +1 -1
  31. package/dist/static/assets/{diagram-VSXAHHWV-D064mNY0.js → diagram-VSXAHHWV-DvRU31CX.js} +1 -1
  32. package/dist/static/assets/{diagram-VX7I27RA-BgzoG8zP.js → diagram-VX7I27RA-1GBEwWok.js} +1 -1
  33. package/dist/static/assets/{diagram-Z3DM3KII-jm0BiglU.js → diagram-Z3DM3KII-D5N4QCPP.js} +1 -1
  34. package/dist/static/assets/{ebnfDiagram-PWID7BFC-BY6rw3pW.js → ebnfDiagram-PWID7BFC-DDNq-lT-.js} +1 -1
  35. package/dist/static/assets/{erDiagram-RLTQ6QDP-DRstIX9i.js → erDiagram-RLTQ6QDP-DDUW9dbi.js} +1 -1
  36. package/dist/static/assets/eventmodeling-NTZA5JFV-CaALW5w2.js +1 -0
  37. package/dist/static/assets/flowDiagram-HODETNUW-zNmJ7Tsi.js +1 -0
  38. package/dist/static/assets/{ganttDiagram-EL5Y4UJY-mydzK_Bn.js → ganttDiagram-EL5Y4UJY-CNEQHgbZ.js} +1 -1
  39. package/dist/static/assets/{gitGraph-4MIJSDKK-BeB8li5e.js → gitGraph-4MIJSDKK-FOjHipMC.js} +1 -1
  40. package/dist/static/assets/{gitGraphDiagram-WWUBYQGX-DMurycuW.js → gitGraphDiagram-WWUBYQGX-lF4TVBls.js} +1 -1
  41. package/dist/static/assets/{highlighted-body-KPVGNVTW-CzKQfdpv.js → highlighted-body-KPVGNVTW-Bm8pyP8B.js} +1 -1
  42. package/dist/static/assets/{index-CDxi_40j.js → index-DoEQcOYk.js} +16 -16
  43. package/dist/static/assets/{info-A6RAGUB7-DT_t2Tpv.js → info-A6RAGUB7-kCjcElFE.js} +1 -1
  44. package/dist/static/assets/{infoDiagram-27XIBGKW-BlCCDdqF.js → infoDiagram-27XIBGKW-B4IOnrCd.js} +1 -1
  45. package/dist/static/assets/{ishikawaDiagram-5VMMS53U-Dxspmkz2.js → ishikawaDiagram-5VMMS53U-CkfaBSRl.js} +1 -1
  46. package/dist/static/assets/{journeyDiagram-3NMN7TZE-B3y4nD6d.js → journeyDiagram-3NMN7TZE-B5Gr3vG3.js} +1 -1
  47. package/dist/static/assets/{kanban-definition-UXKFOSKX-DtQxRxYl.js → kanban-definition-UXKFOSKX-HLuw0Ed2.js} +1 -1
  48. package/dist/static/assets/{line-yAMKkjkn.js → line-asZclUhB.js} +1 -1
  49. package/dist/static/assets/mermaid-HWGCJPDP-TAuev-Zl.js +1 -0
  50. package/dist/static/assets/{mermaid-parser.core-Bt-NTqTu.js → mermaid-parser.core-DYWVm27N.js} +3 -3
  51. package/dist/static/assets/{mermaid.core-Ccd3XIq_.js → mermaid.core-D4B9kTQt.js} +4 -4
  52. package/dist/static/assets/{mindmap-definition-YA3MSWOX-CJvpN6ko.js → mindmap-definition-YA3MSWOX-CVw-Qpaa.js} +1 -1
  53. package/dist/static/assets/{packet-AYTQ26CC-EqnPCLhX.js → packet-AYTQ26CC-Bcjx4I8Y.js} +1 -1
  54. package/dist/static/assets/{pegDiagram-XKGWAZYB-erVXA7R1.js → pegDiagram-XKGWAZYB-CRMTaBi-.js} +1 -1
  55. package/dist/static/assets/{pie-WAS4IAKB-Bntx2SVn.js → pie-WAS4IAKB-Bi3-CVJ1.js} +1 -1
  56. package/dist/static/assets/{pieDiagram-E7YTZNPT-CNvZEFx8.js → pieDiagram-E7YTZNPT-BWNFx276.js} +1 -1
  57. package/dist/static/assets/{quadrantDiagram-AXDQQJYC-B77v5nsX.js → quadrantDiagram-AXDQQJYC-DAvdgdjy.js} +1 -1
  58. package/dist/static/assets/{radar-RG4KPBEZ-DLFXfBEA.js → radar-RG4KPBEZ-C0Pn0S5i.js} +1 -1
  59. package/dist/static/assets/{railroad-74A4TZTK-Dt7418s6.js → railroad-74A4TZTK-CDWxaNu1.js} +1 -1
  60. package/dist/static/assets/railroad-abnf-HS5TGJTU-zJC-_283.js +1 -0
  61. package/dist/static/assets/railroad-ebnf-LZEXJU2U-Iwo7s671.js +1 -0
  62. package/dist/static/assets/railroad-peg-WCYAUIDC-D6H7mjTE.js +1 -0
  63. package/dist/static/assets/{railroadDiagram-O6MQD6OU-CtV-sCmq.js → railroadDiagram-O6MQD6OU-8BhGjnTi.js} +1 -1
  64. package/dist/static/assets/{requirementDiagram-BXWQKSXE-BzRqHEnJ.js → requirementDiagram-BXWQKSXE-DII43vEQ.js} +1 -1
  65. package/dist/static/assets/{sankeyDiagram-P5KCCOFB-gQINnyk3.js → sankeyDiagram-P5KCCOFB-CFnE2h1E.js} +1 -1
  66. package/dist/static/assets/{sequenceDiagram-WJ2MYXX4-BFJ2RUWC.js → sequenceDiagram-WJ2MYXX4-AY1Dpgn9.js} +1 -1
  67. package/dist/static/assets/{stateDiagram-D77RDMKH-B1yZnGVL.js → stateDiagram-D77RDMKH-r6_DWzoK.js} +1 -1
  68. package/dist/static/assets/stateDiagram-v2-MP3YSRHH-D7rluiwE.js +1 -0
  69. package/dist/static/assets/{swimlanes-42K2YHIH-Cx6VD4Ak.js → swimlanes-42K2YHIH-D9JgwmIz.js} +1 -1
  70. package/dist/static/assets/swimlanesDiagram-VR7AAH4N-Cs5Yt0D2.js +8 -0
  71. package/dist/static/assets/{timeline-definition-24CTP7MA-CcoQp3lu.js → timeline-definition-24CTP7MA-b6TN44M5.js} +1 -1
  72. package/dist/static/assets/{treeView-Q6P3EWNA-CTOH6pPe.js → treeView-Q6P3EWNA-G-wl05QO.js} +1 -1
  73. package/dist/static/assets/{treemap-WGGIJYW6-kAbifyB3.js → treemap-WGGIJYW6-Dai-gt04.js} +1 -1
  74. package/dist/static/assets/{vennDiagram-4TSXK5OY-DS6t-tRC.js → vennDiagram-4TSXK5OY-BhCWQywC.js} +1 -1
  75. package/dist/static/assets/{wardley-WFR3VGLG-DaPHsQ0w.js → wardley-WFR3VGLG-CYJb9yRW.js} +1 -1
  76. package/dist/static/assets/{wardleyDiagram-VM6X3IG4-CbgYBj5_.js → wardleyDiagram-VM6X3IG4-Dbd34yM7.js} +1 -1
  77. package/dist/static/assets/{xychartDiagram-S5SC5T6Z-B7tXYZoJ.js → xychartDiagram-S5SC5T6Z-DVoStoUu.js} +1 -1
  78. package/dist/static/index.html +1 -1
  79. package/package.json +1 -1
  80. package/dist/static/assets/architecture-7GRP2DOG-t1vpz4e0.js +0 -1
  81. package/dist/static/assets/channel-Qpz7T57b.js +0 -1
  82. package/dist/static/assets/classDiagram-ZZMXUADV-BgcRoySA.js +0 -1
  83. package/dist/static/assets/classDiagram-v2-VYDZK3BY-BgcRoySA.js +0 -1
  84. package/dist/static/assets/eventmodeling-NTZA5JFV-yDcwp6lt.js +0 -1
  85. package/dist/static/assets/flowDiagram-HODETNUW-DnPPZa4g.js +0 -1
  86. package/dist/static/assets/mermaid-HWGCJPDP-DeEXv092.js +0 -1
  87. package/dist/static/assets/railroad-abnf-HS5TGJTU-D6cFd8f9.js +0 -1
  88. package/dist/static/assets/railroad-ebnf-LZEXJU2U-DFaxAxL1.js +0 -1
  89. package/dist/static/assets/railroad-peg-WCYAUIDC-CZJ_ATS3.js +0 -1
  90. package/dist/static/assets/stateDiagram-v2-MP3YSRHH-CWs-2TtB.js +0 -1
  91. package/dist/static/assets/swimlanesDiagram-VR7AAH4N-OvCnH9Zm.js +0 -8
package/dist/server.mjs CHANGED
@@ -256,7 +256,7 @@ Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycl
256
256
  `),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 ge.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()}`,ge.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new ih(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=oh(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=oh(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}
257
257
  `),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)=>Kc(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=Gn.basename(e,Gn.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(ge.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.
258
258
  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}
259
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function w0(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 D0(){if(ge.env.NO_COLOR||ge.env.FORCE_COLOR==="0"||ge.env.FORCE_COLOR==="false")return!1;if(ge.env.FORCE_COLOR||ge.env.CLICOLOR_FORCE!==void 0)return!0;return}var Ale=new no;var Ms={name:"@rainmanhhh/pi-web",version:"0.15.21",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",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",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":"playwright test","test:unit":"vitest run",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":"0.85.1","@earendil-works/pi-ai":"0.85.1","@earendil-works/pi-coding-agent":"0.85.1","@earendil-works/pi-tui":"0.85.1","@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",undici:"8.10.0",virtua:"^0.50.6",ws:"^8.21.3"},devDependencies:{"@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/ws":"^8.18.1","@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","@vitejs/plugin-react":"^6.1.1",biome:"^0.3.3",commander:"^15.0.0",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"}};import{getAgentDir as pI}from"@earendil-works/pi-coding-agent";var E0={port:31415};var ah=(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 T0=Symbol();var S0=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var C0=32,w4=1e4,Jc=(e)=>("headers"in e),k0=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,s=(Jc(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 D4(e,{all:n,dot:r});return{}};async function D4(e,t){if(!Jc(e)&&e.bodyCache.formData)return A0(await e.bodyCache.formData,t);let n=Jc(e)?e.headers:e.raw.headers,r=await e.arrayBuffer(),i=S0(r,n.get("Content-Type")||"");if(!Jc(e))e.bodyCache.formData=i;let o=await i;if(o)return A0(o,t);return{}}function A0(e,t){let n=Object.create(null),r={count:0};if(e.forEach((i,o)=>{if(!(t.all||o.endsWith("[]")))n[o]=i;else E4(n,o,i)}),t.dot)Object.entries(n).forEach(([i,o])=>{if(i.includes("."))T4(n,i,o,r),delete n[i]});return n}var E4=(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]},T4=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,o=t.split(".",C0+2);if(o.length>C0+1)U0();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++>=w4)U0();i[s]=Object.create(null)}i=i[s]}})},U0=()=>{throw Error("Nesting limit exceeded")};li();var B0=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&&tu(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]=tu(r)}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return M0(this.url,e)}queries(e){return N0(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 k0(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[T0](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};hh();var U4="text/plain; charset=UTF-8",ph=(e,t)=>({"Content-Type":e,...t}),Ns=(e,t)=>new Response(e,t),gh=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 B0(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||=Ns(null,{headers:this.#l??=new Headers})}set res(e){if(this.#r&&e){e=Ns(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=Ns(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 Ns(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,ph(U4,n));json=(e,t,n)=>this.#u(JSON.stringify(e),t,ph("application/json",n));html=(e,t,n)=>{let r=(i)=>this.#u(i,t,ph("text/html; charset=UTF-8",n));return typeof e==="object"?fh(e,L0.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??=()=>Ns(),this.#a(this))};xr();mh();li();var k4=(e)=>e.text("404 Not Found",404),$0=(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)},H0=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...q0,j0].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(qe,this.#e,a)}),this};let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??dh:P0}#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=k4;errorHandler=$0;route(t,n){let r=this.basePath(t);return n.routes.map((i)=>{let o;if(n.errorHandler===$0)o=i.handler;else o=async(s,a)=>(await ah([],n.errorHandler)(s,()=>i.handler(s,a))).res,o[Bs]=i.handler;r.#o(i.method,i.path,o,i.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=vr(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=vr(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(qe,vr(t,"*"),a),this}#o(t,n,r,i){t=t.toUpperCase(),n=vr(this._basePath,n);let o={basePath:i!==void 0?vr(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 gh(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=ah(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${vr("/",t)}`,n),r,i)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};xr();li();var Ve=()=>Object.create(null);xr();var iu=[];function yh(e,t){let n=this.buildAllMatchers(),r=(i,o)=>{let s=n[i]||n[qe],a=s[2][o];if(a)return a;let c=o.match(s[0]);if(!c)return[[],iu];let u=c.indexOf("",1);return[s[1][u],c]};return this.match=r,r(e,t)}var ro="[^/]+",wr=".*",zn="(?:|/.*)",_r=Symbol(),G0=new Set(".\\+*[^]$()");function R4(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===wr||e===zn)return t===zn?-1:1;else if(t===wr||t===zn)return-1;if(e===ro)return 1;else if(t===ro)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var z0=class e{#e;#t;#n=Ve();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?["","",wr]:["","",ro]:null:u==="/*"?["","",zn]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),f;if(d){let h=d[1],p=d[2]||ro;if(h&&d[2]){if(p===".*")throw _r;if(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))throw _r;if(p.length===1&&G0.has(p))throw _r}if(f=s.#n[p],!f){if(p!==wr&&p!==zn){for(let g in s.#n)if((p.length>1||g.length>1)&&g!==wr&&g!==zn)throw _r}f=s.#n[p]=new e}if(h!=="")f.#t??=i.varIndex++,r.push([h,f.#t])}else if(f=s.#n[u],!f){for(let h in s.#n)if(h.length>1&&h!==wr&&h!==zn)throw _r;f=s.#n[u]=new e}s=f}if(s.#e!==void 0)throw _r;s.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(R4).map((r)=>{let i=this.#n[r],o=i.buildRegExpStr();return o===""?"":(typeof i.#t==="number"?`(${r})@${i.#t}`:G0.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 bh=class{#e={varIndex:0};#t=new z0;#n=0;paths=Ve();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 V0=Ve();function X0(e){return V0[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?zn:t==="*"?wr:`/:${ro}`)}$`)}function ou(e,t){for(let n of Object.keys(e).sort((r,i)=>i.length-r.length))if(X0(n).test(t))return[...e[n]];return}var su=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[qe]:Ve()},this.#t={[qe]:Ve()},this.#n={[qe]:new bh}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===_r?new ru(t):n}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(nu);if(!r[e]){this.#n[e]=new bh;for(let a of[r,i]){a[e]=Ve();for(let c in a[qe])a[e][c]=[...a[qe][c]],this.#o(e,c)}}if(t==="/*")t="*";let o=e===qe?Object.keys(r):[e];if(/\*$/.test(t)){let a=X0(t);for(let c of o)if(!r[c][t])this.#o(c,t),r[c][t]=ou(r[c],t)||ou(r[qe],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=eu(t)||[t];for(let a of s)for(let c of o){if(!i[c][a])this.#o(c,a),i[c][a]=ou(r[c],a)||ou(r[qe],a)||[];i[c][a].push([n,a])}}match=yh;buildAllMatchers(){let e=Ve();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,V0=Ve(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Ve(),o=[],[s,a,c]=r.buildRegExp();for(let u of[t,n])for(let d in u){let f=u[d],h=r.paths[d];if(!h){i[d]=[f.map(([p])=>[p,Ve()]),iu];continue}o[h[0]]=f.map(([p,g])=>[p,r.paths[g][1].reduceRight((b,[v],m)=>(b[v]=c[h[1][m][1]],b),Ve())])}return[s,a.map((u)=>o[u]),i]}};xr();xr();var vh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(nu);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 ru)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]}};li();xr();li();var xh=Ve(),F4=0,K0=class e{#e=[];#t=Ve();#n=[];#o;#i=xh;insert(t,n,r){let i=this,o=R0(n),s=new Set,a=0;for(let c of o){let u=o[++a],d=F0(c,u)||(u===void 0&&c&&c.indexOf("*")===c.length-1?c:null),f=Array.isArray(d),h=f?d[0]:d||c,p=i.#t[h]||=new e;if(d&&!p.#o)p.#o=d,i.#n.push(p);if(i=p,f)s.add(d[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...s],score:++F4}})}#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[qe];if(u){u.params=Ve(),t.push(u);for(let d=0,f=u.possibleKeys.length;d<f;d++){let h=u.possibleKeys[d];u.params[h]=o?.[h]&&!d?o[h]:i[h]??o?.[h]}}}}search(t,n){let r=[];this.#i=xh;let o=[this],s=uh(n),a=[],c=s.length,u=null;for(let d=0;d<c;d++){let f=s[d],h=d===c-1,p=[];for(let b=0,v=o.length;b<v;b++){let m=o[b],_=m.#t[f];if(_)if(_.#i=m.#i,h){if(_.#t["*"])this.#r(r,_.#t["*"],t,m.#i);this.#r(r,_,t,m.#i)}else p.push(_);for(let y of m.#n){let x=y.#o,D=m.#i===xh?{}:{...m.#i};if(typeof x==="string"){if(x==="*"||f.startsWith(x.slice(0,-1))){if(this.#r(r,y,t,m.#i),x==="*")y.#i=D,p.push(y)}continue}let[,C,E]=x;if(!f&&E===!0)continue;if(E!==!0){if(!u){u=[];let N=n[0]==="/"?1:0;for(let O=0;O<c;O++)u[O]=N,N+=s[O].length+1}let U=n.slice(u[d]),A=E.exec(U);if(A){if(D[C]=A[0],this.#r(r,y,t,m.#i,D),A[0].length===U.length&&y.#t["*"])this.#r(r,y.#t["*"],t,m.#i,D);for(let N in y.#t){y.#i=D;let O=A[0].match(/\//g)?.length??0;(a[O]||=[]).push(y);break}continue}}if(E===!0||E.test(f))if(D[C]=f,h){if(this.#r(r,y,t,D,m.#i),y.#t["*"])this.#r(r,y.#t["*"],t,D,m.#i)}else y.#i=D,p.push(y)}}let g=a.shift();o=g?p.concat(g):p}if(r[1])r.sort((d,f)=>d.score-f.score);return[r.map(({handler:d,params:f})=>[d,f])]}};var _h=class{name="TrieRouter";#e=new K0;add(e,t,n){for(let r of eu(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}};var wh=class extends H0{constructor(e={}){super(e);this.router=e.router??new vh({routers:[new su,new _h]})}};import{getAgentDir as Bae}from"@earendil-works/pi-coding-agent";import{isIP as Z0}from"node:net";function Y0(e){return(e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e).toLowerCase().replace(/\.$/,"")}function J0(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 Y0(t.hostname)}catch{return null}}function O4(e){let t=e?.trim();if(!t)return null;return Z0(t)?Y0(t):J0(t)}function P4(e){return e==="localhost"||e.endsWith(".localhost")}function Q0(){return[process.env.PI_WEB_HOSTNAME,...process.env.PI_WEB_ALLOWED_HOSTS?.split(",")??[]].filter((e)=>Boolean(e?.trim()))}function e2(e){try{return new URL(e).origin}catch{return null}}function I4(e){let t=new URL(e.url),n=e.headers.get("host");return n?e2(`${t.protocol}//${n}`):null}function M4(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 Dh(e,t=Q0()){let n=e.headers.get("host"),r=n?J0(n):null;if(!r)return!1;if(P4(r)||Z0(r))return!0;return t.some((i)=>O4(i)===r)}function N4(e){let t=e.headers.get("origin");if(e.headers.get("sec-fetch-site")==="cross-site")return!1;if(!t)return!0;let r=I4(e);return r!==null&&e2(t)===r}function B4(e){return e.headers.has("origin")||e.headers.has("sec-fetch-site")}function Tt(e,t=Q0()){if(!Dh(e,t))return!1;if(M4(e))return!0;return!B4(e)||N4(e)}function Dr(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 L4,timingSafeEqual as W4}from"node:crypto";var j4="pi";function t2(e){return L4("sha256").update(e,"utf8").digest()}function n2(e,t){return W4(t2(e),t2(t))}function Ls(e=process.env.PI_WEB_PASSWORD){return typeof e==="string"&&e.length>0}function au(e,t=process.env.PI_WEB_PASSWORD){if(!Ls(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=n2(o,j4),c=n2(s,t);return a&&c}class Eh extends Request{nextUrl;constructor(e){let t=e.method!=="GET"&&e.method!=="HEAD";super(e.url,{method:e.method,headers:e.headers,body:t?e.body:void 0,duplex:t?"half":void 0,signal:e.signal});this.nextUrl=new URL(e.url)}}class w extends Response{static json(e,t){let n=new Headers(t?.headers);return n.set("content-type","application/json; charset=utf-8"),new w(JSON.stringify(e),{status:t?.status??200,statusText:t?.statusText,headers:n})}}var Th=!1,r2=performance.now();function i2(e){if(Th=e,r2=performance.now(),Th)jt("boot","debug log enabled")}function Wt(e){return(t,n)=>jt(e,t,n)}function jt(e,t,n){if(!Th)return;let r=performance.now()-r2,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}`:""}`)}var q4=Wt("mount"),$4=["GET","POST","PUT","PATCH","DELETE"];function ee(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 $4){let c=n[a];if(typeof c!=="function")continue;let u=c;e.on(a,s,async(d)=>{let f=performance.now(),h={};for(let[g,{hono:b,catchAll:v}]of o)if(v){let m=d.req.param(b)??"";h[g]=m===""?[]:m.split("/")}else h[g]=d.req.param(b)??"";let p=await u(new Eh(d.req.raw),{params:Promise.resolve(h)});return q4(`${a} ${d.req.path}`,`${p.status} ${Math.round(performance.now()-f)}ms`),p})}}var Mh={};Q(Mh,{GET:()=>U5});import{tmpdir as C5}from"node:os";import{Readable as A5}from"node:stream";import{constants as Sh}from"node:fs";import{lstat as H4,open as G4}from"node:fs/promises";import{basename as z4,dirname as V4,resolve as o2}from"node:path";var cu=5242880;function s2(e,t){let n=o2(e);if(V4(n)!==o2(t))return null;if(!/^pi-bash-[A-Za-z0-9_-]+\.log$/.test(z4(n)))return null;return n}async function Ch(e){if(!(await H4(e)).isFile())throw Error("Bash output path is not a regular file");let n=typeof Sh.O_NOFOLLOW==="number"?Sh.O_NOFOLLOW:0,r=await G4(e,Sh.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 a2(e,t=cu){let{handle:n,fileInfo:r}=await Ch(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()}}import{open as m2,readFile as a5,readdir as c5}from"node:fs/promises";import{existsSync as u5,readdirSync as l5}from"node:fs";import{join as fu,normalize as Oh}from"node:path";import{getAgentDir as d5,buildContextEntries as f5,buildSessionContext as h5,SessionManager as y2}from"@earendil-works/pi-coding-agent";function X4(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function K4(e){if(!X4(e)||e.type!=="toolCall")return null;return{type:"toolCall",toolCallId:typeof e.toolCallId==="string"?e.toolCallId:typeof e.id==="string"?e.id:"",toolName:typeof e.toolName==="string"?e.toolName:typeof e.name==="string"?e.name:"",input:typeof e.input==="object"&&e.input!==null&&!Array.isArray(e.input)?e.input:typeof e.arguments==="object"&&e.arguments!==null&&!Array.isArray(e.arguments)?e.arguments:{}}}function Ah(e){if(e.role!=="assistant")return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map((r)=>K4(r)??r);return{...e,content:n}}import c2 from"node:path";function qt(e,t=process.platform){let n=t==="win32"?c2.win32.normalize(e):c2.posix.normalize(e);return t==="win32"?n.toLowerCase():n}import{execFile as Z4}from"node:child_process";import{existsSync as lu,mkdirSync as Y4,realpathSync as J4}from"node:fs";import{basename as Q4,dirname as kh,join as l2,resolve as e5}from"node:path";import{promisify as t5}from"node:util";function $e(e){let t=e.replace(/\\/g,"/");return/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Uh(){if(!globalThis.__piAdditionalAllowedRoots)globalThis.__piAdditionalAllowedRoots=new Set;return globalThis.__piAdditionalAllowedRoots}function yt(e){if(!e)return;let t=$e(e);Uh().add(t),globalThis.__piAllowedRootsCache?.roots.add(t)}var n5=t5(Z4),u2=60000;function r5(){if(!globalThis.__piProjectCache)globalThis.__piProjectCache=new Map;return globalThis.__piProjectCache}function d2(){globalThis.__piProjectCache?.clear()}async function di(e,t){let{stdout:n}=await n5("git",["-C",e,...t],{timeout:1e4,maxBuffer:1048576,env:{...process.env,LC_ALL:"C"}});return n.trim()}function uu(e){let t=e.replace(/\\/g,"/");if(process.platform==="win32")t=t.replace(/^\/([a-zA-Z])\/(?=.)/,(n,r)=>`${r.toUpperCase()}:/`),t=t.toLowerCase();return t}function i5(e){let t=kh(e);if(!t.endsWith("-worktrees"))return null;let n=t.slice(0,-10);if(!n||!lu(l2(n,".git")))return null;return{projectRoot:n,branch:Q4(e),isWorktree:!0,isTopLevel:!0}}async function du(e){let t=r5(),n=t.get(e);if(n&&n.expiresAt>Date.now())return n.info;let r;try{if(!lu(e))return r=i5(e)??{projectRoot:e,branch:null,isWorktree:!1,isTopLevel:!1},t.set(e,{info:r,expiresAt:Date.now()+u2}),r;let i=await di(e,["rev-parse","--path-format=absolute","--git-common-dir","--git-dir","--show-toplevel","--abbrev-ref","HEAD"]),[o,s,a,c]=i.split(`
259
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function w0(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 D0(){if(ge.env.NO_COLOR||ge.env.FORCE_COLOR==="0"||ge.env.FORCE_COLOR==="false")return!1;if(ge.env.FORCE_COLOR||ge.env.CLICOLOR_FORCE!==void 0)return!0;return}var Ale=new no;var Ms={name:"@rainmanhhh/pi-web",version:"0.15.22",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",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",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":"playwright test","test:unit":"vitest run",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":"0.85.1","@earendil-works/pi-ai":"0.85.1","@earendil-works/pi-coding-agent":"0.85.1","@earendil-works/pi-tui":"0.85.1","@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",undici:"8.10.0",virtua:"^0.50.6",ws:"^8.21.3"},devDependencies:{"@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/ws":"^8.18.1","@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","@vitejs/plugin-react":"^6.1.1",biome:"^0.3.3",commander:"^15.0.0",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"}};import{getAgentDir as pI}from"@earendil-works/pi-coding-agent";var E0={port:31415};var ah=(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 T0=Symbol();var S0=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var C0=32,w4=1e4,Jc=(e)=>("headers"in e),k0=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,s=(Jc(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 D4(e,{all:n,dot:r});return{}};async function D4(e,t){if(!Jc(e)&&e.bodyCache.formData)return A0(await e.bodyCache.formData,t);let n=Jc(e)?e.headers:e.raw.headers,r=await e.arrayBuffer(),i=S0(r,n.get("Content-Type")||"");if(!Jc(e))e.bodyCache.formData=i;let o=await i;if(o)return A0(o,t);return{}}function A0(e,t){let n=Object.create(null),r={count:0};if(e.forEach((i,o)=>{if(!(t.all||o.endsWith("[]")))n[o]=i;else E4(n,o,i)}),t.dot)Object.entries(n).forEach(([i,o])=>{if(i.includes("."))T4(n,i,o,r),delete n[i]});return n}var E4=(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]},T4=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,o=t.split(".",C0+2);if(o.length>C0+1)U0();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++>=w4)U0();i[s]=Object.create(null)}i=i[s]}})},U0=()=>{throw Error("Nesting limit exceeded")};li();var B0=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&&tu(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]=tu(r)}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return M0(this.url,e)}queries(e){return N0(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 k0(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[T0](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};hh();var U4="text/plain; charset=UTF-8",ph=(e,t)=>({"Content-Type":e,...t}),Ns=(e,t)=>new Response(e,t),gh=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 B0(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||=Ns(null,{headers:this.#l??=new Headers})}set res(e){if(this.#r&&e){e=Ns(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=Ns(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 Ns(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,ph(U4,n));json=(e,t,n)=>this.#u(JSON.stringify(e),t,ph("application/json",n));html=(e,t,n)=>{let r=(i)=>this.#u(i,t,ph("text/html; charset=UTF-8",n));return typeof e==="object"?fh(e,L0.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??=()=>Ns(),this.#a(this))};xr();mh();li();var k4=(e)=>e.text("404 Not Found",404),$0=(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)},H0=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...q0,j0].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(qe,this.#e,a)}),this};let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??dh:P0}#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=k4;errorHandler=$0;route(t,n){let r=this.basePath(t);return n.routes.map((i)=>{let o;if(n.errorHandler===$0)o=i.handler;else o=async(s,a)=>(await ah([],n.errorHandler)(s,()=>i.handler(s,a))).res,o[Bs]=i.handler;r.#o(i.method,i.path,o,i.basePath)}),this}basePath(t){let n=this.#t();return n._basePath=vr(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=vr(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(qe,vr(t,"*"),a),this}#o(t,n,r,i){t=t.toUpperCase(),n=vr(this._basePath,n);let o={basePath:i!==void 0?vr(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 gh(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=ah(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${vr("/",t)}`,n),r,i)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method))})}};xr();li();var Ve=()=>Object.create(null);xr();var iu=[];function yh(e,t){let n=this.buildAllMatchers(),r=(i,o)=>{let s=n[i]||n[qe],a=s[2][o];if(a)return a;let c=o.match(s[0]);if(!c)return[[],iu];let u=c.indexOf("",1);return[s[1][u],c]};return this.match=r,r(e,t)}var ro="[^/]+",wr=".*",zn="(?:|/.*)",_r=Symbol(),G0=new Set(".\\+*[^]$()");function R4(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===wr||e===zn)return t===zn?-1:1;else if(t===wr||t===zn)return-1;if(e===ro)return 1;else if(t===ro)return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var z0=class e{#e;#t;#n=Ve();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?["","",wr]:["","",ro]:null:u==="/*"?["","",zn]:u.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),f;if(d){let h=d[1],p=d[2]||ro;if(h&&d[2]){if(p===".*")throw _r;if(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))throw _r;if(p.length===1&&G0.has(p))throw _r}if(f=s.#n[p],!f){if(p!==wr&&p!==zn){for(let g in s.#n)if((p.length>1||g.length>1)&&g!==wr&&g!==zn)throw _r}f=s.#n[p]=new e}if(h!=="")f.#t??=i.varIndex++,r.push([h,f.#t])}else if(f=s.#n[u],!f){for(let h in s.#n)if(h.length>1&&h!==wr&&h!==zn)throw _r;f=s.#n[u]=new e}s=f}if(s.#e!==void 0)throw _r;s.#e=o?-1:n}buildRegExpStr(){let n=Object.keys(this.#n).sort(R4).map((r)=>{let i=this.#n[r],o=i.buildRegExpStr();return o===""?"":(typeof i.#t==="number"?`(${r})@${i.#t}`:G0.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 bh=class{#e={varIndex:0};#t=new z0;#n=0;paths=Ve();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 V0=Ve();function X0(e){return V0[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,n)=>n?`\\${n}`:t==="/*"?zn:t==="*"?wr:`/:${ro}`)}$`)}function ou(e,t){for(let n of Object.keys(e).sort((r,i)=>i.length-r.length))if(X0(n).test(t))return[...e[n]];return}var su=class{name="RegExpRouter";#e;#t;#n;constructor(){this.#e={[qe]:Ve()},this.#t={[qe]:Ve()},this.#n={[qe]:new bh}}#o(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(n){throw n===_r?new ru(t):n}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(nu);if(!r[e]){this.#n[e]=new bh;for(let a of[r,i]){a[e]=Ve();for(let c in a[qe])a[e][c]=[...a[qe][c]],this.#o(e,c)}}if(t==="/*")t="*";let o=e===qe?Object.keys(r):[e];if(/\*$/.test(t)){let a=X0(t);for(let c of o)if(!r[c][t])this.#o(c,t),r[c][t]=ou(r[c],t)||ou(r[qe],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=eu(t)||[t];for(let a of s)for(let c of o){if(!i[c][a])this.#o(c,a),i[c][a]=ou(r[c],a)||ou(r[qe],a)||[];i[c][a].push([n,a])}}match=yh;buildAllMatchers(){let e=Ve();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,V0=Ve(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Ve(),o=[],[s,a,c]=r.buildRegExp();for(let u of[t,n])for(let d in u){let f=u[d],h=r.paths[d];if(!h){i[d]=[f.map(([p])=>[p,Ve()]),iu];continue}o[h[0]]=f.map(([p,g])=>[p,r.paths[g][1].reduceRight((b,[v],m)=>(b[v]=c[h[1][m][1]],b),Ve())])}return[s,a.map((u)=>o[u]),i]}};xr();xr();var vh=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(nu);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 ru)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]}};li();xr();li();var xh=Ve(),F4=0,K0=class e{#e=[];#t=Ve();#n=[];#o;#i=xh;insert(t,n,r){let i=this,o=R0(n),s=new Set,a=0;for(let c of o){let u=o[++a],d=F0(c,u)||(u===void 0&&c&&c.indexOf("*")===c.length-1?c:null),f=Array.isArray(d),h=f?d[0]:d||c,p=i.#t[h]||=new e;if(d&&!p.#o)p.#o=d,i.#n.push(p);if(i=p,f)s.add(d[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...s],score:++F4}})}#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[qe];if(u){u.params=Ve(),t.push(u);for(let d=0,f=u.possibleKeys.length;d<f;d++){let h=u.possibleKeys[d];u.params[h]=o?.[h]&&!d?o[h]:i[h]??o?.[h]}}}}search(t,n){let r=[];this.#i=xh;let o=[this],s=uh(n),a=[],c=s.length,u=null;for(let d=0;d<c;d++){let f=s[d],h=d===c-1,p=[];for(let b=0,v=o.length;b<v;b++){let m=o[b],_=m.#t[f];if(_)if(_.#i=m.#i,h){if(_.#t["*"])this.#r(r,_.#t["*"],t,m.#i);this.#r(r,_,t,m.#i)}else p.push(_);for(let y of m.#n){let x=y.#o,D=m.#i===xh?{}:{...m.#i};if(typeof x==="string"){if(x==="*"||f.startsWith(x.slice(0,-1))){if(this.#r(r,y,t,m.#i),x==="*")y.#i=D,p.push(y)}continue}let[,C,E]=x;if(!f&&E===!0)continue;if(E!==!0){if(!u){u=[];let N=n[0]==="/"?1:0;for(let O=0;O<c;O++)u[O]=N,N+=s[O].length+1}let U=n.slice(u[d]),A=E.exec(U);if(A){if(D[C]=A[0],this.#r(r,y,t,m.#i,D),A[0].length===U.length&&y.#t["*"])this.#r(r,y.#t["*"],t,m.#i,D);for(let N in y.#t){y.#i=D;let O=A[0].match(/\//g)?.length??0;(a[O]||=[]).push(y);break}continue}}if(E===!0||E.test(f))if(D[C]=f,h){if(this.#r(r,y,t,D,m.#i),y.#t["*"])this.#r(r,y.#t["*"],t,D,m.#i)}else y.#i=D,p.push(y)}}let g=a.shift();o=g?p.concat(g):p}if(r[1])r.sort((d,f)=>d.score-f.score);return[r.map(({handler:d,params:f})=>[d,f])]}};var _h=class{name="TrieRouter";#e=new K0;add(e,t,n){for(let r of eu(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}};var wh=class extends H0{constructor(e={}){super(e);this.router=e.router??new vh({routers:[new su,new _h]})}};import{getAgentDir as Bae}from"@earendil-works/pi-coding-agent";import{isIP as Z0}from"node:net";function Y0(e){return(e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e).toLowerCase().replace(/\.$/,"")}function J0(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 Y0(t.hostname)}catch{return null}}function O4(e){let t=e?.trim();if(!t)return null;return Z0(t)?Y0(t):J0(t)}function P4(e){return e==="localhost"||e.endsWith(".localhost")}function Q0(){return[process.env.PI_WEB_HOSTNAME,...process.env.PI_WEB_ALLOWED_HOSTS?.split(",")??[]].filter((e)=>Boolean(e?.trim()))}function e2(e){try{return new URL(e).origin}catch{return null}}function I4(e){let t=new URL(e.url),n=e.headers.get("host");return n?e2(`${t.protocol}//${n}`):null}function M4(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 Dh(e,t=Q0()){let n=e.headers.get("host"),r=n?J0(n):null;if(!r)return!1;if(P4(r)||Z0(r))return!0;return t.some((i)=>O4(i)===r)}function N4(e){let t=e.headers.get("origin");if(e.headers.get("sec-fetch-site")==="cross-site")return!1;if(!t)return!0;let r=I4(e);return r!==null&&e2(t)===r}function B4(e){return e.headers.has("origin")||e.headers.has("sec-fetch-site")}function Tt(e,t=Q0()){if(!Dh(e,t))return!1;if(M4(e))return!0;return!B4(e)||N4(e)}function Dr(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 L4,timingSafeEqual as W4}from"node:crypto";var j4="pi";function t2(e){return L4("sha256").update(e,"utf8").digest()}function n2(e,t){return W4(t2(e),t2(t))}function Ls(e=process.env.PI_WEB_PASSWORD){return typeof e==="string"&&e.length>0}function au(e,t=process.env.PI_WEB_PASSWORD){if(!Ls(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=n2(o,j4),c=n2(s,t);return a&&c}class Eh extends Request{nextUrl;constructor(e){let t=e.method!=="GET"&&e.method!=="HEAD";super(e.url,{method:e.method,headers:e.headers,body:t?e.body:void 0,duplex:t?"half":void 0,signal:e.signal});this.nextUrl=new URL(e.url)}}class w extends Response{static json(e,t){let n=new Headers(t?.headers);return n.set("content-type","application/json; charset=utf-8"),new w(JSON.stringify(e),{status:t?.status??200,statusText:t?.statusText,headers:n})}}var Th=!1,r2=performance.now();function i2(e){if(Th=e,r2=performance.now(),Th)jt("boot","debug log enabled")}function Wt(e){return(t,n)=>jt(e,t,n)}function jt(e,t,n){if(!Th)return;let r=performance.now()-r2,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}`:""}`)}var q4=Wt("mount"),$4=["GET","POST","PUT","PATCH","DELETE"];function ee(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 $4){let c=n[a];if(typeof c!=="function")continue;let u=c;e.on(a,s,async(d)=>{let f=performance.now(),h={};for(let[g,{hono:b,catchAll:v}]of o)if(v){let m=d.req.param(b)??"";h[g]=m===""?[]:m.split("/")}else h[g]=d.req.param(b)??"";let p=await u(new Eh(d.req.raw),{params:Promise.resolve(h)});return q4(`${a} ${d.req.path}`,`${p.status} ${Math.round(performance.now()-f)}ms`),p})}}var Mh={};Q(Mh,{GET:()=>U5});import{tmpdir as C5}from"node:os";import{Readable as A5}from"node:stream";import{constants as Sh}from"node:fs";import{lstat as H4,open as G4}from"node:fs/promises";import{basename as z4,dirname as V4,resolve as o2}from"node:path";var cu=5242880;function s2(e,t){let n=o2(e);if(V4(n)!==o2(t))return null;if(!/^pi-bash-[A-Za-z0-9_-]+\.log$/.test(z4(n)))return null;return n}async function Ch(e){if(!(await H4(e)).isFile())throw Error("Bash output path is not a regular file");let n=typeof Sh.O_NOFOLLOW==="number"?Sh.O_NOFOLLOW:0,r=await G4(e,Sh.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 a2(e,t=cu){let{handle:n,fileInfo:r}=await Ch(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()}}import{open as m2,readFile as a5,readdir as c5}from"node:fs/promises";import{existsSync as u5,readdirSync as l5}from"node:fs";import{join as fu,normalize as Oh}from"node:path";import{getAgentDir as d5,buildContextEntries as f5,buildSessionContext as h5,SessionManager as y2}from"@earendil-works/pi-coding-agent";function X4(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function K4(e){if(!X4(e)||e.type!=="toolCall")return null;return{type:"toolCall",toolCallId:typeof e.toolCallId==="string"?e.toolCallId:typeof e.id==="string"?e.id:"",toolName:typeof e.toolName==="string"?e.toolName:typeof e.name==="string"?e.name:"",input:typeof e.input==="object"&&e.input!==null&&!Array.isArray(e.input)?e.input:typeof e.arguments==="object"&&e.arguments!==null&&!Array.isArray(e.arguments)?e.arguments:{}}}function Ah(e){if(e.role!=="assistant")return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map((r)=>K4(r)??r);return{...e,content:n}}import c2 from"node:path";function qt(e,t=process.platform){let n=t==="win32"?c2.win32.normalize(e):c2.posix.normalize(e);return t==="win32"?n.toLowerCase():n}import{execFile as Z4}from"node:child_process";import{existsSync as lu,mkdirSync as Y4,realpathSync as J4}from"node:fs";import{basename as Q4,dirname as kh,join as l2,resolve as e5}from"node:path";import{promisify as t5}from"node:util";function $e(e){let t=e.replace(/\\/g,"/");return/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function Uh(){if(!globalThis.__piAdditionalAllowedRoots)globalThis.__piAdditionalAllowedRoots=new Set;return globalThis.__piAdditionalAllowedRoots}function yt(e){if(!e)return;let t=$e(e);Uh().add(t),globalThis.__piAllowedRootsCache?.roots.add(t)}var n5=t5(Z4),u2=60000;function r5(){if(!globalThis.__piProjectCache)globalThis.__piProjectCache=new Map;return globalThis.__piProjectCache}function d2(){globalThis.__piProjectCache?.clear()}async function di(e,t){let{stdout:n}=await n5("git",["-C",e,...t],{timeout:1e4,maxBuffer:1048576,env:{...process.env,LC_ALL:"C"}});return n.trim()}function uu(e){let t=e.replace(/\\/g,"/");if(process.platform==="win32")t=t.replace(/^\/([a-zA-Z])\/(?=.)/,(n,r)=>`${r.toUpperCase()}:/`),t=t.toLowerCase();return t}function i5(e){let t=kh(e);if(!t.endsWith("-worktrees"))return null;let n=t.slice(0,-10);if(!n||!lu(l2(n,".git")))return null;return{projectRoot:n,branch:Q4(e),isWorktree:!0,isTopLevel:!0}}async function du(e){let t=r5(),n=t.get(e);if(n&&n.expiresAt>Date.now())return n.info;let r;try{if(!lu(e))return r=i5(e)??{projectRoot:e,branch:null,isWorktree:!1,isTopLevel:!1},t.set(e,{info:r,expiresAt:Date.now()+u2}),r;let i=await di(e,["rev-parse","--path-format=absolute","--git-common-dir","--git-dir","--show-toplevel","--abbrev-ref","HEAD"]),[o,s,a,c]=i.split(`
260
260
  `).map((h)=>h.trim()),u=e;try{u=J4(e)}catch{}let d=uu(a)===uu(u),f=s!==o&&d;r={projectRoot:f?kh(o):e,branch:c&&c!=="HEAD"?c:null,isWorktree:f,isTopLevel:d}}catch{r={projectRoot:e,branch:null,isWorktree:!1,isTopLevel:!1}}return t.set(e,{info:r,expiresAt:Date.now()+u2}),r}async function o5(e){let t=await di(e,["rev-parse","--path-format=absolute","--git-common-dir"]);return kh(t)}async function Rh(e){let t=await di(e,["worktree","list","--porcelain"]),n=[],r=null,i=()=>{if(r?.path){if(!r.prunable&&lu(r.path))n.push({path:r.path,branch:r.branch??null,isMain:n.length===0})}r=null};for(let o of t.split(`
261
261
  `))if(o.startsWith("worktree "))i(),r={path:o.slice(9).trim()};else if(o.startsWith("branch ")&&r)r.branch=o.slice(7).trim().replace(/^refs\/heads\//,"");else if(o.startsWith("prunable")&&r)r.prunable=!0;else if(o.trim()==="")i();return i(),n}function s5(e){return e.replace(/[/\\:*?"<>|\s]+/g,"-").replace(/^-+|-+$/g,"")}async function f2(e,t){let n=t.trim();if(!n)throw Error("Branch name is required");let r=s5(n);if(!r)throw Error(`Invalid branch name: ${t}`);let i=await o5(e),o=`${e5(i)}-worktrees`,s=l2(o,r);if(lu(s))throw Error(`Directory already exists: ${s}`);Y4(o,{recursive:!0});let a=!1;try{await di(i,["rev-parse","--verify","--quiet",`refs/heads/${n}`]),a=!0}catch{a=!1}try{if(a)await di(i,["worktree","add","--",s,n]);else await di(i,["worktree","add","-b",n,"--",s])}catch(c){throw Error(p2(c),{cause:c})}return yt(s),d2(),{path:s,branch:n}}async function h2(e,t,n=!1){let i=(await Rh(e)).find((o)=>uu(o.path)===uu(t));if(!i)throw Error(`Not a worktree of this repository: ${t}`);if(i.isMain)throw Error("Cannot remove the main worktree");try{await di(e,["worktree","remove",...n?["--force"]:[],t])}catch(o){throw Error(p2(o),{cause:o})}d2()}function p2(e){let t=e.stderr;if(typeof t==="string"&&t.trim())return t.trim();return e instanceof Error?e.message:String(e)}async function p5(e,t){let n=new Map;for(let o of e)n.set(qt(o.path),o.id);let r=[...new Set(e.map((o)=>o.cwd).filter(Boolean))],i=new Map;return await Promise.all(r.map(async(o)=>{i.set(o,await du(o))})),e.map((o)=>{Er(o.id,o.path,t);let s=o.cwd?i.get(o.cwd):void 0;return{path:o.path,id:o.id,cwd:o.cwd,name:o.name,created:o.created instanceof Date?o.created.toISOString():String(o.created),modified:o.modified instanceof Date?o.modified.toISOString():String(o.modified),messageCount:o.messageCount,firstMessage:o.firstMessage||"(no messages)",parentSessionId:o.parentSessionPath?n.get(qt(o.parentSessionPath)):void 0,projectRoot:s?.projectRoot??o.cwd,...s?.isWorktree&&s.branch?{worktreeBranch:s.branch}:{}}})}async function g5(){let e=await b2(fu(d5(),"sessions"));for(let t of e)Er(t.id,t.path);return e}async function m5(e){let t=[],n=async(r)=>{let i;try{i=await c5(r,{withFileTypes:!0})}catch{return}for(let o of i){let s=fu(r,o.name);if(o.isDirectory())await n(s);else if(o.name.endsWith(".jsonl"))t.push(s)}};try{await n(e)}catch{}return t}function y5(e){if(!Array.isArray(e.content))return"";return e.content.filter((t)=>!!t&&typeof t==="object"&&t.type==="text"&&typeof t.text==="string").map((t)=>t.text).join(" ")}async function b5(e){let t=await a5(e,"utf8"),n=[];for(let u of t.split(`
262
262
  `)){let d=u.trim();if(!d)continue;try{let f=JSON.parse(d);if(f&&typeof f==="object")n.push(f)}catch{}}if(n.length===0)throw Error("file contains no session entries");let r=n[0];if(r?.type!=="session"||typeof r.id!=="string")throw Error("missing session header (first line must be a session entry)");let i=new Date(r.timestamp);if(Number.isNaN(i.getTime()))throw Error(`invalid session header timestamp: ${JSON.stringify(r.timestamp)}`);let o=0,s="",a,c;for(let u of n){let d=u;if(d.type==="session_info"){let g=d.name;if(typeof g==="string"&&g.trim())a=g.trim();continue}if(d.type!=="message")continue;o++;let f=d.message;if(!f||f.role!=="user"&&f.role!=="assistant")continue;let h=typeof f.timestamp==="number"?f.timestamp:new Date(d.timestamp).getTime();if(typeof h==="number"&&!Number.isNaN(h))c=Math.max(c??0,h);if(f.role==="user"&&!s){let g=y5(f);if(g)s=g}}return{path:e,id:r.id,cwd:typeof r.cwd==="string"?r.cwd:"",name:a,parentSessionPath:typeof r.parentSession==="string"?r.parentSession:void 0,created:i,modified:typeof c==="number"&&c>0?new Date(c):i,messageCount:o,firstMessage:s||"(no messages)",allMessagesText:""}}function v5(e,t){if(e.error)return t.error?0:1;if(t.error)return-1;return e.modified<t.modified?1:e.modified>t.modified?-1:0}async function x5(e){try{let t=await m2(e,"r");try{let n=Buffer.alloc(8192),{bytesRead:r}=await t.read(n,0,n.length,null),i=n.subarray(0,r).toString("utf8").split(`
@@ -348,7 +348,7 @@ ${a}`,t.length>Wb)break}catch{t+=`
348
348
  git diff:
349
349
  `;async function dne(e){let t="",n="";try{let r=await e.json(),i=await Nn(r.cwd);if(!i.ok)return w.json({error:i.error},{status:i.status});let o=typeof r.provider==="string"?r.provider.trim():"",s=typeof r.modelId==="string"?r.modelId.trim():"";if(t=o,n=s,!o||!s)return w.json({error:"provider and modelId are required"},{status:400});let a=typeof r.maxTokens==="number"&&Number.isFinite(r.maxTokens)?Math.min(4096,Math.max(64,Math.round(r.maxTokens))):512,c=await une(i.cwd);if(!c)return w.json({error:"No changes to generate commit message"},{status:400});let u=await one.create(),d=u.getError();if(d)return w.json({error:d},{status:500});let f=u.getModel(o,s);if(!f)return w.json({error:`Model not found: ${o}/${s}`},{status:404});let h=await u.getAuth(f);if(!h?.auth.apiKey)return w.json({error:`No API key for provider "${o}"`},{status:400});let p=f,g=c,b=f.contextWindow;if(typeof b==="number"&&b>0&&b<20000){let x=a+1500,C=Math.max(3000,b-x)*3;if(g.length>C)g=`${g.slice(0,C)}
350
350
 
351
- ... (truncated for context limit ${b})`}let v=Wt("generate-commit"),m;if(f.reasoning){let x={...f.thinkingLevelMap??{}};for(let C of["off","minimal","low","medium","high"])if(!(C in x))x[C]=C;m=["off","minimal","low","medium","high","xhigh","max"].find((C)=>typeof x[C]==="string")??"low",f.thinkingLevelMap=x}console.log(`[generate-commit] start provider=${o} model=${s} maxTokens=${a} ctx=${b??"unknown"} diffLen=${c.length} promptLen=${g.length} reasoningHint=${m??"<omitted>"}`),v("start",`provider=${o} model=${s} maxTokens=${a} ctx=${b??"unknown"} diffLen=${c.length} promptLen=${g.length} reasoningHint=${m??"<omitted>"}`),v("diff-preview",g.slice(0,50).replace(/\n/g,"\\n"));let _=new AbortController,y=setTimeout(()=>_.abort(),p3);try{let x={apiKey:h.auth.apiKey,headers:h.auth.headers,maxTokens:a,timeoutMs:p3,maxRetries:0,cacheRetention:"none",signal:_.signal};if(m!==void 0&&m!=="off")x.reasoning=m;let D=await sne(p,{messages:[{role:"user",content:lne+g,timestamp:Date.now()}]},x);if(D.stopReason==="error"||D.stopReason==="aborted"){let E=D.errorMessage??(_.signal.aborted?"Generation timed out":"Model error");return console.error(`[generate-commit] failed provider=${o} model=${s} stopReason=${D.stopReason} error=${E}`),v("failed",`provider=${o} model=${s} stopReason=${D.stopReason} error=${E.slice(0,300)}`),w.json({error:E},{status:500})}let C=D.content.filter((E)=>E.type==="text").map((E)=>E.text).join("").trim().replace(/^```[\s\S]*?```$/m,(E)=>E.replace(/^```.*\n|\n```$/g,"").trim()).trim();if(v("result",`stopReason=${D.stopReason??"unknown"} contentTypes=${D.content.map((E)=>E.type).join(",")} textLen=${C.length} error=${D.errorMessage??""}`),!C){let E=D.stopReason==="length"||D.content.length>0&&D.content.every((A)=>A.type!=="text")?"(可能是推理模型上下文/ tokens 不足,尝试换用更大的 maxTokens 或非推理模型)":"",U=`Model returned empty message (stopReason=${D.stopReason??"unknown"})${E}`;return console.warn(`[generate-commit] empty text provider=${o} model=${s} maxTokens=${a} stopReason=${D.stopReason??"unknown"} content=${JSON.stringify(D.content).slice(0,600)} error=${D.errorMessage??""} frontendError=${U}`),v("empty",U),w.json({error:U},{status:500})}return v("success",`provider=${o} model=${s} stopReason=${D.stopReason??"unknown"} len=${C.length} preview=${C.slice(0,50).replace(/\n/g,"\\n")}`),console.log(`[generate-commit] success provider=${o} model=${s} stopReason=${D.stopReason??"unknown"} len=${C.length}`),w.json({message:C})}finally{clearTimeout(y)}}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`[generate-commit] exception provider=${t||"unknown"} model=${n||"unknown"} error=${i.slice(0,800)}`),w.json({error:i},{status:500})}}var $b={};Q($b,{POST:()=>fne});async function fne(e){try{let t=await e.json(),n=await Nn(t.cwd);if(!n.ok)return w.json({error:n.error},{status:n.status});let r=await u3(n.cwd);if(!r.ok)return w.json({error:r.error},{status:400});return w.json({ok:!0,output:r.output})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var Hb={};Q(Hb,{POST:()=>hne});async function hne(e){try{let t=await e.json(),n=await Nn(t.cwd);if(!n.ok)return w.json({error:n.error},{status:n.status});let r=await l3(n.cwd);if(!r.ok)return w.json({error:r.error},{status:400});return w.json({ok:!0,output:r.output})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var cv={};Q(cv,{GET:()=>kne});function Gb(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}import{mkdirSync as gne,readFileSync as af,writeFileSync as v3,existsSync as mne}from"node:fs";import{dirname as yne,join as Zb}from"node:path";import{getAgentDir as Yb}from"@earendil-works/pi-coding-agent";var rf=["off","minimal","low","medium","high","xhigh","max"];var g3=[{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 m3=g3;var of=new Map;function Jb(e){return Zb(e??Yb(),"pi-web","config.json")}function bne(e){return Zb(e??Yb(),"pi-web-preferences.json")}function x3(e){try{if(mne(Jb(e)))return;let t=JSON.parse(af(bne(e),"utf8"));Qb({firstPaint:{locale:tv(t.firstPaint?.locale),fontScale:ov(t.firstPaint?.fontScale)},preferences:t.preferences??{}},e)}catch{}}function ti(e){let t=e===void 0,n=e??"",r=t?of.get(n):void 0;if(!t||r===void 0||r===null)try{let d=af(Jb(e),"utf8"),f=JSON.parse(d);r={firstPaint:{locale:tv(f.firstPaint?.locale),fontScale:ov(f.firstPaint?.fontScale)},preferences:f.preferences??{},theme:sf(e)},of.set(n,r)}catch{if(r={firstPaint:{},preferences:{},theme:sf(e)},t)of.set(n,r)}let i=nv(ps("defaultThinkingLevel",e)),o=rv(e),s=iv(e),a=Vb(ps("defaultProjectTrust",e)),c=S3(e),u=sv(e);return{...r,theme:sf(e),...i!==void 0?{defaultThinkingLevel:i}:{},...o!==void 0?{compaction:o}:{},...s!==void 0?{retry:s}:{},...a!==void 0?{defaultProjectTrust:a}:{},...c!==void 0?{subagents:c}:{},...u!==void 0?{piSettings:u}:{}}}function Qb(e,t){try{let n=Jb(t);gne(yne(n),{recursive:!0});let r={firstPaint:e.firstPaint,preferences:e.preferences};if(v3(n,JSON.stringify(r,null,2),"utf8"),t===void 0)of.set("",e)}catch{}}function _3(e,t){let n=ti(t),r={...n.firstPaint,...e.locale!==void 0?{locale:tv(e.locale)??n.firstPaint.locale}:{},...e.fontScale!==void 0?{fontScale:ov(e.fontScale)??n.firstPaint.fontScale}:{}},i=n.theme;if(e.theme!==void 0)i=Dne(e.theme,t);let o=e.defaultThinkingLevel===void 0?ps("defaultThinkingLevel",t):Kb("defaultThinkingLevel",nv(e.defaultThinkingLevel),t),s=e.compaction===void 0?rv(t):vne(e.compaction,t),a=e.retry===void 0?iv(t):_ne(e.retry,t),c=e.defaultProjectTrust===void 0?Vb(ps("defaultProjectTrust",t)):(()=>{let h=Vb(e.defaultProjectTrust);if(h===void 0)return;return Kb("defaultProjectTrust",h,t),h})(),u=e.subagents===void 0?S3(t):wne(e.subagents,t),d=e.piSettings===void 0?sv(t):Ene(e.piSettings,t),f={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?{subagents:u}:{},...d!==void 0?{piSettings:d}:{}};return Qb(f,t),f}function ev(e,t){let n=ti(t),r={firstPaint:n.firstPaint,preferences:{...n.preferences,...e},theme:n.theme};return Qb(r,t),r}function w3(e){let{preferences:t}=ti(e);if(t.startScreenMessages!==void 0)return;ev({startScreenMessages:m3},e)}function tv(e){return e==="en"||e==="zh-CN"?e:void 0}function D3(e){return e==="dark"||e==="light"?e:void 0}function nv(e){return typeof e==="string"&&rf.includes(e)?e:void 0}function E3(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 rv(e){return E3(gs("compaction",e))}function vne(e,t){let n=E3(e);if(!n)return rv(t);return wc("compaction",n,t),n}function xne(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 T3(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=xne(t.provider);if(r!==void 0)n.provider=r;return n}function iv(e){return T3(gs("retry",e))}function _ne(e,t){let n=T3(e);if(!n)return iv(t);return wc("retry",n,t),n}function Vb(e){if(e==="ask"||e==="always"||e==="never")return e;if(e==="trust")return"always";if(e==="deny")return"never";return}function Xb(e){if(typeof e!=="object"||e===null)return;let t=e,n={};if(typeof t.defaultModel==="string"&&t.defaultModel.trim()!=="")n.defaultModel=t.defaultModel;let r=nv(t.defaultThinking);if(r!==void 0)n.defaultThinking=r;return Object.keys(n).length>0?n:void 0}function S3(e){return Xb(gs("subagents",e))}function wne(e,t){let n=Xb(e);if(n===void 0)return;let r=gs("subagents",t),i=typeof r==="object"&&r!==null?{...r}:{};if(n.defaultModel!==void 0)i.defaultModel=n.defaultModel;else delete i.defaultModel;if(n.defaultThinking!==void 0)i.defaultThinking=n.defaultThinking;else delete i.defaultThinking;return wc("subagents",i,t),Xb(i)}function gs(e,t){try{return JSON.parse(af(C3(t),"utf8"))[e]}catch{return}}function wc(e,t,n){try{let r=C3(n),i={};try{i=JSON.parse(af(r,"utf8"))}catch{i={}}i[e]=t,v3(r,JSON.stringify(i,null,2),"utf8")}catch{}}function ps(e,t){let n=gs(e,t);return typeof n==="string"?n:void 0}function Kb(e,t,n){if(t===void 0)return ps(e,n);return wc(e,t,n),t}function C3(e){return Zb(e??Yb(),"settings.json")}function sf(e){return D3(ps("theme",e))??"light"}function Dne(e,t){let n=D3(e);if(!n)return sf(t);return Kb("theme",n,t),n}function ov(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0.85&&e<=1.3?e:void 0}var _c=(e)=>typeof e==="boolean"?e:void 0,zb=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0,y3=(e)=>typeof e==="string"&&e.trim()!==""?e:void 0;function b3(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 A3=[{key:"httpProxy",validate:y3},{key:"httpIdleTimeoutMs",validate:zb},{key:"websocketConnectTimeoutMs",validate:zb},{key:"enableAnalytics",validate:_c},{key:"enableInstallTelemetry",validate:_c},{key:"trackingId",validate:y3},{key:"branchSummary",validate:(e)=>b3(e,{reserveTokens:zb,skipPrompt:_c})},{key:"images",validate:(e)=>b3(e,{autoResize:_c,blockImages:_c})}];function sv(e){let t={};for(let{key:n,validate:r}of A3){let i=r(gs(n,e));if(i!==void 0)t[n]=i}return Object.keys(t).length>0?t:void 0}function Ene(e,t){for(let{key:n,validate:r}of A3){if(!(n in e))continue;let i=r(e[n]);if(i===void 0)continue;wc(n,i,t)}return sv(t)}var Tne=5000,Sne=60,U3=60000,uf=new Map,cf=new Set,av=new Map,Dc=new Map;function Cne(){let e=ti().preferences.gitAutoFetchIntervalSec;return typeof e==="number"&&Number.isFinite(e)?e:Sne}function Ane(e){let t=av.get(e);if(t)return t;let n=Gb();av.set(e,n.promise);let r;return(async()=>{try{let i=await Promise.race([(async()=>{let o=await d3(e);if(!o.ok)return{ok:!1,error:o.error};let s=await Nb(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 ${U3/1000}s`)),U3),r.unref?.()})]);n.resolve(i)}catch(i){n.resolve({ok:!1,error:i instanceof Error?i.message:String(i)})}finally{if(r)clearTimeout(r);av.delete(e)}})(),n.promise}async function k3(e){let t=new Map;for(let n of e){let r=null;try{r=await Mn(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 R3(e,t){await Promise.all(Array.from(e,async([n,r])=>{let i=await Ane(n);if(!i.ok){console.warn(`[git-autofetch] fetch failed for ${n}: ${i.error}`);return}for(let o of r)uf.set(on(o),i.snapshot);Dc.set(n,t)}))}async function Une(e=Date.now()){let t=Z2();for(let s of[...cf])if(!t.includes(s))cf.delete(s);let n=new Set(t);for(let s of[...uf.keys()])if(!n.has(s))uf.delete(s);if(t.length===0){Dc.clear();return}let r=Cne(),i=await k3(t);for(let s of[...Dc.keys()])if(!i.has(s))Dc.delete(s);if(r<=0){let s=t.filter((c)=>!cf.has(c));if(s.length===0)return;let a=await k3(s);await R3(a,e);for(let c of s)cf.add(c);return}let o=new Map;for(let[s,a]of i){let c=Dc.get(s)??0;if(e-c<r*1000)continue;o.set(s,a)}if(o.size===0)return;await R3(o,e)}function F3(e){return uf.get(on(e))??null}function O3(){setInterval(()=>{Une()},Tne).unref()}async function kne(e){try{let t=new URL(e.url).searchParams.get("cwd")??void 0,n=await Nn(t);if(!n.ok)return w.json({error:n.error},{status:n.status});let r=F3(n.cwd);if(!r)return w.json({ok:!0,cached:!1});return w.json({ok:!0,cached:!0,...r})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var uv={};Q(uv,{POST:()=>Fne});import Rne from"node:fs";async function Fne(e){try{let t=await e.json(),n=t.cwd?.trim()??"",r=t.filePath?.trim()??"",i=t.action==="unstage"?"unstage":"stage";if(!n||!n.startsWith("/")&&!at(n))return w.json({error:"cwd must be an absolute path"},{status:400});if(!r||!r.startsWith("/")&&!at(r))return w.json({error:"filePath must be an absolute path"},{status:400});let o=await de();if(!Xe(n,o))return w.json({error:"Access denied"},{status:403});let s;try{s=Rne.statSync(n)}catch{return w.json({error:"Directory not found"},{status:404})}if(!s.isDirectory())return w.json({error:"Not a directory"},{status:400});if(!be(n,o))return w.json({error:"Access denied"},{status:403});let a=i==="unstage"?await a3(n,r):await s3(n,r);if(!a.ok)return w.json({error:a.error},{status:400});return w.json({ok:!0})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var lv={};Q(lv,{GET:()=>Pne});import One from"node:fs";async function Pne(e){try{let t=e.nextUrl.searchParams.get("cwd")?.trim()??"";if(!t||!t.startsWith("/")&&!at(t))return w.json({error:"cwd must be an absolute path"},{status:400});let n=await de();if(!Xe(t,n))return w.json({error:"Access denied"},{status:403});let r;try{r=One.statSync(t)}catch{return w.json({error:"Directory not found"},{status:404})}if(!r.isDirectory())return w.json({error:"Not a directory"},{status:400});if(!be(t,n))return w.json({error:"Access denied"},{status:403});return w.json(await o3(t))}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var dv={};Q(dv,{GET:()=>Mne});import{homedir as Ine}from"node:os";async function Mne(){return w.json({home:Ine()})}var hv={};Q(hv,{GET:()=>Hne,dynamic:()=>qne,loadModels:()=>ni});import{stat as Nne}from"node:fs/promises";import{resolve as Bne}from"node:path";import{getSupportedThinkingLevels as Lne}from"@earendil-works/pi-ai";import{createAgentSessionServices as Wne,getAgentDir as I3}from"@earendil-works/pi-coding-agent";var lf=null;function P3(e){if(lf)return;let t=(async()=>{for(let n of e)await Promise.allSettled([n()])})();lf=t,t.then(()=>{lf=null})}function Bn(){return lf??Promise.resolve()}import{resolveModelScopeWithDiagnostics as jne}from"@earendil-works/pi-coding-agent";var qne="force-dynamic",fv=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function $ne(e,t){return fv.compare(e.name||e.id,t.name||t.id)||fv.compare(e.provider,t.provider)||fv.compare(e.id,t.id)}async function ni(e){let t=new Map,n=[],r=null,i={},o={},s={},a=I3(),c=oo(e,a),u=await Wne({cwd:e,agentDir:a,...c?{resourceLoaderReloadOptions:c}:{}}),d=u.modelRuntime.getError(),f=u.settingsManager,h=f.getEnabledModels(),p=await wu(u.modelRuntime,h),{visible:g,thinkingLevelPins:b,warnings:v}=p,m=await ao(),_=await so(),y=new Set,x=[],D=[],C=(h??[]).map((S)=>S.trim()).filter(Boolean);if(m.length>0){let S=new Map;for(let B of await u.modelRuntime.getAvailable())S.set(`${B.provider}/${B.id}`,B);for(let B of m){if(_.has(B.toLowerCase()))continue;let G=(await gi(B)).map((T)=>Kh(B,T)).filter((T)=>T!==null);if(G.length===0)continue;y.add(B);for(let T of G)D.push(S.get(`${B}/${T.id}`)??T);for(let T of await Gne(B,G,C))x.push(S.get(`${B}/${T.id}`)??T)}}let E=[...g.filter((S)=>!y.has(S.provider)),...x],U=f.getDefaultProvider(),A=f.getDefaultModel(),N=Du(p,{...U&&A?{defaultModel:{provider:U,modelId:A}}:{}});if(N.model&&E.some((S)=>S.provider===N.model.provider&&S.id===N.model.id))r={provider:N.model.provider,modelId:N.model.id};n=E.map((S)=>({id:S.id,name:S.name,provider:S.provider,reasoning:S.reasoning,input:[...S.input],isDefault:r?.provider===S.provider&&r?.modelId===S.id})).sort($ne);for(let S of E){let B=`${S.provider}/${S.id}`;if(t.set(B,S.name),i[B]=Lne(S),S.thinkingLevelMap)o[B]=S.thinkingLevelMap}let O=[...u.modelRuntime.getModels().filter((S)=>!y.has(S.provider)),...D];for(let S of O){let B=`${S.provider}/${S.id}`;s[B]={id:S.id,name:S.name,api:S.api,provider:S.provider,baseUrl:S.baseUrl,reasoning:S.reasoning,...S.thinkingLevelMap?{thinkingLevelMap:S.thinkingLevelMap}:{},input:[...S.input],cost:{input:S.cost.input,output:S.cost.output,cacheRead:S.cost.cacheRead,cacheWrite:S.cost.cacheWrite},contextWindow:S.contextWindow,maxTokens:S.maxTokens,...S.samplingParams?{samplingParams:S.samplingParams}:{},...S.headers?{headers:S.headers}:{},...S.compat?{compat:S.compat}:{}}}return I2({models:Object.fromEntries(t),modelList:n,defaultModel:r,thinkingLevels:i,thinkingLevelMaps:o,thinkingLevelPins:b,definitions:s,...v.length>0?{modelScopeWarnings:v}:{}},d)}async function Hne(e){await Bn();let t=new URL(e.url),n=t.searchParams.has("cwd"),r=n?t.searchParams.get("cwd"):I3(),i=Bne(r),o;try{o=await Nne(i)}catch{return Response.json({error:`Directory does not exist: ${i}`},{status:400})}if(!o.isDirectory())return Response.json({error:`Not a directory: ${i}`},{status:400});if(n){let s=await de();if(!be(i,s))return Response.json({error:"Access denied"},{status:403})}try{let a={...await Tr(i,()=>ni(i))};return delete a.definitions,Response.json(a)}catch(s){return console.error("[api/models] failed to build model list:",s),Response.json({error:s instanceof Error?s.message:String(s)},{status:500})}}async function Gne(e,t,n){if(n.length===0)return t;let r=[],i=!1;for(let u of n){let d=u.indexOf("/");if(d===-1){i=!0,r.push(u);continue}let f=u.slice(0,d).trim().toLowerCase();if(!f||/[*?[]/.test(f)){i=!0,r.push(u);continue}r.push(u)}let o=e.toLowerCase(),s=i?r:r.filter((u)=>u.slice(0,u.indexOf("/")).trim().toLowerCase()===o);if(!i&&s.length===0)return t;let a={getAvailable:async()=>t},{scopedModels:c}=await jne(s,a);return c.map((u)=>u.model)}import pv from"node:fs";var zne=new Set(["select","confirm","input","editor"]),Vne=new Set(["agent_settled","prompt_done","prompt_error","extension_error"]),Xne=new Set(["turn_start","turn_end"]);function Kne(e){if(Xne.has(e.type))return null;if(e.type==="message_update"){let n=e.assistantMessageEvent;if(!n||typeof n.type!=="string")return e;let r={type:n.type};if(typeof n.delta==="string")r.delta=n.delta;if(typeof n.contentIndex==="number")r.contentIndex=n.contentIndex;if(n.type==="toolcall_end"&&n.toolCall&&typeof n.toolCall==="object")r.toolCall=n.toolCall;return{type:"message_update",assistantMessageEvent:r}}if(e.type==="message_start"||e.type==="message_end")return e;if(e.type==="agent_end")return{type:"agent_end"};return e}var lr=new Map,ff=null,hf=null;function Ot(e,t,n){try{e.ws.send(JSON.stringify({ch:t,data:n}))}catch{}}function M3(e,t){let n=lr.get(e);if(!n)return;for(let r of n){if(e==="global"){let i=t,o=i.type==="extension_ui_request"&&zne.has(i.method),s=typeof i.type==="string"&&Vne.has(i.type);if(o)jt("ui-chain",`3 ws broadcast ${String(i.method)}`,`id=${String(i.id).slice(0,8)} sid=${String(i.sessionId).slice(0,8)} conns=${n.size}`);if(!s){let a=i.sessionId;if(a&&!r.seenSessions.has(a))continue}Ot(r,e,t);continue}if(e==="running"){Ot(r,e,{type:"running",...B3(t,r.seenSessions)});continue}Ot(r,e,t)}}function Zne(e){if(e==="global"&&!ff)ff=n1((t,n)=>{let r=Kne(n);if(r)M3("global",{sessionId:t,...r})});if(e==="running"&&!hf)hf=e1((t)=>M3("running",t))}function B3(e,t){let n=e.runningSessionIds.filter((s)=>t.has(s)),r={},i={},o={};for(let s of n){if(e.phases[s]!==void 0)r[s]=e.phases[s];if(e.phaseSince[s]!==void 0)i[s]=e.phaseSince[s];if(e.busySince[s]!==void 0)o[s]=e.busySince[s]}return{runningSessionIds:n,phases:r,phaseSince:i,busySince:o}}function Yne(e){if(e==="global"&&lr.get("global")?.size===0)ff?.(),ff=null;if(e==="running"&&lr.get("running")?.size===0)hf?.(),hf=null}function N3(e,t){let n=lr.get(t);if(!n)n=new Set,lr.set(t,n);if(n.add(e),!e.channels.has(t))e.channels.set(t,{kind:"passive"});Zne(t)}function df(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(lr.get(t)?.delete(e),n.kind==="passive")Yne(t);if(n.kind==="agent"){let r=lr.get(t);if(!r||r.size===0){let i=t.slice(6);bt(i)?.cancelPendingUiResponses()}}}async function Jne(e,t){let n=`agent:${t}`;if(e.seenSessions.add(t),e.channels.has(n))return;let r=bt(t);if(!r?.isAlive()){let o=await We(t);if(!o){Ot(e,n,{type:"not_found",sessionId:t});return}try{({session:r}=await hi(t,o,void 0))}catch(s){Ot(e,n,{type:"start_failed",sessionId:t,message:String(s)});return}}e.channels.set(n,{kind:"agent",unsubscribe:()=>{}}),lr.get(n)?.add(e),Ot(e,n,{type:"connected",sessionId:t});let i=r.getPendingUiRequests();for(let o of i)Ot(e,"global",{...o,sessionId:t})}function Qne(e,t){let n=t,r=`watch:${n}`,i;try{i=pv.statSync(n)}catch{Ot(e,r,{event:"error",message:"Not found"});return}if(!i.isFile()){Ot(e,r,{event:"error",message:"Not a file"});return}let o,s=i.mtimeMs,a=i.size;try{o=pv.watch(n,()=>{try{let c=pv.statSync(n);if(c.mtimeMs===s&&c.size===a)return;s=c.mtimeMs,a=c.size,Ot(e,r,{event:"change",mtime:c.mtime.toISOString(),size:c.size})}catch{Ot(e,r,{event:"change",mtime:new Date().toISOString(),size:0})}})}catch{Ot(e,r,{event:"error",message:"Failed to watch file"});return}o.on("error",()=>{df(e,r)}),e.channels.set(r,{kind:"watch",watcher:o}),lr.get(r)?.add(e),Ot(e,r,{event:"connected",filePath:n})}async function ere(e,t){switch(t.ch){case"global":{N3(e,"global");return}case"running":{N3(e,"running"),Ot(e,"running",{type:"running",...B3(qs(),e.seenSessions)});return}case"agent":{let n=typeof t.sessionId==="string"?t.sessionId:"";if(n)await Jne(e,n);return}case"watch":{if(typeof t.filePath==="string"&&t.filePath)Qne(e,t.filePath);return}default:return}}function tre(e){if(!Tt(e))return!1;let t=process.env.PI_WEB_PASSWORD;if(Ls(t)&&!au(e.headers.get("authorization"),t))return!1;return!0}var gv=null;function mv(e){gv=e((t)=>{if(!tre(t.req.raw))return{onOpen:(i,o)=>o.close(1008,"untrusted")};let n={ws:null,channels:new Map,seenSessions:new Set},r=null;return{onOpen:(i,o)=>{n.ws=o,o.send(JSON.stringify({type:"connected"})),r=setInterval(()=>{try{o.send(JSON.stringify({type:"ping"}))}catch{}},30000)},onMessage:async(i)=>{if(typeof i.data!=="string")return;let o;try{o=JSON.parse(i.data)}catch{return}if(o.type==="sub")await ere(n,o);else if(o.type==="unsub"&&typeof o.ch==="string")df(n,o.ch);else if(o.type==="unseen"&&typeof o.sessionId==="string"){let s=o.sessionId;n.seenSessions.delete(s);let a=`agent:${s}`;if(n.channels.has(a))df(n,a)}},onClose:()=>{if(r)clearInterval(r);for(let i of[...n.channels.keys()])df(n,i)}}})}function L3(e){e.get("/api/ws",(t,n)=>gv?gv(t,n):n())}var bv={};Q(bv,{GET:()=>xre,dynamic:()=>pre});var nre={anthropic:["api.anthropic.com"],google:["generativelanguage.googleapis.com"],openai:["api.openai.com"],openrouter:["openrouter.ai"]},rre=new Set(["text","image","audio","video","pdf"]);function Hi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function pf(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function gf(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0?e:void 0}function W3(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ire(e){if(!Hi(e))return{};return{input:gf(e.input),output:gf(e.output),cacheRead:gf(e.cache_read),cacheWrite:gf(e.cache_write)}}function ore(e){if(!Hi(e)||!Array.isArray(e.input))return;let t=Array.from(new Set(e.input.filter((n)=>typeof n==="string").map((n)=>n.trim().toLocaleLowerCase()).filter((n)=>rre.has(n))));return t.length?t:void 0}function mf(e){return e.trim().toLocaleLowerCase().replace(/[^a-z0-9]/g,"")}function j3(e){return e.trim().toLocaleLowerCase().replace(/^models\//,"")}function q3(e){if(!e)return;try{return new URL(e).hostname.toLocaleLowerCase().replace(/\.$/,"")}catch{return}}function sre(e,t){return e===t||e.endsWith(`.${t}`)}function are(e,t){let n=mf(t);if(!n)return!1;return mf(e.providerId)===n||mf(e.providerName)===n}function cre(e,t){let n=q3(t);if(!n)return!1;let r=nre[mf(e.providerId)]??[],i=q3(e.providerBaseUrl);return[...r,...i?[i]:[]].some((o)=>sre(n,o))}function ure(e,t){let n=j3(t);if(!n)return!1;let r=j3(e.id),i=`${e.providerId.toLocaleLowerCase()}/${r}`;return r===n||i===n}function yv(e){return e.cost.input!==void 0&&e.cost.output!==void 0}function Ec(e,t,n){if(e.length===0||t<=0)return;let r=new Map;for(let s of e){let a=n(s),c=r.get(a);if(c)c.count+=1;else r.set(a,{value:s,count:1})}let i=[...r.values()].sort((s,a)=>a.count-s.count),o=i[0];if(!o||o.count/t<0.6)return;if(i[1]?.count===o.count)return;return o.value}function $3(e){if(e.length===0)return;let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=[...t.entries()].sort((r,i)=>i[1]-r[1]);if(!n[0]||n[1]?.[1]===n[0][1])return;return n[0][0]}function lre(e){return{name:e.name,reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens}}function dre(e){let t=e.length;return{name:Ec(e.map((n)=>n.name),t,(n)=>n.toLocaleLowerCase()),reasoning:Ec(e.flatMap((n)=>n.reasoning===void 0?[]:[n.reasoning]),t,String),input:Ec(e.flatMap((n)=>n.input?[n.input]:[]),t,(n)=>[...n].sort().join(",")),contextWindow:Ec(e.flatMap((n)=>n.contextWindow===void 0?[]:[n.contextWindow]),t,String),maxTokens:Ec(e.flatMap((n)=>n.maxTokens===void 0?[]:[n.maxTokens]),t,String)}}function H3(e,t){return{status:"reliable",method:t,cost:e.cost,providerId:e.providerId,providerName:e.providerName,support:1,total:1}}function fre(e){let t=e.filter(yv);if(t.length===0)return{status:"unreliable",reason:"no-valid-price",support:0,total:0};if(t.length===1)return{status:"unreliable",reason:"insufficient-support",support:1,total:1};let n=new Map;for(let a of t){let c=JSON.stringify([a.cost.input,a.cost.output]),u=n.get(c);if(u)u.push(a);else n.set(c,[a])}let r=[...n.values()].sort((a,c)=>c.length-a.length),i=r[0];if(!i)return{status:"unreliable",reason:"no-valid-price",support:0,total:t.length};if(r[1]?.length===i.length||i.length/t.length<0.6)return{status:"unreliable",reason:"conflict",support:i.length,total:t.length};let o=$3(i.flatMap((a)=>a.cost.cacheRead===void 0?[]:[a.cost.cacheRead])),s=$3(i.flatMap((a)=>a.cost.cacheWrite===void 0?[]:[a.cost.cacheWrite]));return{status:"reliable",method:"consensus",cost:{input:i[0].cost.input,output:i[0].cost.output,cacheRead:o,cacheWrite:s},support:i.length,total:t.length}}function G3(e){if(!Hi(e))return[];let t=[];for(let[n,r]of Object.entries(e)){if(!Hi(r)||!Hi(r.models))continue;let i=pf(r.name)??n,o=pf(r.api);for(let[s,a]of Object.entries(r.models)){if(!Hi(a))continue;let c=pf(a.id)??s;if(!c)continue;let u=pf(a.name)??c,d={key:`${n}/${c}`,providerId:n,providerName:i,id:c,name:u,cost:ire(a.cost)};if(o)d.providerBaseUrl=o;if(typeof a.reasoning==="boolean")d.reasoning=a.reasoning;let f=ore(a.modalities);if(f)d.input=f;if(Hi(a.limit)){let h=W3(a.limit.context),p=W3(a.limit.output);if(h!==void 0)d.contextWindow=h;if(p!==void 0)d.maxTokens=p}t.push(d)}}return t}function z3(e,t,n="",r=""){let i=e.filter((p)=>ure(p,t));if(i.length===0)return{exactMatches:0,metadataMethod:"none",preset:{},price:{status:"unreliable",reason:"no-exact-match",support:0,total:0}};let o=i.filter((p)=>are(p,n)),s=i.filter((p)=>cre(p,r)),a=o[0]??s[0],c=o.length?"provider":s.length?"base-url":"consensus",u=a?lre(a):dre(i),d=o.find(yv),f=s.find(yv),h=d?H3(d,"provider"):f?H3(f,"base-url"):fre(i);if(h.status==="reliable")u.cost=h.cost;return{exactMatches:i.length,metadataMethod:c,matchedProviderId:a?.providerId,matchedProviderName:a?.providerName,preset:u,price:h}}function hre(e,t,n){let r=e.id.toLocaleLowerCase(),i=e.name.toLocaleLowerCase(),o=e.providerId.toLocaleLowerCase(),s=e.providerName.toLocaleLowerCase(),a=`${o}/${r}`,c=20;if(!t)c=10;else if(r===t||a===t)c=0;else if(i===t)c=1;else if(r.startsWith(t)||i.startsWith(t))c=2;else if(a.startsWith(t)||o===t||s===t)c=3;else if(r.includes(t)||i.includes(t))c=4;else if(a.includes(t)||s.includes(t))c=5;if(c<20&&n&&(o===n||s===n))c-=0.5;return c}function V3(e,t,n="",r=50){let i=t.trim().toLocaleLowerCase(),o=n.trim().toLocaleLowerCase(),s=Math.max(1,Math.min(100,Math.floor(r)||50));return e.map((a)=>({entry:a,rank:hre(a,i,o)})).filter(({rank:a})=>!i||a<20).sort((a,c)=>a.rank-c.rank||a.entry.providerName.localeCompare(c.entry.providerName,void 0,{sensitivity:"base"})||a.entry.name.localeCompare(c.entry.name,void 0,{numeric:!0,sensitivity:"base"})||a.entry.id.localeCompare(c.entry.id,void 0,{numeric:!0,sensitivity:"base"})).slice(0,s).map(({entry:a})=>a)}var pre="force-dynamic",X3="https://models.dev/api.json",gre=3600000,mre=15000;function yre(){return globalThis.__piModelsDevCatalogCache??={entries:[],expiresAt:0}}async function bre(){let e=await fetch(X3,{cache:"no-store",headers:{Accept:"application/json"},signal:AbortSignal.timeout(mre)});if(!e.ok)throw Error(`models.dev returned HTTP ${e.status}`);let t=G3(await e.json());if(t.length===0)throw Error("models.dev returned an empty catalog");return t}async function vre(){let e=yre();if(e.entries.length>0&&e.expiresAt>Date.now())return e.entries;if(!e.inFlight)e.inFlight=bre().then((t)=>(e.entries=t,e.expiresAt=Date.now()+gre,t)).finally(()=>{e.inFlight=void 0});try{return await e.inFlight}catch(t){if(e.entries.length>0)return e.entries;throw t}}async function xre(e){let{searchParams:t}=new URL(e.url),n=(t.get("q")??"").slice(0,120),r=(t.get("provider")??"").slice(0,120),i=(t.get("baseUrl")??"").slice(0,500),o=Number.parseInt(t.get("limit")??"50",10),s=Number.isFinite(o)?o:50;try{let a=await vre(),c=V3(a,n,r,s),u=z3(a,n,r,i);return w.json({models:c,recommendation:u,source:X3})}catch(a){return w.json({error:a instanceof Error?a.message:String(a)},{status:502})}}var vv={};Q(vv,{POST:()=>Rre,dynamic:()=>Cre});import{mkdtempSync as _re,rmSync as wre,writeFileSync as Dre}from"node:fs";import{tmpdir as Ere}from"node:os";import{join as K3}from"node:path";import{ModelRuntime as Tre}from"@earendil-works/pi-coding-agent";function Sre(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Z3(e){if(!Sre(e))return{};return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]==="string"))}async function Y3(e,t){let n;try{n=_re(K3(Ere(),"pi-web-model-discovery-"));let r=K3(n,"models.json"),i="__pi_web_model_discovery__";Dre(r,JSON.stringify({providers:{[e]:{...t,models:[{id:i}]}}},null,2),"utf8");let o=await Tre.create({modelsPath:r}),s=o.getError();if(s)throw Error(s);let a=o.getModel(e,i);if(!a)throw Error(`Unable to load provider "${e}"`);let c=await o.getAuth(a);if(c)return{apiKey:c.auth.apiKey,headers:Z3(c.auth.headers)};return{headers:Z3(o.getCompatibilityRequestConfig(a).headers)}}finally{if(n)wre(n,{recursive:!0,force:!0})}}var Cre="force-dynamic",Are=20000;function Ure(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Tc(e,t){return e.has(t)}function kre(e,t,n){let r=new Headers(n);if(!Tc(r,"accept"))r.set("Accept","application/json");if(!t)return r;if(e==="anthropic-messages"){if(!Tc(r,"x-api-key"))r.set("x-api-key",t);if(!Tc(r,"anthropic-version"))r.set("anthropic-version","2023-06-01")}else if(e==="google-generative-ai"){if(!Tc(r,"x-goog-api-key"))r.set("x-goog-api-key",t)}else if(!Tc(r,"authorization"))r.set("Authorization",`Bearer ${t}`);return r}async function Rre(e){try{let t=await e.json(),n=typeof t.providerName==="string"?t.providerName.trim():"";if(!n)return w.json({error:"providerName is required"},{status:400});if(!Ure(t.provider))return w.json({error:"provider is required"},{status:400});let r=typeof t.provider.baseUrl==="string"?t.provider.baseUrl.trim():"";if(!r)return w.json({error:"Base URL is required"},{status:400});let i=typeof t.provider.api==="string"&&t.provider.api?t.provider.api:"openai-completions",o;try{o=$s(r,i)}catch{return w.json({error:"Base URL is invalid"},{status:400})}let s=await gi(n);if(s.length>0){let h=s.map((p)=>Ar(p)).filter((p)=>p!==null);if(h.length>0)return w.json({models:h})}let a=await Y3(n,t.provider);if(typeof t.provider.apiKey==="string"&&t.provider.apiKey.trim()&&!a.apiKey)return w.json({error:`No API key found for "${n}"`},{status:400});let c=await fetch(o,{cache:"no-store",headers:kre(i,a.apiKey,a.headers),signal:AbortSignal.timeout(Are)}),u=await c.text();if(!c.ok)return w.json({error:u.slice(0,500)||`Upstream returned HTTP ${c.status}`,status:c.status},{status:502});let d;try{d=JSON.parse(u)}catch{return w.json({error:"Upstream model list was not valid JSON"},{status:502})}let f=Xh(d);if(f.length===0)return w.json({error:"No models found in the upstream response"},{status:502});return await Au(n,Ur(d)),w.json({models:f,endpoint:o.toString()})}catch(t){let n=t instanceof Error?t.message:String(t),r=t instanceof DOMException&&t.name==="TimeoutError"?504:500;return w.json({error:n},{status:r})}}var xv={};Q(xv,{GET:()=>Ore,dynamic:()=>Fre});import{getAgentDir as J3}from"@earendil-works/pi-coding-agent";var Fre="force-dynamic";async function Ore(e){await Bn();let t=new URL(e.url),n=t.searchParams.get("provider")?.trim()??"",r=t.searchParams.get("model")?.trim()??"";if(!n||!r)return Response.json({error:"provider and model are required"},{status:400});try{let o=(await Tr(J3(),()=>ni(J3()))).definitions?.[`${n}/${r}`];if(!o)return Response.json({error:`Model not found: ${n}/${r}`},{status:404});return Response.json({model:o})}catch(i){return console.error("[api/models-config/effective] failed:",i),Response.json({error:i instanceof Error?i.message:String(i)},{status:500})}}var _v={};Q(_v,{GET:()=>Ire,dynamic:()=>Pre});import{getAgentDir as Q3}from"@earendil-works/pi-coding-agent";var Pre="force-dynamic";async function Ire(e){await Bn();let t=new URL(e.url),n=t.searchParams.get("provider")?.trim()??"",r=t.searchParams.get("model")?.trim()??"";if(!n||!r)return Response.json({error:"provider and model are required"},{status:400});try{let o=(await Tr(Q3(),()=>ni(Q3()))).definitions?.[`${n}/${r}`];if(!o)return Response.json({error:`Model not found: ${n}/${r}`},{status:404});let a=(await gi(n)).find((u)=>Ar(u)?.id===r),c=a?h1(a,o):{};return Response.json({suggestion:c})}catch(i){return console.error("[api/models-config/override-suggestion] failed:",i),Response.json({error:i instanceof Error?i.message:String(i)},{status:500})}}var Dv={};Q(Dv,{POST:()=>Bre,dynamic:()=>Mre});var Mre="force-dynamic",Nre=15000;function wv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function Bre(e){if(!Tt(e))return w.json({ok:!1,error:"Untrusted API request"},{status:403});if(!Dr(e))return w.json({ok:!1,error:"Content-Type must be application/json"},{status:415});try{let t=await e.json(),n=wv(t.provider)?t.provider:{},r=typeof n.baseUrl==="string"?n.baseUrl.trim():"";if(!r)return w.json({ok:!1,error:"baseUrl is required"},{status:400});let i=typeof n.apiKey==="string"?n.apiKey.trim():"",o=typeof n.api==="string"?n.api:"",s={Accept:"application/json"};if(o==="anthropic-messages"){if(i)s["x-api-key"]=i;s["anthropic-version"]="2023-06-01"}else if(o==="google-generative-ai"){if(i)s["x-goog-api-key"]=i}else if(i)s.Authorization=`Bearer ${i}`;let a=`${r.replace(/\/+$/,"")}/models`,c=await fetch(a,{headers:s,cache:"no-store",signal:AbortSignal.timeout(Nre)});if(!c.ok)return w.json({ok:!1,error:`HTTP ${c.status}`},{status:502});let u=await c.json().catch(()=>{return}),d=Array.isArray(u)?u:wv(u)&&Array.isArray(u.data)?u.data:wv(u)&&Array.isArray(u.models)?u.models:[];return w.json({ok:!0,models:d})}catch(t){return w.json({ok:!1,error:t instanceof Error?t.message:String(t)})}}co();Zh();var Av={};Q(Av,{GET:()=>zre,PUT:()=>Vre,cleanupStaleEnabledModels:()=>Cv,dynamic:()=>qre,extractLiteralApiKeys:()=>a8});import{existsSync as vf,mkdirSync as n8,readFileSync as r8}from"node:fs";import{rename as Wre,rm as e8}from"node:fs/promises";import{dirname as i8,join as bf}from"node:path";import{getAgentDir as jre}from"@earendil-works/pi-coding-agent";var Lre=new Set(["off","minimal","low","medium","high","xhigh","max"]),yf=new Set(["amazon-bedrock","ant-ling","anthropic","azure-openai-responses","baseten","cerebras","cloudflare-ai-gateway","cloudflare-workers-ai","deepseek","fireworks","github-copilot","google","google-vertex","groq","huggingface","kimi-coding","minimax","minimax-cn","mistral","moonshotai","moonshotai-cn","nvidia","openai","openai-codex","opencode","opencode-go","openrouter","qwen-token-plan","qwen-token-plan-cn","qwen-token-plan-individual","radius","together","vercel-ai-gateway","xai","xiaomi","xiaomi-token-plan-ams","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","zai","zai-coding-cn"]);function Ev(e,t,n){let r=Object.keys(n?.providers??{}),i=t?.providers??{},o=new Set([...r,...Object.keys(i)]);return e.filter((s)=>{if(/[?*[\]]/.test(s)||!s.includes("/"))return!0;let a=s.indexOf("/"),c=s.slice(0,a);if(!o.has(c))return yf.has(c);let u=s.slice(a+1),d=u.lastIndexOf(":");if(d!==-1){let h=u.slice(d+1);if(Lre.has(h))u=u.slice(0,d);else return!0}let f=i[c];if(!f)return!1;if(yf.has(c))return!0;return(f.models??[]).some((h)=>h.id===u)})}var qre="force-dynamic";function o8(e){return sn("models.json",vt("models.json",e))}function Sv(e){let t=o8(e);if(!vf(t))return{providers:{}};try{return JSON.parse(r8(t,"utf8"))}catch{return{providers:{}}}}function t8(e,t){let n=o8(t),r=i8(n);if(!vf(r))n8(r,{recursive:!0});Gs(n,JSON.stringify(e,null,2))}var $re=/\$[A-Za-z_][A-Za-z0-9_]*|\$\{[A-Za-z_][A-Za-z0-9_]*\}/;function s8(e){return!e.startsWith("!")&&!$re.test(e)}async function a8(e,t){if(!e||typeof e!=="object")return;for(let[n,r]of Object.entries(e)){if(!r||typeof r!=="object"||Array.isArray(r))continue;let i=r.apiKey;if(typeof i!=="string"||i.length===0)continue;if(!s8(i))continue;await ju(n,{type:"api_key",key:i},t),delete r.apiKey}}function Hre(e){if(!e||typeof e!=="object")return;let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==="object"&&!Array.isArray(r)){let i=r;if(typeof i.apiKey==="string"&&s8(i.apiKey))t[n]={...i},delete t[n].apiKey;else t[n]=r}else t[n]=r;return t}function c8(e){return sn("settings.json",vt("settings.json",e))}function Sc(e){let t=c8(e);if(!vf(t))return{};try{return JSON.parse(r8(t,"utf8"))}catch{return{}}}function Tv(e,t){let n=c8(t),r=i8(n);if(!vf(r))n8(r,{recursive:!0});Gs(n,JSON.stringify(e,null,2))}function Gre(e){let t=Sc(e),n=t.defaultProvider,r=t.defaultModel;if(typeof n==="string"&&typeof r==="string"&&n&&r)return{provider:n,modelId:r};return null}function u8(e){let t=Sc(e);return Array.isArray(t.enabledModels)?t.enabledModels.filter((n)=>typeof n==="string"):[]}function Cv(e){let t=u8(e);if(t.length===0)return;let n=Sv(e),r=Ev(t,n,n);if(r.length===t.length)return;let i=Sc(e);i.enabledModels=r,Tv(i,e),ke(),console.log(`[models-config] pruned ${t.length-r.length} stale enabledModels entr${t.length-r.length===1?"y":"ies"}: ${t.filter((o)=>!r.includes(o)).join(", ")}`)}async function zre(e){let t=ae(e),n=Sv(t);return w.json({providers:n.providers??{},defaultModel:Gre(t),enabledModels:u8(t)})}async function Vre(e){try{let t=await e.json(),{models:n,defaultModel:r,enabledModels:i,renames:o}=t,a={...n??t};delete a.enabledModels,delete a.defaultModel,delete a.defaultProvider;let c=ae(e),u=sn("auth.json",vt("auth.json",c)),d=Sv(ae(e));t8({...a,providers:Hre(a.providers)},ae(e));try{await a8(a.providers,u)}catch(m){throw t8(d,ae(e)),m}if(r&&typeof r.provider==="string"&&typeof r.modelId==="string"){let m=Sc(ae(e));m.defaultProvider=r.provider,m.defaultModel=r.modelId,Tv(m,ae(e))}if(Array.isArray(i)){let m=Sc(ae(e));m.enabledModels=Ev(i.filter((_)=>typeof _==="string"),a,d),Tv(m,ae(e))}let f=d.providers??{},h=a.providers??{},p=new Set(Object.keys(h)),g=(Array.isArray(o)?o:[]).filter((m)=>!!m&&typeof m.oldId==="string"&&typeof m.newId==="string"&&m.oldId!==m.newId&&!yf.has(m.newId)&&!Object.hasOwn(f,m.newId)&&Object.hasOwn(f,m.oldId)&&qu(f[m.oldId])&&Object.hasOwn(h,m.newId));for(let m of g)await K1(m.oldId,m.newId,u);let b=new Set(g.map((m)=>m.oldId));await Z1(f,p,u,b);let v=bf(jre(),"pi-web","provider");for(let{oldId:m,newId:_}of g){if(!kr(m)||!kr(_))continue;let y=bf(v,m),x=bf(v,_);try{await Wre(y,x)}catch{await e8(y,{recursive:!0,force:!0}).catch(()=>{})}}for(let m of Object.keys(f)){if(p.has(m)||b.has(m)||!kr(m))continue;await e8(bf(v,m),{recursive:!0,force:!0}).catch(()=>{})}return ke(),w.json({success:!0})}catch(t){return w.json({error:String(t)},{status:500})}}var kv={};Q(kv,{GET:()=>iie,POST:()=>rie,dynamic:()=>Jre,getProviderModelsCaches:()=>f8});import{getAgentDir as Xre}from"@earendil-works/pi-coding-agent";import{ModelRuntime as Kre}from"@earendil-works/pi-coding-agent";import{readFile as Zre,readdir as Yre,stat as l8}from"node:fs/promises";import{join as d8}from"node:path";var Jre="force-dynamic",Uv=d8(Xre(),"pi-web","provider"),Qre=5000;async function f8(){try{if(!(await l8(Uv)).isDirectory())return{}}catch{return{}}let e=await Yre(Uv,{withFileTypes:!0}),t={};for(let n of e){if(!n.isDirectory())continue;let r=d8(Uv,n.name,"models.json");try{let i=JSON.parse(await Zre(r,"utf-8")),o=Ur(i),s=await l8(r);t[n.name]={modelCount:o.length,lastSyncedAt:s.mtimeMs}}catch{}}return t}function eie(e){return e.replace(/\$\{(\w+)\}/g,(t,n)=>process.env[n]??"").replace(/\$([A-Z_][A-Z0-9_]*)/g,(t,n)=>process.env[n]??"")}async function tie(e){let{configFilePath:t,resolveConfigFileDir:n}=await Promise.resolve().then(() => (co(),y1)),r=t("models.json",n("models.json")),{readFileSync:i,existsSync:o}=await import("node:fs");if(!o(r))return null;try{let c=JSON.parse(i(r,"utf-8")).providers?.[e];if(!c)return null;let u=typeof c.baseUrl==="string"?c.baseUrl:void 0,d;if(typeof c.apiKey==="string")d=eie(c.apiKey);return u?{baseUrl:u,apiKey:d}:null}catch{return null}}async function nie(e,t){let n=t.getProvider(e),r,i={},o=await t.getAvailable();if(n){r=typeof n.baseUrl==="string"&&n.baseUrl.trim()&&n.baseUrl||o.find((p)=>p.provider===e)?.baseUrl||void 0;try{let p=await t.getAuth(e);if(p?.auth?.apiKey)i={Authorization:`Bearer ${p.auth.apiKey}`}}catch{}}else{let p=await tie(e);if(!p)throw Error(`Provider "${e}" not found in built-in or models.json`);if(r=p.baseUrl,p.apiKey)i={Authorization:`Bearer ${p.apiKey}`}}if(!r||r.trim()==="")throw Error(`Provider "${e}" has no baseUrl configured`);let s=o.find((p)=>p.provider===e)?.api??"",a;try{a=$s(r,s)}catch{throw Error(`Invalid baseUrl for provider "${e}"`)}let c=await fetch(a,{headers:i,cache:"no-store",signal:AbortSignal.timeout(Qre)});if(!c.ok)throw Error(`Provider "${e}" returned HTTP ${c.status} from ${a}`);let u=await c.text();if(!u.trim())throw Error(`Provider "${e}" returned empty response`);let d=JSON.parse(u),{parseDiscoveredModels:f}=await Promise.resolve().then(() => u1),h=Ur(d);if(f(d).length===0)throw Error(`Provider "${e}" returned no parsable models`);return await Au(e,h),{count:h.length}}async function rie(e){try{let{providerName:t}=await e.json();if(typeof t!=="string"||t.trim()==="")return Response.json({error:"providerName is required"},{status:400});let n=t.trim();if(!kr(n))return Response.json({error:`Invalid providerName: ${JSON.stringify(t)}`},{status:400});let r=await Kre.create({allowModelNetwork:!0}),{count:i}=await nie(n,r);return ke(),Response.json({count:i})}catch(t){let n=t instanceof Error?t.message:String(t);return Response.json({error:n},{status:500})}}async function iie(){let e=await f8();return Response.json(e)}var Rv={};Q(Rv,{GET:()=>pie,PUT:()=>gie});import{mkdirSync as aie,readFileSync as cie,writeFileSync as uie}from"node:fs";import{dirname as lie,join as die}from"node:path";import{getAgentDir as fie}from"@earendil-works/pi-coding-agent";var oie=rf;function sie(e){return typeof e==="string"&&oie.includes(e)}function ms(e){if(!e||typeof e!=="object"||Array.isArray(e))return{};let t=e,n=(r)=>{let i=t[r];if(!i||typeof i!=="object"||Array.isArray(i))return;let o={};for(let[s,a]of Object.entries(i))if(sie(a))o[s]=a;return Object.keys(o).length>0?o:void 0};return{models:n("models"),providers:n("providers")}}var xf=new Map;function h8(e){return die(e??fie(),"pi-web","model-thinking.json")}function p8(e){let t=e??"",n=xf.get(t);if(n!==void 0&&n!==null)return n;try{let r=cie(h8(e),"utf8"),i=JSON.parse(r);return n=ms(i),xf.set(t,n),n}catch{return n={},xf.set(t,n),n}}function hie(e,t){try{let n=h8(t);aie(lie(n),{recursive:!0});let r=ms(e);uie(n,JSON.stringify(r,null,2)+`
351
+ ... (truncated for context limit ${b})`}let v=Wt("generate-commit"),m;if(f.reasoning){let x={...f.thinkingLevelMap??{}};for(let C of["off","minimal","low","medium","high"])if(!(C in x))x[C]=C;m=["off","minimal","low","medium","high","xhigh","max"].find((C)=>typeof x[C]==="string")??"low",f.thinkingLevelMap=x}console.log(`[generate-commit] start provider=${o} model=${s} maxTokens=${a} ctx=${b??"unknown"} diffLen=${c.length} promptLen=${g.length} reasoningHint=${m??"<omitted>"}`),v("start",`provider=${o} model=${s} maxTokens=${a} ctx=${b??"unknown"} diffLen=${c.length} promptLen=${g.length} reasoningHint=${m??"<omitted>"}`),v("diff-preview",g.slice(0,50).replace(/\n/g,"\\n"));let _=new AbortController,y=setTimeout(()=>_.abort(),p3);try{let x={apiKey:h.auth.apiKey,headers:h.auth.headers,maxTokens:a,timeoutMs:p3,maxRetries:0,cacheRetention:"none",signal:_.signal};if(m!==void 0&&m!=="off")x.reasoning=m;let D=await sne(p,{messages:[{role:"user",content:lne+g,timestamp:Date.now()}]},x);if(D.stopReason==="error"||D.stopReason==="aborted"){let E=D.errorMessage??(_.signal.aborted?"Generation timed out":"Model error");return console.error(`[generate-commit] failed provider=${o} model=${s} stopReason=${D.stopReason} error=${E}`),v("failed",`provider=${o} model=${s} stopReason=${D.stopReason} error=${E.slice(0,300)}`),w.json({error:E},{status:500})}let C=D.content.filter((E)=>E.type==="text").map((E)=>E.text).join("").trim().replace(/^```[\s\S]*?```$/m,(E)=>E.replace(/^```.*\n|\n```$/g,"").trim()).trim();if(v("result",`stopReason=${D.stopReason??"unknown"} contentTypes=${D.content.map((E)=>E.type).join(",")} textLen=${C.length} error=${D.errorMessage??""}`),!C){let E=D.stopReason==="length"||D.content.length>0&&D.content.every((A)=>A.type!=="text")?"(可能是推理模型上下文/ tokens 不足,尝试换用更大的 maxTokens 或非推理模型)":"",U=`Model returned empty message (stopReason=${D.stopReason??"unknown"})${E}`;return console.warn(`[generate-commit] empty text provider=${o} model=${s} maxTokens=${a} stopReason=${D.stopReason??"unknown"} content=${JSON.stringify(D.content).slice(0,600)} error=${D.errorMessage??""} frontendError=${U}`),v("empty",U),w.json({error:U},{status:500})}return v("success",`provider=${o} model=${s} stopReason=${D.stopReason??"unknown"} len=${C.length} preview=${C.slice(0,50).replace(/\n/g,"\\n")}`),console.log(`[generate-commit] success provider=${o} model=${s} stopReason=${D.stopReason??"unknown"} len=${C.length}`),w.json({message:C})}finally{clearTimeout(y)}}catch(r){let i=r instanceof Error?r.message:String(r);return console.error(`[generate-commit] exception provider=${t||"unknown"} model=${n||"unknown"} error=${i.slice(0,800)}`),w.json({error:i},{status:500})}}var $b={};Q($b,{POST:()=>fne});async function fne(e){try{let t=await e.json(),n=await Nn(t.cwd);if(!n.ok)return w.json({error:n.error},{status:n.status});let r=await u3(n.cwd);if(!r.ok)return w.json({error:r.error},{status:400});return w.json({ok:!0,output:r.output})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var Hb={};Q(Hb,{POST:()=>hne});async function hne(e){try{let t=await e.json(),n=await Nn(t.cwd);if(!n.ok)return w.json({error:n.error},{status:n.status});let r=await l3(n.cwd);if(!r.ok)return w.json({error:r.error},{status:400});return w.json({ok:!0,output:r.output})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var cv={};Q(cv,{GET:()=>kne});function Gb(){let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e}import{mkdirSync as gne,readFileSync as af,writeFileSync as v3,existsSync as mne}from"node:fs";import{dirname as yne,join as Zb}from"node:path";import{getAgentDir as Yb}from"@earendil-works/pi-coding-agent";var rf=["off","minimal","low","medium","high","xhigh","max"];var g3=[{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 m3=g3;var of=new Map;function Jb(e){return Zb(e??Yb(),"pi-web","config.json")}function bne(e){return Zb(e??Yb(),"pi-web-preferences.json")}function x3(e){try{if(mne(Jb(e)))return;let t=JSON.parse(af(bne(e),"utf8"));Qb({firstPaint:{locale:tv(t.firstPaint?.locale),fontScale:ov(t.firstPaint?.fontScale)},preferences:t.preferences??{}},e)}catch{}}function ti(e){let t=e===void 0,n=e??"",r=t?of.get(n):void 0;if(!t||r===void 0||r===null)try{let d=af(Jb(e),"utf8"),f=JSON.parse(d);r={firstPaint:{locale:tv(f.firstPaint?.locale),fontScale:ov(f.firstPaint?.fontScale)},preferences:f.preferences??{},theme:sf(e)},of.set(n,r)}catch{if(r={firstPaint:{},preferences:{},theme:sf(e)},t)of.set(n,r)}let i=nv(ps("defaultThinkingLevel",e)),o=rv(e),s=iv(e),a=Vb(ps("defaultProjectTrust",e)),c=S3(e),u=sv(e);return{...r,theme:sf(e),...i!==void 0?{defaultThinkingLevel:i}:{},...o!==void 0?{compaction:o}:{},...s!==void 0?{retry:s}:{},...a!==void 0?{defaultProjectTrust:a}:{},...c!==void 0?{subagents:c}:{},...u!==void 0?{piSettings:u}:{}}}function Qb(e,t){try{let n=Jb(t);gne(yne(n),{recursive:!0});let r={firstPaint:e.firstPaint,preferences:e.preferences};if(v3(n,JSON.stringify(r,null,2),"utf8"),t===void 0)of.set("",e)}catch{}}function _3(e,t){let n=ti(t),r={...n.firstPaint,...e.locale!==void 0?{locale:tv(e.locale)??n.firstPaint.locale}:{},...e.fontScale!==void 0?{fontScale:ov(e.fontScale)??n.firstPaint.fontScale}:{}},i=n.theme;if(e.theme!==void 0)i=Dne(e.theme,t);let o=e.defaultThinkingLevel===void 0?ps("defaultThinkingLevel",t):Kb("defaultThinkingLevel",nv(e.defaultThinkingLevel),t),s=e.compaction===void 0?rv(t):vne(e.compaction,t),a=e.retry===void 0?iv(t):_ne(e.retry,t),c=e.defaultProjectTrust===void 0?Vb(ps("defaultProjectTrust",t)):(()=>{let h=Vb(e.defaultProjectTrust);if(h===void 0)return;return Kb("defaultProjectTrust",h,t),h})(),u=e.subagents===void 0?S3(t):wne(e.subagents,t),d=e.piSettings===void 0?sv(t):Ene(e.piSettings,t),f={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?{subagents:u}:{},...d!==void 0?{piSettings:d}:{}};return Qb(f,t),f}function ev(e,t){let n=ti(t),r={firstPaint:n.firstPaint,preferences:{...n.preferences,...e},theme:n.theme};return Qb(r,t),r}function w3(e){let{preferences:t}=ti(e);if(t.startScreenMessages!==void 0)return;ev({startScreenMessages:m3},e)}function tv(e){return e==="en"||e==="zh-CN"?e:void 0}function D3(e){return e==="dark"||e==="light"?e:void 0}function nv(e){return typeof e==="string"&&rf.includes(e)?e:void 0}function E3(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 rv(e){return E3(gs("compaction",e))}function vne(e,t){let n=E3(e);if(!n)return rv(t);return wc("compaction",n,t),n}function xne(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 T3(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=xne(t.provider);if(r!==void 0)n.provider=r;return n}function iv(e){return T3(gs("retry",e))}function _ne(e,t){let n=T3(e);if(!n)return iv(t);return wc("retry",n,t),n}function Vb(e){if(e==="ask"||e==="always"||e==="never")return e;if(e==="trust")return"always";if(e==="deny")return"never";return}function Xb(e){if(typeof e!=="object"||e===null)return;let t=e,n={};if(typeof t.defaultModel==="string"&&t.defaultModel.trim()!=="")n.defaultModel=t.defaultModel;let r=nv(t.defaultThinking);if(r!==void 0)n.defaultThinking=r;return Object.keys(n).length>0?n:void 0}function S3(e){return Xb(gs("subagents",e))}function wne(e,t){let n=Xb(e);if(n===void 0)return;let r=gs("subagents",t),i=typeof r==="object"&&r!==null?{...r}:{};if(n.defaultModel!==void 0)i.defaultModel=n.defaultModel;else delete i.defaultModel;if(n.defaultThinking!==void 0)i.defaultThinking=n.defaultThinking;else delete i.defaultThinking;return wc("subagents",i,t),Xb(i)}function gs(e,t){try{return JSON.parse(af(C3(t),"utf8"))[e]}catch{return}}function wc(e,t,n){try{let r=C3(n),i={};try{i=JSON.parse(af(r,"utf8"))}catch{i={}}i[e]=t,v3(r,JSON.stringify(i,null,2),"utf8")}catch{}}function ps(e,t){let n=gs(e,t);return typeof n==="string"?n:void 0}function Kb(e,t,n){if(t===void 0)return ps(e,n);return wc(e,t,n),t}function C3(e){return Zb(e??Yb(),"settings.json")}function sf(e){return D3(ps("theme",e))??"light"}function Dne(e,t){let n=D3(e);if(!n)return sf(t);return Kb("theme",n,t),n}function ov(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0.85&&e<=1.3?e:void 0}var _c=(e)=>typeof e==="boolean"?e:void 0,zb=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0,y3=(e)=>typeof e==="string"&&e.trim()!==""?e:void 0;function b3(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 A3=[{key:"httpProxy",validate:y3},{key:"httpIdleTimeoutMs",validate:zb},{key:"websocketConnectTimeoutMs",validate:zb},{key:"enableAnalytics",validate:_c},{key:"enableInstallTelemetry",validate:_c},{key:"trackingId",validate:y3},{key:"branchSummary",validate:(e)=>b3(e,{reserveTokens:zb,skipPrompt:_c})},{key:"images",validate:(e)=>b3(e,{autoResize:_c,blockImages:_c})}];function sv(e){let t={};for(let{key:n,validate:r}of A3){let i=r(gs(n,e));if(i!==void 0)t[n]=i}return Object.keys(t).length>0?t:void 0}function Ene(e,t){for(let{key:n,validate:r}of A3){if(!(n in e))continue;let i=r(e[n]);if(i===void 0)continue;wc(n,i,t)}return sv(t)}var Tne=5000,Sne=60,U3=60000,uf=new Map,cf=new Set,av=new Map,Dc=new Map;function Cne(){let e=ti().preferences.gitAutoFetchIntervalSec;return typeof e==="number"&&Number.isFinite(e)?e:Sne}function Ane(e){let t=av.get(e);if(t)return t;let n=Gb();av.set(e,n.promise);let r;return(async()=>{try{let i=await Promise.race([(async()=>{let o=await d3(e);if(!o.ok)return{ok:!1,error:o.error};let s=await Nb(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 ${U3/1000}s`)),U3),r.unref?.()})]);n.resolve(i)}catch(i){n.resolve({ok:!1,error:i instanceof Error?i.message:String(i)})}finally{if(r)clearTimeout(r);av.delete(e)}})(),n.promise}async function k3(e){let t=new Map;for(let n of e){let r=null;try{r=await Mn(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 R3(e,t){await Promise.all(Array.from(e,async([n,r])=>{let i=await Ane(n);if(!i.ok){console.warn(`[git-autofetch] fetch failed for ${n}: ${i.error}`);return}for(let o of r)uf.set(on(o),i.snapshot);Dc.set(n,t)}))}async function Une(e=Date.now()){let t=Z2();for(let s of[...cf])if(!t.includes(s))cf.delete(s);let n=new Set(t);for(let s of[...uf.keys()])if(!n.has(s))uf.delete(s);if(t.length===0){Dc.clear();return}let r=Cne(),i=await k3(t);for(let s of[...Dc.keys()])if(!i.has(s))Dc.delete(s);if(r<=0){let s=t.filter((c)=>!cf.has(c));if(s.length===0)return;let a=await k3(s);await R3(a,e);for(let c of s)cf.add(c);return}let o=new Map;for(let[s,a]of i){let c=Dc.get(s)??0;if(e-c<r*1000)continue;o.set(s,a)}if(o.size===0)return;await R3(o,e)}function F3(e){return uf.get(on(e))??null}function O3(){setInterval(()=>{Une()},Tne).unref()}async function kne(e){try{let t=new URL(e.url).searchParams.get("cwd")??void 0,n=await Nn(t);if(!n.ok)return w.json({error:n.error},{status:n.status});let r=F3(n.cwd);if(!r)return w.json({ok:!0,cached:!1});return w.json({ok:!0,cached:!0,...r})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var uv={};Q(uv,{POST:()=>Fne});import Rne from"node:fs";async function Fne(e){try{let t=await e.json(),n=t.cwd?.trim()??"",r=t.filePath?.trim()??"",i=t.action==="unstage"?"unstage":"stage";if(!n||!n.startsWith("/")&&!at(n))return w.json({error:"cwd must be an absolute path"},{status:400});if(!r||!r.startsWith("/")&&!at(r))return w.json({error:"filePath must be an absolute path"},{status:400});let o=await de();if(!Xe(n,o))return w.json({error:"Access denied"},{status:403});let s;try{s=Rne.statSync(n)}catch{return w.json({error:"Directory not found"},{status:404})}if(!s.isDirectory())return w.json({error:"Not a directory"},{status:400});if(!be(n,o))return w.json({error:"Access denied"},{status:403});let a=i==="unstage"?await a3(n,r):await s3(n,r);if(!a.ok)return w.json({error:a.error},{status:400});return w.json({ok:!0})}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var lv={};Q(lv,{GET:()=>Pne});import One from"node:fs";async function Pne(e){try{let t=e.nextUrl.searchParams.get("cwd")?.trim()??"";if(!t||!t.startsWith("/")&&!at(t))return w.json({error:"cwd must be an absolute path"},{status:400});let n=await de();if(!Xe(t,n))return w.json({error:"Access denied"},{status:403});let r;try{r=One.statSync(t)}catch{return w.json({error:"Directory not found"},{status:404})}if(!r.isDirectory())return w.json({error:"Not a directory"},{status:400});if(!be(t,n))return w.json({error:"Access denied"},{status:403});return w.json(await o3(t))}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var dv={};Q(dv,{GET:()=>Mne});import{homedir as Ine}from"node:os";async function Mne(){return w.json({home:Ine()})}var hv={};Q(hv,{GET:()=>Hne,dynamic:()=>qne,loadModels:()=>ni});import{stat as Nne}from"node:fs/promises";import{resolve as Bne}from"node:path";import{getSupportedThinkingLevels as Lne}from"@earendil-works/pi-ai";import{createAgentSessionServices as Wne,getAgentDir as I3}from"@earendil-works/pi-coding-agent";var lf=null;function P3(e){if(lf)return;let t=(async()=>{for(let n of e)await Promise.allSettled([n()])})();lf=t,t.then(()=>{lf=null})}function Bn(){return lf??Promise.resolve()}import{resolveModelScopeWithDiagnostics as jne}from"@earendil-works/pi-coding-agent";var qne="force-dynamic",fv=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function $ne(e,t){return fv.compare(e.name||e.id,t.name||t.id)||fv.compare(e.provider,t.provider)||fv.compare(e.id,t.id)}async function ni(e){let t=new Map,n=[],r=null,i={},o={},s={},a=I3(),c=oo(e,a),u=await Wne({cwd:e,agentDir:a,...c?{resourceLoaderReloadOptions:c}:{}}),d=u.modelRuntime.getError(),f=u.settingsManager,h=f.getEnabledModels(),p=await wu(u.modelRuntime,h),{visible:g,thinkingLevelPins:b,warnings:v}=p,m=await ao(),_=await so(),y=new Set,x=[],D=[],C=(h??[]).map((S)=>S.trim()).filter(Boolean);if(m.length>0){let S=new Map;for(let B of await u.modelRuntime.getAvailable())S.set(`${B.provider}/${B.id}`,B);for(let B of m){if(_.has(B.toLowerCase()))continue;let G=(await gi(B)).map((T)=>Kh(B,T)).filter((T)=>T!==null);if(G.length===0)continue;y.add(B);for(let T of G)D.push(S.get(`${B}/${T.id}`)??T);for(let T of await Gne(B,G,C))x.push(S.get(`${B}/${T.id}`)??T)}}let E=[...g.filter((S)=>!y.has(S.provider)),...x],U=f.getDefaultProvider(),A=f.getDefaultModel(),N=Du(p,{...U&&A?{defaultModel:{provider:U,modelId:A}}:{}});if(N.model&&E.some((S)=>S.provider===N.model.provider&&S.id===N.model.id))r={provider:N.model.provider,modelId:N.model.id};n=E.map((S)=>({id:S.id,name:S.name,provider:S.provider,reasoning:S.reasoning,input:[...S.input],isDefault:r?.provider===S.provider&&r?.modelId===S.id})).sort($ne);for(let S of E){let B=`${S.provider}/${S.id}`;if(t.set(B,S.name),i[B]=Lne(S),S.thinkingLevelMap)o[B]=S.thinkingLevelMap}let O=[...u.modelRuntime.getModels().filter((S)=>!y.has(S.provider)),...D];for(let S of O){let B=`${S.provider}/${S.id}`;s[B]={id:S.id,name:S.name,api:S.api,provider:S.provider,baseUrl:S.baseUrl,reasoning:S.reasoning,...S.thinkingLevelMap?{thinkingLevelMap:S.thinkingLevelMap}:{},input:[...S.input],cost:{input:S.cost.input,output:S.cost.output,cacheRead:S.cost.cacheRead,cacheWrite:S.cost.cacheWrite},contextWindow:S.contextWindow,maxTokens:S.maxTokens,...S.samplingParams?{samplingParams:S.samplingParams}:{},...S.headers?{headers:S.headers}:{},...S.compat?{compat:S.compat}:{}}}return I2({models:Object.fromEntries(t),modelList:n,defaultModel:r,thinkingLevels:i,thinkingLevelMaps:o,thinkingLevelPins:b,definitions:s,...v.length>0?{modelScopeWarnings:v}:{}},d)}async function Hne(e){await Bn();let t=new URL(e.url),n=t.searchParams.has("cwd"),r=n?t.searchParams.get("cwd"):I3(),i=Bne(r),o;try{o=await Nne(i)}catch{return Response.json({error:`Directory does not exist: ${i}`},{status:400})}if(!o.isDirectory())return Response.json({error:`Not a directory: ${i}`},{status:400});if(n){let s=await de();if(!be(i,s))return Response.json({error:"Access denied"},{status:403})}try{let a={...await Tr(i,()=>ni(i))};return delete a.definitions,Response.json(a)}catch(s){return console.error("[api/models] failed to build model list:",s),Response.json({error:s instanceof Error?s.message:String(s)},{status:500})}}async function Gne(e,t,n){if(n.length===0)return t;let r=[],i=!1;for(let u of n){let d=u.indexOf("/");if(d===-1){i=!0,r.push(u);continue}let f=u.slice(0,d).trim().toLowerCase();if(!f||/[*?[]/.test(f)){i=!0,r.push(u);continue}r.push(u)}let o=e.toLowerCase(),s=i?r:r.filter((u)=>u.slice(0,u.indexOf("/")).trim().toLowerCase()===o);if(!i&&s.length===0)return t;let a={getAvailable:async()=>t},{scopedModels:c}=await jne(s,a);return c.map((u)=>u.model)}import pv from"node:fs";var zne=new Set(["select","confirm","input","editor"]),Vne=new Set(["agent_settled","prompt_done","prompt_error","extension_error"]),Xne=new Set(["turn_start","turn_end"]);function Kne(e){if(Xne.has(e.type))return null;if(e.type==="message_update"){let n=e.assistantMessageEvent;if(!n||typeof n.type!=="string")return e;let r={type:n.type};if(typeof n.delta==="string")r.delta=n.delta;if(typeof n.contentIndex==="number")r.contentIndex=n.contentIndex;if(n.type==="toolcall_end"&&n.toolCall&&typeof n.toolCall==="object")r.toolCall=n.toolCall;if(n.type==="toolcall_start"&&typeof n.contentIndex==="number"){let o=n.partial?.content?.[n.contentIndex];if(o&&o.type==="toolCall"&&typeof o.name==="string")r.toolCall={type:"toolCall",toolCallId:typeof o.id==="string"?o.id:"",toolName:o.name}}return{type:"message_update",assistantMessageEvent:r}}if(e.type==="message_start"||e.type==="message_end")return e;if(e.type==="agent_end")return{type:"agent_end"};return e}var lr=new Map,ff=null,hf=null;function Ot(e,t,n){try{e.ws.send(JSON.stringify({ch:t,data:n}))}catch{}}function M3(e,t){let n=lr.get(e);if(!n)return;for(let r of n){if(e==="global"){let i=t,o=i.type==="extension_ui_request"&&zne.has(i.method),s=typeof i.type==="string"&&Vne.has(i.type);if(o)jt("ui-chain",`3 ws broadcast ${String(i.method)}`,`id=${String(i.id).slice(0,8)} sid=${String(i.sessionId).slice(0,8)} conns=${n.size}`);if(!s){let a=i.sessionId;if(a&&!r.seenSessions.has(a))continue}Ot(r,e,t);continue}if(e==="running"){Ot(r,e,{type:"running",...B3(t,r.seenSessions)});continue}Ot(r,e,t)}}function Zne(e){if(e==="global"&&!ff)ff=n1((t,n)=>{let r=Kne(n);if(r)M3("global",{sessionId:t,...r})});if(e==="running"&&!hf)hf=e1((t)=>M3("running",t))}function B3(e,t){let n=e.runningSessionIds.filter((s)=>t.has(s)),r={},i={},o={};for(let s of n){if(e.phases[s]!==void 0)r[s]=e.phases[s];if(e.phaseSince[s]!==void 0)i[s]=e.phaseSince[s];if(e.busySince[s]!==void 0)o[s]=e.busySince[s]}return{runningSessionIds:n,phases:r,phaseSince:i,busySince:o}}function Yne(e){if(e==="global"&&lr.get("global")?.size===0)ff?.(),ff=null;if(e==="running"&&lr.get("running")?.size===0)hf?.(),hf=null}function N3(e,t){let n=lr.get(t);if(!n)n=new Set,lr.set(t,n);if(n.add(e),!e.channels.has(t))e.channels.set(t,{kind:"passive"});Zne(t)}function df(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(lr.get(t)?.delete(e),n.kind==="passive")Yne(t);if(n.kind==="agent"){let r=lr.get(t);if(!r||r.size===0){let i=t.slice(6);bt(i)?.cancelPendingUiResponses()}}}async function Jne(e,t){let n=`agent:${t}`;if(e.seenSessions.add(t),e.channels.has(n))return;let r=bt(t);if(!r?.isAlive()){let o=await We(t);if(!o){Ot(e,n,{type:"not_found",sessionId:t});return}try{({session:r}=await hi(t,o,void 0))}catch(s){Ot(e,n,{type:"start_failed",sessionId:t,message:String(s)});return}}e.channels.set(n,{kind:"agent",unsubscribe:()=>{}}),lr.get(n)?.add(e),Ot(e,n,{type:"connected",sessionId:t});let i=r.getPendingUiRequests();for(let o of i)Ot(e,"global",{...o,sessionId:t})}function Qne(e,t){let n=t,r=`watch:${n}`,i;try{i=pv.statSync(n)}catch{Ot(e,r,{event:"error",message:"Not found"});return}if(!i.isFile()){Ot(e,r,{event:"error",message:"Not a file"});return}let o,s=i.mtimeMs,a=i.size;try{o=pv.watch(n,()=>{try{let c=pv.statSync(n);if(c.mtimeMs===s&&c.size===a)return;s=c.mtimeMs,a=c.size,Ot(e,r,{event:"change",mtime:c.mtime.toISOString(),size:c.size})}catch{Ot(e,r,{event:"change",mtime:new Date().toISOString(),size:0})}})}catch{Ot(e,r,{event:"error",message:"Failed to watch file"});return}o.on("error",()=>{df(e,r)}),e.channels.set(r,{kind:"watch",watcher:o}),lr.get(r)?.add(e),Ot(e,r,{event:"connected",filePath:n})}async function ere(e,t){switch(t.ch){case"global":{N3(e,"global");return}case"running":{N3(e,"running"),Ot(e,"running",{type:"running",...B3(qs(),e.seenSessions)});return}case"agent":{let n=typeof t.sessionId==="string"?t.sessionId:"";if(n)await Jne(e,n);return}case"watch":{if(typeof t.filePath==="string"&&t.filePath)Qne(e,t.filePath);return}default:return}}function tre(e){if(!Tt(e))return!1;let t=process.env.PI_WEB_PASSWORD;if(Ls(t)&&!au(e.headers.get("authorization"),t))return!1;return!0}var gv=null;function mv(e){gv=e((t)=>{if(!tre(t.req.raw))return{onOpen:(i,o)=>o.close(1008,"untrusted")};let n={ws:null,channels:new Map,seenSessions:new Set},r=null;return{onOpen:(i,o)=>{n.ws=o,o.send(JSON.stringify({type:"connected"})),r=setInterval(()=>{try{o.send(JSON.stringify({type:"ping"}))}catch{}},30000)},onMessage:async(i)=>{if(typeof i.data!=="string")return;let o;try{o=JSON.parse(i.data)}catch{return}if(o.type==="sub")await ere(n,o);else if(o.type==="unsub"&&typeof o.ch==="string")df(n,o.ch);else if(o.type==="unseen"&&typeof o.sessionId==="string"){let s=o.sessionId;n.seenSessions.delete(s);let a=`agent:${s}`;if(n.channels.has(a))df(n,a)}},onClose:()=>{if(r)clearInterval(r);for(let i of[...n.channels.keys()])df(n,i)}}})}function L3(e){e.get("/api/ws",(t,n)=>gv?gv(t,n):n())}var bv={};Q(bv,{GET:()=>xre,dynamic:()=>pre});var nre={anthropic:["api.anthropic.com"],google:["generativelanguage.googleapis.com"],openai:["api.openai.com"],openrouter:["openrouter.ai"]},rre=new Set(["text","image","audio","video","pdf"]);function Hi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function pf(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function gf(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0?e:void 0}function W3(e){return typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0}function ire(e){if(!Hi(e))return{};return{input:gf(e.input),output:gf(e.output),cacheRead:gf(e.cache_read),cacheWrite:gf(e.cache_write)}}function ore(e){if(!Hi(e)||!Array.isArray(e.input))return;let t=Array.from(new Set(e.input.filter((n)=>typeof n==="string").map((n)=>n.trim().toLocaleLowerCase()).filter((n)=>rre.has(n))));return t.length?t:void 0}function mf(e){return e.trim().toLocaleLowerCase().replace(/[^a-z0-9]/g,"")}function j3(e){return e.trim().toLocaleLowerCase().replace(/^models\//,"")}function q3(e){if(!e)return;try{return new URL(e).hostname.toLocaleLowerCase().replace(/\.$/,"")}catch{return}}function sre(e,t){return e===t||e.endsWith(`.${t}`)}function are(e,t){let n=mf(t);if(!n)return!1;return mf(e.providerId)===n||mf(e.providerName)===n}function cre(e,t){let n=q3(t);if(!n)return!1;let r=nre[mf(e.providerId)]??[],i=q3(e.providerBaseUrl);return[...r,...i?[i]:[]].some((o)=>sre(n,o))}function ure(e,t){let n=j3(t);if(!n)return!1;let r=j3(e.id),i=`${e.providerId.toLocaleLowerCase()}/${r}`;return r===n||i===n}function yv(e){return e.cost.input!==void 0&&e.cost.output!==void 0}function Ec(e,t,n){if(e.length===0||t<=0)return;let r=new Map;for(let s of e){let a=n(s),c=r.get(a);if(c)c.count+=1;else r.set(a,{value:s,count:1})}let i=[...r.values()].sort((s,a)=>a.count-s.count),o=i[0];if(!o||o.count/t<0.6)return;if(i[1]?.count===o.count)return;return o.value}function $3(e){if(e.length===0)return;let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=[...t.entries()].sort((r,i)=>i[1]-r[1]);if(!n[0]||n[1]?.[1]===n[0][1])return;return n[0][0]}function lre(e){return{name:e.name,reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens}}function dre(e){let t=e.length;return{name:Ec(e.map((n)=>n.name),t,(n)=>n.toLocaleLowerCase()),reasoning:Ec(e.flatMap((n)=>n.reasoning===void 0?[]:[n.reasoning]),t,String),input:Ec(e.flatMap((n)=>n.input?[n.input]:[]),t,(n)=>[...n].sort().join(",")),contextWindow:Ec(e.flatMap((n)=>n.contextWindow===void 0?[]:[n.contextWindow]),t,String),maxTokens:Ec(e.flatMap((n)=>n.maxTokens===void 0?[]:[n.maxTokens]),t,String)}}function H3(e,t){return{status:"reliable",method:t,cost:e.cost,providerId:e.providerId,providerName:e.providerName,support:1,total:1}}function fre(e){let t=e.filter(yv);if(t.length===0)return{status:"unreliable",reason:"no-valid-price",support:0,total:0};if(t.length===1)return{status:"unreliable",reason:"insufficient-support",support:1,total:1};let n=new Map;for(let a of t){let c=JSON.stringify([a.cost.input,a.cost.output]),u=n.get(c);if(u)u.push(a);else n.set(c,[a])}let r=[...n.values()].sort((a,c)=>c.length-a.length),i=r[0];if(!i)return{status:"unreliable",reason:"no-valid-price",support:0,total:t.length};if(r[1]?.length===i.length||i.length/t.length<0.6)return{status:"unreliable",reason:"conflict",support:i.length,total:t.length};let o=$3(i.flatMap((a)=>a.cost.cacheRead===void 0?[]:[a.cost.cacheRead])),s=$3(i.flatMap((a)=>a.cost.cacheWrite===void 0?[]:[a.cost.cacheWrite]));return{status:"reliable",method:"consensus",cost:{input:i[0].cost.input,output:i[0].cost.output,cacheRead:o,cacheWrite:s},support:i.length,total:t.length}}function G3(e){if(!Hi(e))return[];let t=[];for(let[n,r]of Object.entries(e)){if(!Hi(r)||!Hi(r.models))continue;let i=pf(r.name)??n,o=pf(r.api);for(let[s,a]of Object.entries(r.models)){if(!Hi(a))continue;let c=pf(a.id)??s;if(!c)continue;let u=pf(a.name)??c,d={key:`${n}/${c}`,providerId:n,providerName:i,id:c,name:u,cost:ire(a.cost)};if(o)d.providerBaseUrl=o;if(typeof a.reasoning==="boolean")d.reasoning=a.reasoning;let f=ore(a.modalities);if(f)d.input=f;if(Hi(a.limit)){let h=W3(a.limit.context),p=W3(a.limit.output);if(h!==void 0)d.contextWindow=h;if(p!==void 0)d.maxTokens=p}t.push(d)}}return t}function z3(e,t,n="",r=""){let i=e.filter((p)=>ure(p,t));if(i.length===0)return{exactMatches:0,metadataMethod:"none",preset:{},price:{status:"unreliable",reason:"no-exact-match",support:0,total:0}};let o=i.filter((p)=>are(p,n)),s=i.filter((p)=>cre(p,r)),a=o[0]??s[0],c=o.length?"provider":s.length?"base-url":"consensus",u=a?lre(a):dre(i),d=o.find(yv),f=s.find(yv),h=d?H3(d,"provider"):f?H3(f,"base-url"):fre(i);if(h.status==="reliable")u.cost=h.cost;return{exactMatches:i.length,metadataMethod:c,matchedProviderId:a?.providerId,matchedProviderName:a?.providerName,preset:u,price:h}}function hre(e,t,n){let r=e.id.toLocaleLowerCase(),i=e.name.toLocaleLowerCase(),o=e.providerId.toLocaleLowerCase(),s=e.providerName.toLocaleLowerCase(),a=`${o}/${r}`,c=20;if(!t)c=10;else if(r===t||a===t)c=0;else if(i===t)c=1;else if(r.startsWith(t)||i.startsWith(t))c=2;else if(a.startsWith(t)||o===t||s===t)c=3;else if(r.includes(t)||i.includes(t))c=4;else if(a.includes(t)||s.includes(t))c=5;if(c<20&&n&&(o===n||s===n))c-=0.5;return c}function V3(e,t,n="",r=50){let i=t.trim().toLocaleLowerCase(),o=n.trim().toLocaleLowerCase(),s=Math.max(1,Math.min(100,Math.floor(r)||50));return e.map((a)=>({entry:a,rank:hre(a,i,o)})).filter(({rank:a})=>!i||a<20).sort((a,c)=>a.rank-c.rank||a.entry.providerName.localeCompare(c.entry.providerName,void 0,{sensitivity:"base"})||a.entry.name.localeCompare(c.entry.name,void 0,{numeric:!0,sensitivity:"base"})||a.entry.id.localeCompare(c.entry.id,void 0,{numeric:!0,sensitivity:"base"})).slice(0,s).map(({entry:a})=>a)}var pre="force-dynamic",X3="https://models.dev/api.json",gre=3600000,mre=15000;function yre(){return globalThis.__piModelsDevCatalogCache??={entries:[],expiresAt:0}}async function bre(){let e=await fetch(X3,{cache:"no-store",headers:{Accept:"application/json"},signal:AbortSignal.timeout(mre)});if(!e.ok)throw Error(`models.dev returned HTTP ${e.status}`);let t=G3(await e.json());if(t.length===0)throw Error("models.dev returned an empty catalog");return t}async function vre(){let e=yre();if(e.entries.length>0&&e.expiresAt>Date.now())return e.entries;if(!e.inFlight)e.inFlight=bre().then((t)=>(e.entries=t,e.expiresAt=Date.now()+gre,t)).finally(()=>{e.inFlight=void 0});try{return await e.inFlight}catch(t){if(e.entries.length>0)return e.entries;throw t}}async function xre(e){let{searchParams:t}=new URL(e.url),n=(t.get("q")??"").slice(0,120),r=(t.get("provider")??"").slice(0,120),i=(t.get("baseUrl")??"").slice(0,500),o=Number.parseInt(t.get("limit")??"50",10),s=Number.isFinite(o)?o:50;try{let a=await vre(),c=V3(a,n,r,s),u=z3(a,n,r,i);return w.json({models:c,recommendation:u,source:X3})}catch(a){return w.json({error:a instanceof Error?a.message:String(a)},{status:502})}}var vv={};Q(vv,{POST:()=>Rre,dynamic:()=>Cre});import{mkdtempSync as _re,rmSync as wre,writeFileSync as Dre}from"node:fs";import{tmpdir as Ere}from"node:os";import{join as K3}from"node:path";import{ModelRuntime as Tre}from"@earendil-works/pi-coding-agent";function Sre(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Z3(e){if(!Sre(e))return{};return Object.fromEntries(Object.entries(e).filter((t)=>typeof t[1]==="string"))}async function Y3(e,t){let n;try{n=_re(K3(Ere(),"pi-web-model-discovery-"));let r=K3(n,"models.json"),i="__pi_web_model_discovery__";Dre(r,JSON.stringify({providers:{[e]:{...t,models:[{id:i}]}}},null,2),"utf8");let o=await Tre.create({modelsPath:r}),s=o.getError();if(s)throw Error(s);let a=o.getModel(e,i);if(!a)throw Error(`Unable to load provider "${e}"`);let c=await o.getAuth(a);if(c)return{apiKey:c.auth.apiKey,headers:Z3(c.auth.headers)};return{headers:Z3(o.getCompatibilityRequestConfig(a).headers)}}finally{if(n)wre(n,{recursive:!0,force:!0})}}var Cre="force-dynamic",Are=20000;function Ure(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Tc(e,t){return e.has(t)}function kre(e,t,n){let r=new Headers(n);if(!Tc(r,"accept"))r.set("Accept","application/json");if(!t)return r;if(e==="anthropic-messages"){if(!Tc(r,"x-api-key"))r.set("x-api-key",t);if(!Tc(r,"anthropic-version"))r.set("anthropic-version","2023-06-01")}else if(e==="google-generative-ai"){if(!Tc(r,"x-goog-api-key"))r.set("x-goog-api-key",t)}else if(!Tc(r,"authorization"))r.set("Authorization",`Bearer ${t}`);return r}async function Rre(e){try{let t=await e.json(),n=typeof t.providerName==="string"?t.providerName.trim():"";if(!n)return w.json({error:"providerName is required"},{status:400});if(!Ure(t.provider))return w.json({error:"provider is required"},{status:400});let r=typeof t.provider.baseUrl==="string"?t.provider.baseUrl.trim():"";if(!r)return w.json({error:"Base URL is required"},{status:400});let i=typeof t.provider.api==="string"&&t.provider.api?t.provider.api:"openai-completions",o;try{o=$s(r,i)}catch{return w.json({error:"Base URL is invalid"},{status:400})}let s=await gi(n);if(s.length>0){let h=s.map((p)=>Ar(p)).filter((p)=>p!==null);if(h.length>0)return w.json({models:h})}let a=await Y3(n,t.provider);if(typeof t.provider.apiKey==="string"&&t.provider.apiKey.trim()&&!a.apiKey)return w.json({error:`No API key found for "${n}"`},{status:400});let c=await fetch(o,{cache:"no-store",headers:kre(i,a.apiKey,a.headers),signal:AbortSignal.timeout(Are)}),u=await c.text();if(!c.ok)return w.json({error:u.slice(0,500)||`Upstream returned HTTP ${c.status}`,status:c.status},{status:502});let d;try{d=JSON.parse(u)}catch{return w.json({error:"Upstream model list was not valid JSON"},{status:502})}let f=Xh(d);if(f.length===0)return w.json({error:"No models found in the upstream response"},{status:502});return await Au(n,Ur(d)),w.json({models:f,endpoint:o.toString()})}catch(t){let n=t instanceof Error?t.message:String(t),r=t instanceof DOMException&&t.name==="TimeoutError"?504:500;return w.json({error:n},{status:r})}}var xv={};Q(xv,{GET:()=>Ore,dynamic:()=>Fre});import{getAgentDir as J3}from"@earendil-works/pi-coding-agent";var Fre="force-dynamic";async function Ore(e){await Bn();let t=new URL(e.url),n=t.searchParams.get("provider")?.trim()??"",r=t.searchParams.get("model")?.trim()??"";if(!n||!r)return Response.json({error:"provider and model are required"},{status:400});try{let o=(await Tr(J3(),()=>ni(J3()))).definitions?.[`${n}/${r}`];if(!o)return Response.json({error:`Model not found: ${n}/${r}`},{status:404});return Response.json({model:o})}catch(i){return console.error("[api/models-config/effective] failed:",i),Response.json({error:i instanceof Error?i.message:String(i)},{status:500})}}var _v={};Q(_v,{GET:()=>Ire,dynamic:()=>Pre});import{getAgentDir as Q3}from"@earendil-works/pi-coding-agent";var Pre="force-dynamic";async function Ire(e){await Bn();let t=new URL(e.url),n=t.searchParams.get("provider")?.trim()??"",r=t.searchParams.get("model")?.trim()??"";if(!n||!r)return Response.json({error:"provider and model are required"},{status:400});try{let o=(await Tr(Q3(),()=>ni(Q3()))).definitions?.[`${n}/${r}`];if(!o)return Response.json({error:`Model not found: ${n}/${r}`},{status:404});let a=(await gi(n)).find((u)=>Ar(u)?.id===r),c=a?h1(a,o):{};return Response.json({suggestion:c})}catch(i){return console.error("[api/models-config/override-suggestion] failed:",i),Response.json({error:i instanceof Error?i.message:String(i)},{status:500})}}var Dv={};Q(Dv,{POST:()=>Bre,dynamic:()=>Mre});var Mre="force-dynamic",Nre=15000;function wv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function Bre(e){if(!Tt(e))return w.json({ok:!1,error:"Untrusted API request"},{status:403});if(!Dr(e))return w.json({ok:!1,error:"Content-Type must be application/json"},{status:415});try{let t=await e.json(),n=wv(t.provider)?t.provider:{},r=typeof n.baseUrl==="string"?n.baseUrl.trim():"";if(!r)return w.json({ok:!1,error:"baseUrl is required"},{status:400});let i=typeof n.apiKey==="string"?n.apiKey.trim():"",o=typeof n.api==="string"?n.api:"",s={Accept:"application/json"};if(o==="anthropic-messages"){if(i)s["x-api-key"]=i;s["anthropic-version"]="2023-06-01"}else if(o==="google-generative-ai"){if(i)s["x-goog-api-key"]=i}else if(i)s.Authorization=`Bearer ${i}`;let a=`${r.replace(/\/+$/,"")}/models`,c=await fetch(a,{headers:s,cache:"no-store",signal:AbortSignal.timeout(Nre)});if(!c.ok)return w.json({ok:!1,error:`HTTP ${c.status}`},{status:502});let u=await c.json().catch(()=>{return}),d=Array.isArray(u)?u:wv(u)&&Array.isArray(u.data)?u.data:wv(u)&&Array.isArray(u.models)?u.models:[];return w.json({ok:!0,models:d})}catch(t){return w.json({ok:!1,error:t instanceof Error?t.message:String(t)})}}co();Zh();var Av={};Q(Av,{GET:()=>zre,PUT:()=>Vre,cleanupStaleEnabledModels:()=>Cv,dynamic:()=>qre,extractLiteralApiKeys:()=>a8});import{existsSync as vf,mkdirSync as n8,readFileSync as r8}from"node:fs";import{rename as Wre,rm as e8}from"node:fs/promises";import{dirname as i8,join as bf}from"node:path";import{getAgentDir as jre}from"@earendil-works/pi-coding-agent";var Lre=new Set(["off","minimal","low","medium","high","xhigh","max"]),yf=new Set(["amazon-bedrock","ant-ling","anthropic","azure-openai-responses","baseten","cerebras","cloudflare-ai-gateway","cloudflare-workers-ai","deepseek","fireworks","github-copilot","google","google-vertex","groq","huggingface","kimi-coding","minimax","minimax-cn","mistral","moonshotai","moonshotai-cn","nvidia","openai","openai-codex","opencode","opencode-go","openrouter","qwen-token-plan","qwen-token-plan-cn","qwen-token-plan-individual","radius","together","vercel-ai-gateway","xai","xiaomi","xiaomi-token-plan-ams","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","zai","zai-coding-cn"]);function Ev(e,t,n){let r=Object.keys(n?.providers??{}),i=t?.providers??{},o=new Set([...r,...Object.keys(i)]);return e.filter((s)=>{if(/[?*[\]]/.test(s)||!s.includes("/"))return!0;let a=s.indexOf("/"),c=s.slice(0,a);if(!o.has(c))return yf.has(c);let u=s.slice(a+1),d=u.lastIndexOf(":");if(d!==-1){let h=u.slice(d+1);if(Lre.has(h))u=u.slice(0,d);else return!0}let f=i[c];if(!f)return!1;if(yf.has(c))return!0;return(f.models??[]).some((h)=>h.id===u)})}var qre="force-dynamic";function o8(e){return sn("models.json",vt("models.json",e))}function Sv(e){let t=o8(e);if(!vf(t))return{providers:{}};try{return JSON.parse(r8(t,"utf8"))}catch{return{providers:{}}}}function t8(e,t){let n=o8(t),r=i8(n);if(!vf(r))n8(r,{recursive:!0});Gs(n,JSON.stringify(e,null,2))}var $re=/\$[A-Za-z_][A-Za-z0-9_]*|\$\{[A-Za-z_][A-Za-z0-9_]*\}/;function s8(e){return!e.startsWith("!")&&!$re.test(e)}async function a8(e,t){if(!e||typeof e!=="object")return;for(let[n,r]of Object.entries(e)){if(!r||typeof r!=="object"||Array.isArray(r))continue;let i=r.apiKey;if(typeof i!=="string"||i.length===0)continue;if(!s8(i))continue;await ju(n,{type:"api_key",key:i},t),delete r.apiKey}}function Hre(e){if(!e||typeof e!=="object")return;let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==="object"&&!Array.isArray(r)){let i=r;if(typeof i.apiKey==="string"&&s8(i.apiKey))t[n]={...i},delete t[n].apiKey;else t[n]=r}else t[n]=r;return t}function c8(e){return sn("settings.json",vt("settings.json",e))}function Sc(e){let t=c8(e);if(!vf(t))return{};try{return JSON.parse(r8(t,"utf8"))}catch{return{}}}function Tv(e,t){let n=c8(t),r=i8(n);if(!vf(r))n8(r,{recursive:!0});Gs(n,JSON.stringify(e,null,2))}function Gre(e){let t=Sc(e),n=t.defaultProvider,r=t.defaultModel;if(typeof n==="string"&&typeof r==="string"&&n&&r)return{provider:n,modelId:r};return null}function u8(e){let t=Sc(e);return Array.isArray(t.enabledModels)?t.enabledModels.filter((n)=>typeof n==="string"):[]}function Cv(e){let t=u8(e);if(t.length===0)return;let n=Sv(e),r=Ev(t,n,n);if(r.length===t.length)return;let i=Sc(e);i.enabledModels=r,Tv(i,e),ke(),console.log(`[models-config] pruned ${t.length-r.length} stale enabledModels entr${t.length-r.length===1?"y":"ies"}: ${t.filter((o)=>!r.includes(o)).join(", ")}`)}async function zre(e){let t=ae(e),n=Sv(t);return w.json({providers:n.providers??{},defaultModel:Gre(t),enabledModels:u8(t)})}async function Vre(e){try{let t=await e.json(),{models:n,defaultModel:r,enabledModels:i,renames:o}=t,a={...n??t};delete a.enabledModels,delete a.defaultModel,delete a.defaultProvider;let c=ae(e),u=sn("auth.json",vt("auth.json",c)),d=Sv(ae(e));t8({...a,providers:Hre(a.providers)},ae(e));try{await a8(a.providers,u)}catch(m){throw t8(d,ae(e)),m}if(r&&typeof r.provider==="string"&&typeof r.modelId==="string"){let m=Sc(ae(e));m.defaultProvider=r.provider,m.defaultModel=r.modelId,Tv(m,ae(e))}if(Array.isArray(i)){let m=Sc(ae(e));m.enabledModels=Ev(i.filter((_)=>typeof _==="string"),a,d),Tv(m,ae(e))}let f=d.providers??{},h=a.providers??{},p=new Set(Object.keys(h)),g=(Array.isArray(o)?o:[]).filter((m)=>!!m&&typeof m.oldId==="string"&&typeof m.newId==="string"&&m.oldId!==m.newId&&!yf.has(m.newId)&&!Object.hasOwn(f,m.newId)&&Object.hasOwn(f,m.oldId)&&qu(f[m.oldId])&&Object.hasOwn(h,m.newId));for(let m of g)await K1(m.oldId,m.newId,u);let b=new Set(g.map((m)=>m.oldId));await Z1(f,p,u,b);let v=bf(jre(),"pi-web","provider");for(let{oldId:m,newId:_}of g){if(!kr(m)||!kr(_))continue;let y=bf(v,m),x=bf(v,_);try{await Wre(y,x)}catch{await e8(y,{recursive:!0,force:!0}).catch(()=>{})}}for(let m of Object.keys(f)){if(p.has(m)||b.has(m)||!kr(m))continue;await e8(bf(v,m),{recursive:!0,force:!0}).catch(()=>{})}return ke(),w.json({success:!0})}catch(t){return w.json({error:String(t)},{status:500})}}var kv={};Q(kv,{GET:()=>iie,POST:()=>rie,dynamic:()=>Jre,getProviderModelsCaches:()=>f8});import{getAgentDir as Xre}from"@earendil-works/pi-coding-agent";import{ModelRuntime as Kre}from"@earendil-works/pi-coding-agent";import{readFile as Zre,readdir as Yre,stat as l8}from"node:fs/promises";import{join as d8}from"node:path";var Jre="force-dynamic",Uv=d8(Xre(),"pi-web","provider"),Qre=5000;async function f8(){try{if(!(await l8(Uv)).isDirectory())return{}}catch{return{}}let e=await Yre(Uv,{withFileTypes:!0}),t={};for(let n of e){if(!n.isDirectory())continue;let r=d8(Uv,n.name,"models.json");try{let i=JSON.parse(await Zre(r,"utf-8")),o=Ur(i),s=await l8(r);t[n.name]={modelCount:o.length,lastSyncedAt:s.mtimeMs}}catch{}}return t}function eie(e){return e.replace(/\$\{(\w+)\}/g,(t,n)=>process.env[n]??"").replace(/\$([A-Z_][A-Z0-9_]*)/g,(t,n)=>process.env[n]??"")}async function tie(e){let{configFilePath:t,resolveConfigFileDir:n}=await Promise.resolve().then(() => (co(),y1)),r=t("models.json",n("models.json")),{readFileSync:i,existsSync:o}=await import("node:fs");if(!o(r))return null;try{let c=JSON.parse(i(r,"utf-8")).providers?.[e];if(!c)return null;let u=typeof c.baseUrl==="string"?c.baseUrl:void 0,d;if(typeof c.apiKey==="string")d=eie(c.apiKey);return u?{baseUrl:u,apiKey:d}:null}catch{return null}}async function nie(e,t){let n=t.getProvider(e),r,i={},o=await t.getAvailable();if(n){r=typeof n.baseUrl==="string"&&n.baseUrl.trim()&&n.baseUrl||o.find((p)=>p.provider===e)?.baseUrl||void 0;try{let p=await t.getAuth(e);if(p?.auth?.apiKey)i={Authorization:`Bearer ${p.auth.apiKey}`}}catch{}}else{let p=await tie(e);if(!p)throw Error(`Provider "${e}" not found in built-in or models.json`);if(r=p.baseUrl,p.apiKey)i={Authorization:`Bearer ${p.apiKey}`}}if(!r||r.trim()==="")throw Error(`Provider "${e}" has no baseUrl configured`);let s=o.find((p)=>p.provider===e)?.api??"",a;try{a=$s(r,s)}catch{throw Error(`Invalid baseUrl for provider "${e}"`)}let c=await fetch(a,{headers:i,cache:"no-store",signal:AbortSignal.timeout(Qre)});if(!c.ok)throw Error(`Provider "${e}" returned HTTP ${c.status} from ${a}`);let u=await c.text();if(!u.trim())throw Error(`Provider "${e}" returned empty response`);let d=JSON.parse(u),{parseDiscoveredModels:f}=await Promise.resolve().then(() => u1),h=Ur(d);if(f(d).length===0)throw Error(`Provider "${e}" returned no parsable models`);return await Au(e,h),{count:h.length}}async function rie(e){try{let{providerName:t}=await e.json();if(typeof t!=="string"||t.trim()==="")return Response.json({error:"providerName is required"},{status:400});let n=t.trim();if(!kr(n))return Response.json({error:`Invalid providerName: ${JSON.stringify(t)}`},{status:400});let r=await Kre.create({allowModelNetwork:!0}),{count:i}=await nie(n,r);return ke(),Response.json({count:i})}catch(t){let n=t instanceof Error?t.message:String(t);return Response.json({error:n},{status:500})}}async function iie(){let e=await f8();return Response.json(e)}var Rv={};Q(Rv,{GET:()=>pie,PUT:()=>gie});import{mkdirSync as aie,readFileSync as cie,writeFileSync as uie}from"node:fs";import{dirname as lie,join as die}from"node:path";import{getAgentDir as fie}from"@earendil-works/pi-coding-agent";var oie=rf;function sie(e){return typeof e==="string"&&oie.includes(e)}function ms(e){if(!e||typeof e!=="object"||Array.isArray(e))return{};let t=e,n=(r)=>{let i=t[r];if(!i||typeof i!=="object"||Array.isArray(i))return;let o={};for(let[s,a]of Object.entries(i))if(sie(a))o[s]=a;return Object.keys(o).length>0?o:void 0};return{models:n("models"),providers:n("providers")}}var xf=new Map;function h8(e){return die(e??fie(),"pi-web","model-thinking.json")}function p8(e){let t=e??"",n=xf.get(t);if(n!==void 0&&n!==null)return n;try{let r=cie(h8(e),"utf8"),i=JSON.parse(r);return n=ms(i),xf.set(t,n),n}catch{return n={},xf.set(t,n),n}}function hie(e,t){try{let n=h8(t);aie(lie(n),{recursive:!0});let r=ms(e);uie(n,JSON.stringify(r,null,2)+`
352
352
  `,"utf8"),xf.set(t??"",r)}catch{}}function g8(e,t){let n=ms(e);return hie(n,t),n}async function pie(e){return w.json(p8(ae(e)))}async function gie(e){try{let t=await e.json(),n=ae(e),r=ms(t),i=g8(r,n);return w.json(i)}catch{return w.json({error:"invalid body"},{status:400})}}var Fv={};Q(Fv,{POST:()=>Tie,dynamic:()=>wie});import{mkdtempSync as mie,rmSync as yie,writeFileSync as bie}from"node:fs";import{tmpdir as vie}from"node:os";import{join as m8}from"node:path";import{completeSimple as xie}from"@earendil-works/pi-ai/compat";import{ModelRuntime as _ie}from"@earendil-works/pi-coding-agent";var wie="force-dynamic",y8=20000;function b8(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Die(e){return e instanceof Error?e.message:String(e)}function Eie(e){return e.content.filter((t)=>t.type==="text").map((t)=>t.text).join("")}async function Tie(e){if(!Tt(e))return w.json({ok:!1,error:"Untrusted API request"},{status:403});if(!Dr(e))return w.json({ok:!1,error:"Content-Type must be application/json"},{status:415});let t;try{let n=await e.json(),r=typeof n.providerName==="string"?n.providerName.trim():"";if(!r)return w.json({ok:!1,error:"providerName is required"},{status:400});if(!b8(n.provider))return w.json({ok:!1,error:"provider is required"},{status:400});if(!b8(n.model))return w.json({ok:!1,error:"model is required"},{status:400});let i=typeof n.model.id==="string"?n.model.id.trim():"";if(!i)return w.json({ok:!1,error:"Model ID is required"},{status:400});t=mie(m8(vie(),"pi-web-model-test-"));let o=m8(t,"models.json");bie(o,JSON.stringify({providers:{[r]:{...n.provider,models:[{...n.model,id:i}]}}},null,2),"utf8");let s=await _ie.create({modelsPath:o}),a=s.getError();if(a)return w.json({ok:!1,error:a});let c=s.getModel(r,i);if(!c)return w.json({ok:!1,error:`Model not found: ${r}/${i}`});let u=await s.getAuth(c);if(!u?.auth.apiKey)return w.json({ok:!1,error:`No API key found for "${r}"`});let d=new AbortController,f=setTimeout(()=>d.abort(),y8),h,p=Date.now();try{let g=await xie(c,{messages:[{role:"user",content:"Reply with OK only.",timestamp:Date.now()}]},{apiKey:u.auth.apiKey,headers:u.auth.headers,maxTokens:16,timeoutMs:y8,maxRetries:0,cacheRetention:"none",signal:d.signal,onResponse:(v)=>{h=v.status}}),b=Date.now()-p;if(g.stopReason==="error"||g.stopReason==="aborted")return w.json({ok:!1,error:g.errorMessage??(d.signal.aborted?"Test timed out":"Model returned an error"),latencyMs:b,status:h});return w.json({ok:!0,latencyMs:b,status:h,responseText:Eie(g).slice(0,300)})}finally{clearTimeout(f)}}catch(n){return w.json({ok:!1,error:Die(n)},{status:500})}finally{if(t)yie(t,{recursive:!0,force:!0})}}var Iv={};Q(Iv,{GET:()=>Bie,POST:()=>Lie,dynamic:()=>Aie,fixtureDirFrom:()=>ae,readPlugins:()=>Ac});import{existsSync as C8,readFileSync as A8,statSync as Pv}from"node:fs";import{basename as Ov,dirname as Cc,extname as Sie,join as wf,relative as Cie}from"node:path";import{DefaultPackageManager as U8,getAgentDir as x8,SettingsManager as k8}from"@earendil-works/pi-coding-agent";function v8(e){return/^[!+-].+/.test(e.trim())}co();var Aie="force-dynamic";function Df(){return{extensions:0,skills:0,prompts:0,themes:0}}function R8(e){return e==="project"?"project":"global"}function Ef(e,t){return`${t}\x00${e}`}function Tf(e){return typeof e==="string"?e:e.source}function _8(e){if(typeof e==="string")return!1;return Array.isArray(e.extensions)&&e.extensions.length===0&&Array.isArray(e.skills)&&e.skills.length===0&&Array.isArray(e.prompts)&&e.prompts.length===0&&Array.isArray(e.themes)&&e.themes.length===0}function Uie(e){let t=new Map;for(let n of e.getGlobalSettings().packages??[])t.set(Ef(Tf(n),"global"),_8(n));for(let n of e.getProjectSettings().packages??[])t.set(Ef(Tf(n),"project"),_8(n));return t}function w8(e,t,n,r){let i=n==="project"?e.getProjectSettings().packages??[]:e.getGlobalSettings().packages??[],o=!1,s=i.map((a)=>{if(Tf(a)!==t)return a;if(o=!0,r)return{...typeof a==="string"?{source:a}:a,extensions:[],skills:[],prompts:[],themes:[]};return Tf(a)});if(!o)return!1;if(n==="project")e.setProjectPackages(s);else e.setPackages(s);return!0}function D8(e,t){e[t]+=1}function kie(e,t){let n=Ov(e),r=Sie(n);if(t==="skill"&&n.toLowerCase()==="skill.md")return Ov(Cc(e));if((t==="extension"||t==="theme"||t==="prompt")&&r){if(t==="extension"&&/^index\.(ts|js)$/.test(n))return Ov(Cc(e));return n.slice(0,-r.length)}return n}function Rie(e){let t=e.metadata.baseDir;if(!t)return e.path;let n=Cie(t,e.path);return n&&!n.startsWith("..")?n:e.path}function Fie(e){let t=e.startsWith("npm:")?e.slice(4):void 0;if(t){let n=t.lastIndexOf("@"),r=t.startsWith("@")?t.indexOf("/",1):0;if(n>r)return t.slice(n+1)||void 0;return}if(e.startsWith("git:")||/^[a-z]+:\/\//.test(e)){let n=e.lastIndexOf("@"),r=e.lastIndexOf("/"),i=e.lastIndexOf(":");if(n>Math.max(r,i))return e.slice(n+1)||void 0}return}function Oie(e){if(!e)return{};try{let n=Pv(e).isDirectory()?wf(e,"package.json"):wf(Cc(e),"package.json");if(!C8(n))return{};let r=JSON.parse(A8(n,"utf8"));return{packageName:typeof r.name==="string"?r.name:void 0,version:typeof r.version==="string"?r.version:void 0}}catch{return{}}}var E8=500;function Pie(e){if(!e)return null;try{let n=Pv(e).isDirectory()?wf(e,"README.md"):wf(Cc(e),"README.md");if(!C8(n)||!Pv(n).isFile())return null;let r=A8(n,"utf8"),i=r.slice(0,E8).trim();if(!i)return null;return{path:n,summary:r.length>E8?`${i}…`:i}}catch{return null}}function _f(e,t,n,r,i){if(!e.enabled||e.metadata.origin!=="package")return;let o=e.metadata.source,s=R8(e.metadata.scope),a=Ef(o,s),c=n.get(a)??Df();D8(c,t),D8(i,t),n.set(a,c);let u=r.get(a)??[],d=t==="extensions"?"extension":t==="skills"?"skill":t==="prompts"?"prompt":"theme";u.push({kind:d,name:kie(e.path,d),path:e.path,relativePath:Rie(e)}),r.set(a,u)}function Iie(e){let t=new Map,n=new Map,r=Df();for(let i of e.extensions)_f(i,"extensions",t,n,r);for(let i of e.skills)_f(i,"skills",t,n,r);for(let i of e.prompts)_f(i,"prompts",t,n,r);for(let i of e.themes)_f(i,"themes",t,n,r);return{countsByPackage:t,resourcesByPackage:n,totals:r}}function F8(e){return e?vt("settings.json",e)??x8():x8()}function Mie(e){let t=(e.getGlobalSettings().extensions??[]).map((r)=>({pattern:r,scope:"global"})),n=(e.getProjectSettings().extensions??[]).map((r)=>({pattern:r,scope:"project"}));return[...t,...n]}function T8(e,t,n){if(t==="project")e.setProjectExtensionPaths(n);else e.setExtensionPaths(n)}function S8(e,t){return(t==="project"?e.getProjectSettings():e.getGlobalSettings()).extensions??[]}async function Ac(e,t){let n=F8(t),r=ct(e,n),i=k8.create(e,n,{projectTrusted:r.trusted}),o=new U8({cwd:e,agentDir:n,settingsManager:i}),s=[],a=new Map,c=new Map,u=Df(),d=Uie(i);try{let h=await o.resolve(async(p)=>(s.push({type:"warning",source:p,message:"Package is configured but not installed yet."}),"skip"));({countsByPackage:a,resourcesByPackage:c,totals:u}=Iie(h))}catch(h){s.push({type:"error",message:h instanceof Error?h.message:String(h)})}return{packages:o.listConfiguredPackages().map((h)=>{let p=R8(h.scope),g=Ef(h.source,p),b=d.get(g)??!1,v=a.get(g)??Df(),m=c.get(g)??[],_=v.extensions+v.skills+v.prompts+v.themes,y=Oie(h.installedPath),x=Pie(h.installedPath);if(x)yt(Cc(x.path));if(!h.installedPath)s.push({type:"warning",source:h.source,message:"Configured package path was not found."});return{source:h.source,scope:p,filtered:h.filtered,disabled:b,installedPath:h.installedPath,packageName:y.packageName,version:y.version,configuredVersion:Fie(h.source),readmePath:x?.path,readmeSummary:x?.summary,counts:v,resources:m,status:b?"disabled":_>0?"loaded":h.installedPath?"installed":"missing"}}),extensionFilters:Mie(i),totals:u,diagnostics:s,projectResourcesLoaded:r.trusted}}function Nie(e){return e==="project"?"project":"global"}async function Bie(e){let{searchParams:t}=new URL(e.url),n=t.get("cwd");if(!n)return w.json({error:"cwd required"},{status:400});try{let r=await de();if(!be(n,r))return w.json({error:"Access denied"},{status:403});let i=await Ac(n,ae(e)),o=i.packages.filter((s)=>s.scope==="project");return w.json({...i,packages:o,extensionFilters:i.extensionFilters.filter((s)=>s.scope==="project"),totals:o.reduce((s,a)=>({extensions:s.extensions+a.counts.extensions,skills:s.skills+a.counts.skills,prompts:s.prompts+a.counts.prompts,themes:s.themes+a.counts.themes}),{extensions:0,skills:0,prompts:0,themes:0})})}catch(r){return w.json({error:String(r)},{status:500})}}async function Lie(e){if(!Tt(e))return w.json({error:"Untrusted API request"},{status:403});if(!Dr(e))return w.json({error:"Content-Type must be application/json"},{status:415});try{let t=await e.json();if(!t.cwd)return w.json({error:"cwd required"},{status:400});if(!t.action)return w.json({error:"action required"},{status:400});let n=await de();if(!be(t.cwd,n))return w.json({error:"Access denied"},{status:403});let r=ae(e),i=F8(r),o=ct(t.cwd,i),s=k8.create(t.cwd,i,{projectTrusted:o.trusted}),a=Nie(t.scope);if(a==="project"&&!o.trusted)return w.json({error:"Project resources must be trusted before modifying project plugins"},{status:403});let c=new U8({cwd:t.cwd,agentDir:i,settingsManager:s}),u=t.source?.trim(),d=a==="project";if(t.action==="install"){if(!u)return w.json({error:"source required"},{status:400});await c.installAndPersist(u,{local:d})}else if(t.action==="remove"){if(!u)return w.json({error:"source required"},{status:400});await c.removeAndPersist(u,{local:d})}else if(t.action==="update")await c.update(u);else if(t.action==="disable"){if(!u)return w.json({error:"source required"},{status:400});w8(s,u,a,!0),await s.flush()}else if(t.action==="enable"){if(!u)return w.json({error:"source required"},{status:400});w8(s,u,a,!1),await s.flush()}else if(t.action==="addExtensionFilter"){if(!u)return w.json({error:"pattern required"},{status:400});if(!v8(u))return w.json({error:`Invalid extension filter "${u}": must start with !, +, or - (plain paths have no effect in the extensions field)`},{status:400});let f=S8(s,a);if(f.includes(u))return w.json({error:`Extension filter already exists: ${u}`},{status:400});T8(s,a,[...f,u]),await s.flush()}else if(t.action==="removeExtensionFilter"){if(!u)return w.json({error:"pattern required"},{status:400});let f=S8(s,a),h=f.filter((p)=>p!==u);if(h.length===f.length)return w.json({error:`Extension filter not found: ${u}`},{status:400});T8(s,a,h),await s.flush()}else return w.json({error:`Unsupported action: ${t.action}`},{status:400});return w.json(await Ac(t.cwd,r))}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var Mv={};Q(Mv,{GET:()=>qie,dynamic:()=>jie});import{getAgentDir as Wie}from"@earendil-works/pi-coding-agent";var jie="force-dynamic";async function qie(e){let t=ae(e);try{return w.json(await Ac(t??Wie(),t))}catch(n){return w.json({error:String(n)},{status:500})}}var Nv={};Q(Nv,{GET:()=>$ie,PUT:()=>Hie});async function $ie(e){return w.json(ti(ae(e)))}async function Hie(e){try{let t=await e.json(),n=ae(e);if(t.firstPaint&&typeof t.firstPaint==="object")_3(t.firstPaint,n);if(t.preferences&&typeof t.preferences==="object")ev(t.preferences,n);return w.json(ti(n))}catch{return w.json({error:"invalid body"},{status:400})}}var Bv={};Q(Bv,{GET:()=>Xie,POST:()=>Kie,dynamic:()=>Vie});import{stat as Gie}from"node:fs/promises";import{resolve as zie}from"node:path";import{getAgentDir as O8}from"@earendil-works/pi-coding-agent";var Vie="force-dynamic";async function P8(e){if(typeof e!=="string"||!e.trim())return{response:w.json({error:"cwd required"},{status:400})};let t=zie($e(e));try{if(!(await Gie(t)).isDirectory())return{response:w.json({error:"cwd must be a directory"},{status:400})}}catch{return{response:w.json({error:"Directory does not exist"},{status:400})}}let n=await de();if(!be(t,n))return{response:w.json({error:"Access denied"},{status:403})};return{cwd:t}}async function Xie(e){let t=new URL(e.url),n=t.searchParams.get("piE2eTrustCwd");if(n){for(let i of n.split(","))if(i.trim())yt(i.trim())}let r=await P8(t.searchParams.get("cwd"));if("response"in r)return r.response;return w.json(ct(r.cwd,O8()))}async function Kie(e){try{let t=await e.json(),n=await P8(t.cwd);if("response"in n)return n.response;let r=O8();if(!ct(n.cwd,r).requiresTrust)return w.json({error:"This project has no resources that require trust"},{status:409});if(K2(n.cwd))return w.json({error:"Wait for the active session to finish before trusting this project"},{status:409});let o=M2(n.cwd,r);return ke(),Y2(n.cwd),w.json(o)}catch(t){return w.json({error:t instanceof Error?t.message:String(t)},{status:500})}}var Wv={};Q(Wv,{POST:()=>ooe});import{Agent as Zie}from"@earendil-works/pi-agent-core";var Yie=90000,I8=80,Lv=`Create a concise title for this session based on the conversation above.
353
353
 
354
354
  Requirements:
@@ -1,4 +1,4 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,s as n}from"./index-CDxi_40j.js";var r=e(t(),1),i=[],a=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?a:i).push(n+=e[t])})();function o(e){if(e<768)return!1;for(let t=0,n=i.length;;){let r=t+n>>1;if(e<i[r])n=r;else if(e>=a[r])t=r+1;else return!0;if(t==n)return!1}}function s(e){return e>=127462&&e<=127487}var c=8205;function l(e,t,n=!0,r=!0){return(n?u:d)(e,t,r)}function u(e,t,n){if(t==e.length)return t;t&&p(e.charCodeAt(t))&&m(e.charCodeAt(t-1))&&t--;let r=f(e,t);for(t+=h(r);t<e.length;){let i=f(e,t);if(r==c||i==c||n&&o(i))t+=h(i),r=i;else if(s(i)){let n=0,r=t-2;for(;r>=0&&s(f(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function d(e,t,n){for(;t>1;){let r=u(e,t-2,n);if(r<t)return r;t--}return 0}function f(e,t){let n=e.charCodeAt(t);if(!m(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return p(r)?(n-55296<<10)+(r-56320)+65536:n}function p(e){return e>=56320&&e<57344}function m(e){return e>=55296&&e<56320}function h(e){return e<65536?1:2}var g=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=ae(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),v.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ae(this,e,t);let n=[];return this.decompose(e,t,n,0),v.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new b(this),i=new b(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new b(this,e)}iterRange(e,t=this.length){return new ne(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new re(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new _(t):v.from(_.split(t,[]))}},_=class e extends g{constructor(e,t=y(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new ie(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(te(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=ee(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=ae(this,t,n);let i=ee(this.text,ee(r.text,te(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):v.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,s as n}from"./index-DoEQcOYk.js";var r=e(t(),1),i=[],a=[];(()=>{let e=`lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5`.split(`,`).map(e=>e?parseInt(e,36):1);for(let t=0,n=0;t<e.length;t++)(t%2?a:i).push(n+=e[t])})();function o(e){if(e<768)return!1;for(let t=0,n=i.length;;){let r=t+n>>1;if(e<i[r])n=r;else if(e>=a[r])t=r+1;else return!0;if(t==n)return!1}}function s(e){return e>=127462&&e<=127487}var c=8205;function l(e,t,n=!0,r=!0){return(n?u:d)(e,t,r)}function u(e,t,n){if(t==e.length)return t;t&&p(e.charCodeAt(t))&&m(e.charCodeAt(t-1))&&t--;let r=f(e,t);for(t+=h(r);t<e.length;){let i=f(e,t);if(r==c||i==c||n&&o(i))t+=h(i),r=i;else if(s(i)){let n=0,r=t-2;for(;r>=0&&s(f(e,r));)n++,r-=2;if(n%2==0)break;t+=2}else break}return t}function d(e,t,n){for(;t>1;){let r=u(e,t-2,n);if(r<t)return r;t--}return 0}function f(e,t){let n=e.charCodeAt(t);if(!m(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return p(r)?(n-55296<<10)+(r-56320)+65536:n}function p(e){return e>=56320&&e<57344}function m(e){return e>=55296&&e<56320}function h(e){return e<65536?1:2}var g=class e{lineAt(e){if(e<0||e>this.length)throw RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=ae(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),v.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ae(this,e,t);let n=[];return this.decompose(e,t,n,0),v.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new b(this),i=new b(e);for(let e=t,a=t;;){if(r.next(e),i.next(e),e=0,r.lineBreak!=i.lineBreak||r.done!=i.done||r.value!=i.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new b(this,e)}iterRange(e,t=this.length){return new ne(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t??=this.lines+1;let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new re(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(t){if(t.length==0)throw RangeError(`A document must have at least one line`);return t.length==1&&!t[0]?e.empty:t.length<=32?new _(t):v.from(_.split(t,[]))}},_=class e extends g{constructor(e,t=y(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.text[i],o=r+a.length;if((t?n:o)>=e)return new ie(r,o,n,a);r=o+1,n++}}decompose(t,n,r,i){let a=t<=0&&n>=this.length?this:new e(te(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(i&1){let t=r.pop(),n=ee(a.text,t.text.slice(),0,a.length);if(n.length<=32)r.push(new e(n,t.length+a.length));else{let t=n.length>>1;r.push(new e(n.slice(0,t)),new e(n.slice(t)))}}else r.push(a)}replace(t,n,r){if(!(r instanceof e))return super.replace(t,n,r);[t,n]=ae(this,t,n);let i=ee(this.text,ee(r.text,te(this.text,0,t)),n),a=this.length+r.length-(n-t);return i.length<=32?new e(i,a):v.from(e.split(i,[]),a)}sliceString(e,t=this.length,n=`
2
2
  `){[e,t]=ae(this,e,t);let r=``;for(let i=0,a=0;i<=t&&a<this.text.length;a++){let o=this.text[a],s=i+o.length;i>e&&a&&(r+=n),e<s&&t>i&&(r+=o.slice(Math.max(0,e-i),t-i)),i=s+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(t,n){let r=[],i=-1;for(let a of t)r.push(a),i+=a.length+1,r.length==32&&(n.push(new e(r,i)),r=[],i=-1);return i>-1&&n.push(new e(r,i)),n}},v=class e extends g{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let t of e)this.lines+=t.lines}lineInner(e,t,n,r){for(let i=0;;i++){let a=this.children[i],o=r+a.length,s=n+a.lines-1;if((t?s:o)>=e)return a.lineInner(e,t,n,r);r=o+1,n=s+1}}decompose(e,t,n,r){for(let i=0,a=0;a<=t&&i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(e<=s&&t>=a){let i=r&(a<=e|(s>=t?2:0));a>=e&&s<=t&&!i?n.push(o):o.decompose(e-a,t-a,n,i)}a=s+1}}replace(t,n,r){if([t,n]=ae(this,t,n),r.lines<this.lines)for(let i=0,a=0;i<this.children.length;i++){let o=this.children[i],s=a+o.length;if(t>=a&&n<=s){let c=o.replace(t-a,n-a,r),l=this.lines-o.lines+c.lines;if(c.lines<l>>4&&c.lines>l>>6){let a=this.children.slice();return a[i]=c,new e(a,this.length-(n-t)+r.length)}return super.replace(a,s,c)}a=s+1}return super.replace(t,n,r)}sliceString(e,t=this.length,n=`
3
3
  `){[e,t]=ae(this,e,t);let r=``;for(let i=0,a=0;i<this.children.length&&a<=t;i++){let o=this.children[i],s=a+o.length;a>e&&i&&(r+=n),e<s&&t>a&&(r+=o.sliceString(e-a,t-a,n)),a=s+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(t,n){if(!(t instanceof e))return 0;let r=0,[i,a,o,s]=n>0?[0,0,this.children.length,t.children.length]:[this.children.length-1,t.children.length-1,-1,-1];for(;;i+=n,a+=n){if(i==o||a==s)return r;let e=this.children[i],c=t.children[a];if(e!=c)return r+e.scanIdentical(c,n);r+=e.length+1}}static from(t,n=t.reduce((e,t)=>e+t.length+1,-1)){let r=0;for(let e of t)r+=e.lines;if(r<32){let e=[];for(let n of t)n.flatten(e);return new _(e,n)}let i=Math.max(32,r>>5),a=i<<1,o=i>>1,s=[],c=0,l=-1,u=[];function d(t){let n;if(t.lines>a&&t instanceof e)for(let e of t.children)d(e);else t.lines>o&&(c>o||!c)?(f(),s.push(t)):t instanceof _&&c&&(n=u[u.length-1])instanceof _&&t.lines+n.lines<=32?(c+=t.lines,l+=t.length+1,u[u.length-1]=new _(n.text.concat(t.text),n.length+1+t.length)):(c+t.lines>i&&f(),c+=t.lines,l+=t.length+1,u.push(t))}function f(){c!=0&&(s.push(u.length==1?u[0]:e.from(u,l)),l=-1,c=u.length=0)}for(let e of t)d(e);return f(),s.length==1?s[0]:new e(s,n)}};g.empty=new _([``],0);function y(e){let t=-1;for(let n of e)t+=n.length+1;return t}function ee(e,t,n=0,r=1e9){for(let i=0,a=0,o=!0;a<e.length&&i<=r;a++){let s=e[a],c=i+s.length;c>=n&&(c>r&&(s=s.slice(0,r-i)),i<n&&(s=s.slice(n-i)),o?(t[t.length-1]+=s,o=!1):t.push(s)),i=c+1}return t}function te(e,t,n){return ee(e,[``],t,n)}var b=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value=``,this.nodes=[e],this.offsets=[t>0?1:(e instanceof _?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,r=this.nodes[n],i=this.offsets[n],a=i>>1,o=r instanceof _?r.text.length:r.children.length;if(a==(t>0?o:0)){if(n==0)return this.done=!0,this.value=``,this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((i&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=`
4
4
  `,this;e--}else if(r instanceof _){let i=r.text[a+(t<0?-1:0)];if(this.offsets[n]+=t,i.length>Math.max(0,e))return this.value=e==0?i:t>0?i.slice(e):i.slice(0,i.length-e),this;e-=i.length}else{let i=r.children[a+(t<0?-1:0)];e>i.length?(e-=i.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(i),this.offsets.push(t>0?1:(i instanceof _?i.text.length:i.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},ne=class{constructor(e,t,n){this.value=``,this.done=!1,this.cursor=new b(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value=``,this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=n?r:t<0?r.slice(r.length-n):r.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=``}},re=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value=``,this.done=!1}next(e=0){let{done:t,lineBreak:n,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value=``,this.afterBreak=!1):t?(this.done=!0,this.value=``):n?this.afterBreak?this.value=``:(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<`u`&&(g.prototype[Symbol.iterator]=function(){return this.iter()},b.prototype[Symbol.iterator]=ne.prototype[Symbol.iterator]=re.prototype[Symbol.iterator]=function(){return this});var ie=class{constructor(e,t,n,r){this.from=e,this.to=t,this.number=n,this.text=r}get length(){return this.to-this.from}};function ae(e,t,n){return t=Math.max(0,Math.min(e.length,t)),[t,Math.max(t,Math.min(e.length,n))]}function x(e,t,n=!0,r=!0){return l(e,t,n,r)}function oe(e){return e>=56320&&e<57344}function se(e){return e>=55296&&e<56320}function S(e,t){let n=e.charCodeAt(t);if(!se(n)||t+1==e.length)return n;let r=e.charCodeAt(t+1);return oe(r)?(n-55296<<10)+(r-56320)+65536:n}function ce(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}function le(e){return e<65536?1:2}var ue=/\r\n?|\n/,C=(function(e){return e[e.Simple=0]=`Simple`,e[e.TrackDel=1]=`TrackDel`,e[e.TrackBefore=2]=`TrackBefore`,e[e.TrackAfter=3]=`TrackAfter`,e})(C||={}),de=class e{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t+1];e+=n<0?this.sections[t]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,n=0,r=0;t<this.sections.length;){let i=this.sections[t++],a=this.sections[t++];a<0?(e(n,r,i),r+=i):r+=a,n+=i}}iterChangedRanges(e,t=!1){me(this,e,t)}get invertedDesc(){let t=[];for(let e=0;e<this.sections.length;){let n=this.sections[e++],r=this.sections[e++];r<0?t.push(n,r):t.push(r,n)}return new e(t)}composeDesc(e){return this.empty?e:e.empty?this:ge(this,e)}mapDesc(e,t=!1){return e.empty?this:he(this,e,t)}mapPos(e,t=-1,n=C.Simple){let r=0,i=0;for(let a=0;a<this.sections.length;){let o=this.sections[a++],s=this.sections[a++],c=r+o;if(s<0){if(c>e)return i+(e-r);i+=o}else{if(n!=C.Simple&&c>=e&&(n==C.TrackDel&&r<e&&c>e||n==C.TrackBefore&&r<e||n==C.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!o)return e==r||t<0?i:i+s;i+=s}r=c}if(e>r)throw RangeError(`Position ${e} is out of range for changeset of length ${r}`);return i}touchesRange(e,t=e){for(let n=0,r=0;n<this.sections.length&&r<=t;){let i=this.sections[n++],a=this.sections[n++],o=r+i;if(a>=0&&r<=t&&o>=e)return r<e&&o>t?`cover`:!0;r=o}return!1}toString(){let e=``;for(let t=0;t<this.sections.length;){let n=this.sections[t++],r=this.sections[t++];e+=(e?` `:``)+n+(r>=0?`:`+r:``)}return e}toJSON(){return this.sections}static fromJSON(t){if(!Array.isArray(t)||t.length%2||t.some(e=>typeof e!=`number`))throw RangeError(`Invalid JSON representation of ChangeDesc`);return new e(t)}static create(t){return new e(t)}},fe=class e extends de{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw RangeError(`Applying change set to a document with the wrong length`);return me(this,(t,n,r,i,a)=>e=e.replace(r,r+(n-t),a),!1),e}mapDesc(e,t=!1){return he(this,e,t,!0)}invert(t){let n=this.sections.slice(),r=[];for(let e=0,i=0;e<n.length;e+=2){let a=n[e],o=n[e+1];if(o>=0){n[e]=o,n[e+1]=a;let s=e>>1;for(;r.length<s;)r.push(g.empty);r.push(a?t.slice(i,i+a):g.empty)}i+=a}return new e(n,r)}compose(e){return this.empty?e:e.empty?this:ge(this,e,!0)}map(e,t=!1){return e.empty?this:he(this,e,t,!0)}iterChanges(e,t=!1){me(this,e,t)}get desc(){return de.create(this.sections)}filter(t){let n=[],r=[],i=[],a=new _e(this);done:for(let e=0,o=0;;){let s=e==t.length?1e9:t[e++];for(;o<s||o==s&&a.len==0;){if(a.done)break done;let e=Math.min(a.len,s-o);w(i,e,-1);let t=a.ins==-1?-1:a.off==0?a.ins:0;w(n,e,t),t>0&&pe(r,n,a.text),a.forward(e),o+=e}let c=t[e++];for(;o<c;){if(a.done)break done;let e=Math.min(a.len,c-o);w(n,e,-1),w(i,e,a.ins==-1?-1:a.off==0?a.ins:0),a.forward(e),o+=e}}return{changes:new e(n,r),filtered:de.create(i)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t],r=this.sections[t+1];r<0?e.push(n):r==0?e.push([n]):e.push([n].concat(this.inserted[t>>1].toJSON()))}return e}static of(t,n,r){let i=[],a=[],o=0,s=null;function c(t=!1){if(!t&&!i.length)return;o<n&&w(i,n-o,-1);let r=new e(i,a);s=s?s.compose(r.map(s)):r,i=[],a=[],o=0}function l(t){if(Array.isArray(t))for(let e of t)l(e);else if(t instanceof e){if(t.length!=n)throw RangeError(`Mismatched change set length (got ${t.length}, expected ${n})`);c(),s=s?s.compose(t.map(s)):t}else{let{from:e,to:s=e,insert:l}=t;if(e>s||e<0||s>n)throw RangeError(`Invalid change range ${e} to ${s} (in doc of length ${n})`);let u=l?typeof l==`string`?g.of(l.split(r||ue)):l:g.empty,d=u.length;if(e==s&&d==0)return;e<o&&c(),e>o&&w(i,e-o,-1),w(i,s-e,d),pe(a,i,u),o=s}}return l(t),c(!s),s}static empty(t){return new e(t?[t,-1]:[],[])}static fromJSON(t){if(!Array.isArray(t))throw RangeError(`Invalid JSON representation of ChangeSet`);let n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i==`number`)n.push(i,-1);else if(!Array.isArray(i)||typeof i[0]!=`number`||i.some((e,t)=>t&&typeof e!=`string`))throw RangeError(`Invalid JSON representation of ChangeSet`);else if(i.length==1)n.push(i[0],0);else{for(;r.length<e;)r.push(g.empty);r[e]=g.of(i.slice(1)),n.push(i[0],r[e].length)}}return new e(n,r)}static createSet(t,n){return new e(t,n)}};function w(e,t,n,r=!1){if(t==0&&n<=0)return;let i=e.length-2;i>=0&&n<=0&&n==e[i+1]?e[i]+=t:i>=0&&t==0&&e[i]==0?e[i+1]+=n:r?(e[i]+=t,e[i+1]+=n):e.push(t,n)}function pe(e,t,n){if(n.length==0)return;let r=t.length-2>>1;if(r<e.length)e[e.length-1]=e[e.length-1].append(n);else{for(;e.length<r;)e.push(g.empty);e.push(n)}}function me(e,t,n){let r=e.inserted;for(let i=0,a=0,o=0;o<e.sections.length;){let s=e.sections[o++],c=e.sections[o++];if(c<0)i+=s,a+=s;else{let l=i,u=a,d=g.empty;for(;l+=s,u+=c,c&&r&&(d=d.append(r[o-2>>1])),!(n||o==e.sections.length||e.sections[o+1]<0);)s=e.sections[o++],c=e.sections[o++];t(i,l,a,u,d),i=l,a=u}}}function he(e,t,n,r=!1){let i=[],a=r?[]:null,o=new _e(e),s=new _e(t);for(let e=-1;;)if(o.done&&s.len||s.done&&o.len)throw Error(`Mismatched change set lengths`);else if(o.ins==-1&&s.ins==-1){let e=Math.min(o.len,s.len);w(i,e,-1),o.forward(e),s.forward(e)}else if(s.ins>=0&&(o.ins<0||e==o.i||o.off==0&&(s.len<o.len||s.len==o.len&&!n))){let t=s.len;for(w(i,s.ins,-1);t;){let n=Math.min(o.len,t);o.ins>=0&&e<o.i&&o.len<=n&&(w(i,0,o.ins),a&&pe(a,i,o.text),e=o.i),o.forward(n),t-=n}s.next()}else if(o.ins>=0){let t=0,n=o.len;for(;n;)if(s.ins==-1){let e=Math.min(n,s.len);t+=e,n-=e,s.forward(e)}else if(s.ins==0&&s.len<n)n-=s.len,s.next();else break;w(i,t,e<o.i?o.ins:0),a&&e<o.i&&pe(a,i,o.text),e=o.i,o.forward(o.len-n)}else if(o.done&&s.done)return a?fe.createSet(i,a):de.create(i);else throw Error(`Mismatched change set lengths`)}function ge(e,t,n=!1){let r=[],i=n?[]:null,a=new _e(e),o=new _e(t);for(let e=!1;;)if(a.done&&o.done)return i?fe.createSet(r,i):de.create(r);else if(a.ins==0)w(r,a.len,0,e),a.next();else if(o.len==0&&!o.done)w(r,0,o.ins,e),i&&pe(i,r,o.text),o.next();else if(a.done||o.done)throw Error(`Mismatched change set lengths`);else{let t=Math.min(a.len2,o.len),n=r.length;if(a.ins==-1){let n=o.ins==-1?-1:o.off?0:o.ins;w(r,t,n,e),i&&n&&pe(i,r,o.text)}else o.ins==-1?(w(r,a.off?0:a.len,t,e),i&&pe(i,r,a.textBit(t))):(w(r,a.off?0:a.len,o.off?0:o.ins,e),i&&!o.off&&pe(i,r,o.text));e=(a.ins>t||o.ins>=0&&o.len>t)&&(e||r.length>n),a.forward2(t),o.forward(t)}}var _e=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?g.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?g.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},ve=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.flags=n,this.goalColumn=r}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(t,n=-1){let r,i;return this.empty?r=i=t.mapPos(this.from,n):(r=t.mapPos(this.from,1),i=t.mapPos(this.to,-1)),r==this.from&&i==this.to?this:new e(r,i,this.flags,this.goalColumn)}extend(e,t=e,n=0){if(e<=this.anchor&&t>=this.anchor)return T.range(e,t,void 0,void 0,n);let r=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return T.range(this.anchor,r,void 0,void 0,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!=`number`||typeof e.head!=`number`)throw RangeError(`Invalid JSON representation for SelectionRange`);return T.range(e.anchor,e.head)}static create(t,n,r,i){return new e(t,n,r,i)}},T=class e{constructor(e,t){this.ranges=e,this.mainIndex=t}map(t,n=-1){return t.empty?this:e.create(this.ranges.map(e=>e.map(t,n)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new e([this.main],0)}addRange(t,n=!0){return e.create([t].concat(this.ranges),n?0:this.mainIndex+1)}replaceRange(t,n=this.mainIndex){let r=this.ranges.slice();return r[n]=t,e.create(r,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(t){if(!t||!Array.isArray(t.ranges)||typeof t.main!=`number`||t.main>=t.ranges.length)throw RangeError(`Invalid JSON representation for EditorSelection`);return new e(t.ranges.map(e=>ve.fromJSON(e)),t.main)}static single(t,n=t){return new e([e.range(t,n)],0)}static create(t,n=0){if(t.length==0)throw RangeError(`A selection needs at least one range`);for(let r=0,i=0;i<t.length;i++){let a=t[i];if(a.empty?a.from<=r:a.from<r)return e.normalized(t.slice(),n);r=a.to}return new e(t,n)}static cursor(e,t=0,n,r){return ve.create(e,e,(t==0?0:t<0?8:16)|(n==null?7:Math.min(6,n)),r)}static range(e,t,n,r,i){let a=r==null?7:Math.min(6,r);return!i&&e!=t&&(i=t<e?1:-1),i&&(a|=i<0?8:16),t<e?ve.create(t,e,a|32,n):ve.create(e,t,a,n)}static undirectionalRange(e,t){return ve.create(e,t,64,void 0)}static normalized(t,n=0){let r=t[n];t.sort((e,t)=>e.from-t.from),n=t.indexOf(r);for(let r=1;r<t.length;r++){let i=t[r],a=t[r-1];if(i.empty?i.from<=a.to:i.from<a.to){let o=a.from,s=Math.max(i.to,a.to);r<=n&&n--,t.splice(--r,2,i.anchor>i.head?e.range(s,o):e.range(o,s))}}return new e(t,n)}};function ye(e,t){for(let n of e.ranges)if(n.to>t)throw RangeError(`Selection points outside of document`)}var be=0,E=class e{constructor(e,t,n,r,i){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=r,this.id=be++,this.default=e([]),this.extensions=typeof i==`function`?i(this):i}get reader(){return this}static define(t={}){return new e(t.combine||(e=>e),t.compareInput||((e,t)=>e===t),t.compare||(t.combine?(e,t)=>e===t:xe),!!t.static,t.enables)}of(e){return new Se([],this,0,e)}compute(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new Se(e,this,1,t)}computeN(e,t){if(this.isStatic)throw Error(`Can't compute a static facet`);return new Se(e,this,2,t)}from(e,t){return t||=e=>e,this.compute([e],n=>t(n.field(e)))}};function xe(e,t){return e==t||e.length==t.length&&e.every((e,n)=>e===t[n])}var Se=class{constructor(e,t,n,r){this.dependencies=e,this.facet=t,this.type=n,this.value=r,this.id=be++}dynamicSlot(e){let t=this.value,n=this.facet.compareInput,r=this.id,i=e[r]>>1,a=this.type==2,o=!1,s=!1,c=[];for(let t of this.dependencies)t==`doc`?o=!0:t==`selection`?s=!0:(e[t.id]??1)&1||c.push(e[t.id]);return{create(e){return e.values[i]=t(e),1},update(e,r){if(o&&r.docChanged||s&&(r.docChanged||r.selection)||we(e,c)){let r=t(e);if(a?!Ce(r,e.values[i],n):!n(r,e.values[i]))return e.values[i]=r,1}return 0},reconfigure:(e,o)=>{let s,c=o.config.address[r];if(c!=null){let r=Le(o,c);if(this.dependencies.every(t=>t instanceof E?o.facet(t)===e.facet(t):t instanceof De?o.field(t,!1)==e.field(t,!1):!0)||(a?Ce(s=t(e),r,n):n(s=t(e),r)))return e.values[i]=r,0}else s=t(e);return e.values[i]=s,1}}}get extension(){return this}};function Ce(e,t,n){if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!n(e[r],t[r]))return!1;return!0}function we(e,t){let n=!1;for(let r of t)Ie(e,r)&1&&(n=!0);return n}function Te(e,t,n){let r=n.map(t=>e[t.id]),i=n.map(e=>e.type),a=r.filter(e=>!(e&1)),o=e[t.id]>>1;function s(e){let n=[];for(let t=0;t<r.length;t++){let a=Le(e,r[t]);if(i[t]==2)for(let e of a)n.push(e);else n.push(a)}return t.combine(n)}return{create(e){for(let t of r)Ie(e,t);return e.values[o]=s(e),1},update(e,n){if(!we(e,a))return 0;let r=s(e);return t.compare(r,e.values[o])?0:(e.values[o]=r,1)},reconfigure(e,i){let a=we(e,r),c=i.config.facets[t.id],l=i.facet(t);if(c&&!a&&xe(n,c))return e.values[o]=l,0;let u=s(e);return t.compare(u,l)?(e.values[o]=l,0):(e.values[o]=u,1)}}}var Ee=E.define({static:!0}),De=class e{constructor(e,t,n,r,i){this.id=e,this.createF=t,this.updateF=n,this.compareF=r,this.spec=i,this.provides=void 0}static define(t){let n=new e(be++,t.create,t.update,t.compare||((e,t)=>e===t),t);return t.provide&&(n.provides=t.provide(n)),n}create(e){return(e.facet(Ee).find(e=>e.field==this)?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:e=>(e.values[t]=this.create(e),1),update:(e,n)=>{let r=e.values[t],i=this.updateF(r,n);return this.compareF(r,i)?0:(e.values[t]=i,1)},reconfigure:(e,n)=>{let r=e.facet(Ee),i=n.facet(Ee),a;return(a=r.find(e=>e.field==this))&&a!=i.find(e=>e.field==this)?(e.values[t]=a.create(e),1):n.config.address[this.id]==null?(e.values[t]=this.create(e),1):(e.values[t]=n.field(this),0)}}}init(e){return[this,Ee.of({field:this,create:e})]}get extension(){return this}},Oe={lowest:4,low:3,default:2,high:1,highest:0};function ke(e){return t=>new je(t,e)}var Ae={highest:ke(Oe.highest),high:ke(Oe.high),default:ke(Oe.default),low:ke(Oe.low),lowest:ke(Oe.lowest)},je=class{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}},Me=class e{of(e){return new Ne(this,e)}reconfigure(t){return e.reconfigure.of({compartment:this,extension:t})}get(e){return e.config.compartments.get(this)}},Ne=class{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}},Pe=class e{constructor(e,t,n,r,i,a){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=r,this.staticValues=i,this.facets=a,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(t,n,r){let i=[],a=Object.create(null),o=new Map;for(let e of Fe(t,n,o))e instanceof De?i.push(e):(a[e.facet.id]||(a[e.facet.id]=[])).push(e);let s=Object.create(null),c=[],l=[];for(let e of i)s[e.id]=l.length<<1,l.push(t=>e.slot(t));let u=r?.config.facets;for(let e in a){let t=a[e],n=t[0].facet,i=u&&u[e]||[];if(t.every(e=>e.type==0)){if(s[n.id]=c.length<<1|1,xe(i,t))c.push(r.facet(n));else{let e=n.combine(t.map(e=>e.value));c.push(r&&n.compare(e,r.facet(n))?r.facet(n):e)}}else{for(let e of t)e.type==0?(s[e.id]=c.length<<1|1,c.push(e.value)):(s[e.id]=l.length<<1,l.push(t=>e.dynamicSlot(t)));s[n.id]=l.length<<1,l.push(e=>Te(e,n,t))}}let d=l.map(e=>e(s));return new e(t,o,d,s,c,a)}};function Fe(e,t,n){let r=[[],[],[],[],[]],i=new Map;function a(e,o){let s=i.get(e);if(s!=null){if(s<=o)return;let t=r[s].indexOf(e);t>-1&&r[s].splice(t,1),e instanceof Ne&&n.delete(e.compartment)}if(i.set(e,o),Array.isArray(e))for(let t of e)a(t,o);else if(e instanceof Ne){if(n.has(e.compartment))throw RangeError(`Duplicate use of compartment in extensions`);let r=t.get(e.compartment)||e.inner;n.set(e.compartment,r),a(r,o)}else if(e instanceof je)a(e.inner,e.prec);else if(e instanceof De)r[o].push(e),e.provides&&a(e.provides,o);else if(e instanceof Se)r[o].push(e),e.facet.extensions&&a(e.facet.extensions,Oe.default);else{let t=e.extension;if(!t)throw Error(`Unrecognized extension value in extension set (${e}).`);if(t==e)throw Error(`Unrecognized extension value in extension set (${e}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);a(t,o)}}return a(e,Oe.default),r.reduce((e,t)=>e.concat(t))}function Ie(e,t){if(t&1)return 2;let n=t>>1,r=e.status[n];if(r==4)throw Error(`Cyclic dependency between fields and/or facets`);if(r&2)return r;e.status[n]=4;let i=e.computeSlot(e,e.config.dynamicSlots[n]);return e.status[n]=2|i}function Le(e,t){return t&1?e.config.staticValues[t>>1]:e.values[t>>1]}var Re=E.define(),ze=E.define({combine:e=>e.some(e=>e),static:!0}),Be=E.define({combine:e=>e.length?e[0]:void 0,static:!0}),Ve=E.define(),He=E.define(),Ue=E.define(),We=E.define({combine:e=>e.length?e[0]:!1}),Ge=class{constructor(e,t){this.type=e,this.value=t}static define(){return new Ke}},Ke=class{of(e){return new Ge(this,e)}},qe=class{constructor(e){this.map=e}of(e){return new D(this,e)}},D=class e{constructor(e,t){this.type=e,this.value=t}map(t){let n=this.type.map(this.value,t);return n===void 0?void 0:n==this.value?this:new e(this.type,n)}is(e){return this.type==e}static define(e={}){return new qe(e.map||(e=>e))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let r of e){let e=r.map(t);e&&n.push(e)}return n}};D.reconfigure=D.define(),D.appendConfig=D.define();var Je=class e{constructor(t,n,r,i,a,o){this.startState=t,this.changes=n,this.selection=r,this.effects=i,this.annotations=a,this.scrollIntoView=o,this._doc=null,this._state=null,r&&ye(r,n.newLength),a.some(t=>t.type==e.time)||(this.annotations=a.concat(e.time.of(Date.now())))}static create(t,n,r,i,a,o){return new e(t,n,r,i,a,o)}get newDoc(){return this._doc||=this.changes.apply(this.startState.doc)}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(t){let n=this.annotation(e.userEvent);return!!(n&&(n==t||n.length>t.length&&n.slice(0,t.length)==t&&n[t.length]==`.`))}};Je.time=Ge.define(),Je.userEvent=Ge.define(),Je.addToHistory=Ge.define(),Je.remote=Ge.define();function Ye(e,t){let n=[];for(let r=0,i=0;;){let a,o;if(r<e.length&&(i==t.length||t[i]>=e[r]))a=e[r++],o=e[r++];else if(i<t.length)a=t[i++],o=t[i++];else return n;!n.length||n[n.length-1]<a?n.push(a,o):n[n.length-1]<o&&(n[n.length-1]=o)}}function Xe(e,t,n){let r,i,a;return n?(r=t.changes,i=fe.empty(t.changes.length),a=e.changes.compose(t.changes)):(r=t.changes.map(e.changes),i=e.changes.mapDesc(t.changes,!0),a=e.changes.compose(r)),{changes:a,selection:t.selection?t.selection.map(i):e.selection?.map(r),effects:D.mapEffects(e.effects,r).concat(D.mapEffects(t.effects,i)),annotations:e.annotations.length?e.annotations.concat(t.annotations):t.annotations,scrollIntoView:e.scrollIntoView||t.scrollIntoView}}function Ze(e,t,n){let r=t.selection,i=nt(t.annotations);return t.userEvent&&(i=i.concat(Je.userEvent.of(t.userEvent))),{changes:t.changes instanceof fe?t.changes:fe.of(t.changes||[],n,e.facet(Be)),selection:r&&(r instanceof T?r:T.single(r.anchor,r.head)),effects:nt(t.effects),annotations:i,scrollIntoView:!!t.scrollIntoView}}function Qe(e,t,n){let r=Ze(e,t.length?t[0]:{},e.doc.length);t.length&&t[0].filter===!1&&(n=!1);for(let i=1;i<t.length;i++){t[i].filter===!1&&(n=!1);let a=!!t[i].sequential;r=Xe(r,Ze(e,t[i],a?r.changes.newLength:e.doc.length),a)}let i=Je.create(e,r.changes,r.selection,r.effects,r.annotations,r.scrollIntoView);return et(n?$e(i):i)}function $e(e){let t=e.startState,n=!0;for(let r of t.facet(Ve)){let t=r(e);if(t===!1){n=!1;break}Array.isArray(t)&&(n=n===!0?t:Ye(n,t))}if(n!==!0){let r,i;if(n===!1)i=e.changes.invertedDesc,r=fe.empty(t.doc.length);else{let t=e.changes.filter(n);r=t.changes,i=t.filtered.mapDesc(t.changes).invertedDesc}e=Je.create(t,r,e.selection&&e.selection.map(i),D.mapEffects(e.effects,i),e.annotations,e.scrollIntoView)}let r=t.facet(He);for(let n=r.length-1;n>=0;n--){let i=r[n](e);e=i instanceof Je?i:Array.isArray(i)&&i.length==1&&i[0]instanceof Je?i[0]:Qe(t,nt(i),!1)}return e}function et(e){let t=e.startState,n=t.facet(Ue),r=e;for(let i=n.length-1;i>=0;i--){let a=n[i](e);a&&Object.keys(a).length&&(r=Xe(r,Ze(t,a,e.changes.newLength),!0))}return r==e?e:Je.create(t,e.changes,e.selection,r.effects,r.annotations,r.scrollIntoView)}var tt=[];function nt(e){return e==null?tt:Array.isArray(e)?e:[e]}var O=(function(e){return e[e.Word=0]=`Word`,e[e.Space=1]=`Space`,e[e.Other=2]=`Other`,e})(O||={}),rt=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,it;try{it=RegExp(`[\\p{Alphabetic}\\p{Number}_]`,`u`)}catch{}function at(e){if(it)return it.test(e);for(let t=0;t<e.length;t++){let n=e[t];if(/\w/.test(n)||n>`€`&&(n.toUpperCase()!=n.toLowerCase()||rt.test(n)))return!0}return!1}function ot(e){return t=>{if(!/\S/.test(t))return O.Space;if(at(t))return O.Word;for(let n=0;n<e.length;n++)if(t.indexOf(e[n])>-1)return O.Word;return O.Other}}var k=class e{constructor(e,t,n,r,i,a){this.config=e,this.doc=t,this.selection=n,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=i,a&&(a._state=this);for(let e=0;e<this.config.dynamicSlots.length;e++)Ie(this,e<<1);this.computeSlot=null}field(e,t=!0){let n=this.config.address[e.id];if(n==null){if(t)throw RangeError(`Field is not present in this state`);return}return Ie(this,n),Le(this,n)}update(...e){return Qe(this,e,!0)}applyTransaction(t){let n=this.config,{base:r,compartments:i}=n;for(let e of t.effects)e.is(Me.reconfigure)?(n&&=(i=new Map,n.compartments.forEach((e,t)=>i.set(t,e)),null),i.set(e.value.compartment,e.value.extension)):e.is(D.reconfigure)?(n=null,r=e.value):e.is(D.appendConfig)&&(n=null,r=nt(r).concat(e.value));let a;n?a=t.startState.values.slice():(n=Pe.resolve(r,i,this),a=new e(n,this.doc,this.selection,n.dynamicSlots.map(()=>null),(e,t)=>t.reconfigure(e,this),null).values);let o=t.startState.facet(ze)?t.newSelection:t.newSelection.asSingle();new e(n,t.newDoc,o,a,(e,n)=>n.update(e,t),t)}replaceSelection(e){return typeof e==`string`&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:T.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),r=this.changes(n.changes),i=[n.range],a=nt(n.effects);for(let n=1;n<t.ranges.length;n++){let o=e(t.ranges[n]),s=this.changes(o.changes),c=s.map(r);for(let e=0;e<n;e++)i[e]=i[e].map(c);let l=r.mapDesc(s,!0);i.push(o.range.map(l)),r=r.compose(c),a=D.mapEffects(a,c).concat(D.mapEffects(nt(o.effects),l))}return{changes:r,selection:T.create(i,t.mainIndex),effects:a}}changes(t=[]){return t instanceof fe?t:fe.of(t,this.doc.length,this.facet(e.lineSeparator))}toText(t){return g.of(t.split(this.facet(e.lineSeparator)||ue))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(Ie(this,t),Le(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let r=e[n];r instanceof De&&this.config.address[r.id]!=null&&(t[n]=r.spec.toJSON(this.field(e[n]),this))}return t}static fromJSON(t,n={},r){if(!t||typeof t.doc!=`string`)throw RangeError(`Invalid JSON representation for EditorState`);let i=[];if(r){for(let e in r)if(Object.prototype.hasOwnProperty.call(t,e)){let n=r[e],a=t[e];i.push(n.init(e=>n.spec.fromJSON(a,e)))}}return e.create({doc:t.doc,selection:T.fromJSON(t.selection),extensions:n.extensions?i.concat([n.extensions]):i})}static create(t={}){let n=Pe.resolve(t.extensions||[],new Map),r=t.doc instanceof g?t.doc:g.of((t.doc||``).split(n.staticFacet(e.lineSeparator)||ue)),i=t.selection?t.selection instanceof T?t.selection:T.single(t.selection.anchor,t.selection.head):T.single(0);return ye(i,r.length),n.staticFacet(ze)||(i=i.asSingle()),new e(n,r,i,n.dynamicSlots.map(()=>null),(e,t)=>t.create(e),null)}get tabSize(){return this.facet(e.tabSize)}get lineBreak(){return this.facet(e.lineSeparator)||`
@@ -1 +1 @@
1
- import{m as e,t}from"./mermaid-parser.core-Bt-NTqTu.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as r}from"./src-B6xuSHsQ.js";import"./chunk-DU6HZSFF-Cok-A1CS.js";import{n as i,r as a,t as o}from"./chunk-SVP7TREG-BCZgT1m2.js";import{t as s}from"./chunk-JWPE2WC7-DVXcaiue.js";import"./mermaid.core-Ccd3XIq_.js";var c=e().RailroadAbnf.parser.LangiumParser,l=n(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformAlternation`),u=n(e=>{let t=e.elements.map(f);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformConcatenation`),d=n(e=>{if(e.includes(`*`)){let[t,n]=e.split(`*`);return{min:t?parseInt(t,10):0,max:n?parseInt(n,10):1/0}}let t=parseInt(e,10);return{min:t,max:t}},`parseRepeat`),f=n(e=>{let t=p(e.primary);if(!e.repeat)return t;let{min:n,max:r}=d(e.repeat);return n===0&&r===1?{type:`optional`,element:t}:{type:`repetition`,element:t,min:n,max:r}},`transformElement`),p=n(e=>{switch(e.$type){case`AbnfStringLiteral`:return{type:`terminal`,value:e.value};case`AbnfNumVal`:return{type:`terminal`,value:e.value};case`AbnfRuleName`:return{type:`nonterminal`,name:e.name};case`AbnfGroup`:return l(e.element);case`AbnfOptionalGroup`:return{type:`optional`,element:l(e.element)};default:throw Error(`Unsupported ABNF primary node: ${e.$type}`)}},`transformPrimary`),m=n(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=n(e=>{s(e,o),e.title&&o.setTitle(e.title),e.rules.map(e=>o.addRule(m(e)))},`populateDb`),g={parser:{parse:n(e=>{o.clear(),r.debug(`[ABNF Parser] Starting Langium parse`);let n=c.parse(e);if(n.lexerErrors.length>0||n.parserErrors.length>0)throw new t(n);let i=n.value;r.debug(`[ABNF Parser] Parsed rules:`,i.rules.length),h(i),r.debug(`[ABNF Parser] Parse complete`)},`parse`),parser:{yy:o}},db:o,renderer:a,styles:i};export{g as diagram};
1
+ import{m as e,t}from"./mermaid-parser.core-DYWVm27N.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as r}from"./src-B6xuSHsQ.js";import"./chunk-DU6HZSFF-C5NvhurN.js";import{n as i,r as a,t as o}from"./chunk-SVP7TREG-Moh81bMs.js";import{t as s}from"./chunk-JWPE2WC7-DVXcaiue.js";import"./mermaid.core-D4B9kTQt.js";var c=e().RailroadAbnf.parser.LangiumParser,l=n(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformAlternation`),u=n(e=>{let t=e.elements.map(f);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformConcatenation`),d=n(e=>{if(e.includes(`*`)){let[t,n]=e.split(`*`);return{min:t?parseInt(t,10):0,max:n?parseInt(n,10):1/0}}let t=parseInt(e,10);return{min:t,max:t}},`parseRepeat`),f=n(e=>{let t=p(e.primary);if(!e.repeat)return t;let{min:n,max:r}=d(e.repeat);return n===0&&r===1?{type:`optional`,element:t}:{type:`repetition`,element:t,min:n,max:r}},`transformElement`),p=n(e=>{switch(e.$type){case`AbnfStringLiteral`:return{type:`terminal`,value:e.value};case`AbnfNumVal`:return{type:`terminal`,value:e.value};case`AbnfRuleName`:return{type:`nonterminal`,name:e.name};case`AbnfGroup`:return l(e.element);case`AbnfOptionalGroup`:return{type:`optional`,element:l(e.element)};default:throw Error(`Unsupported ABNF primary node: ${e.$type}`)}},`transformPrimary`),m=n(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=n(e=>{s(e,o),e.title&&o.setTitle(e.title),e.rules.map(e=>o.addRule(m(e)))},`populateDb`),g={parser:{parse:n(e=>{o.clear(),r.debug(`[ABNF Parser] Starting Langium parse`);let n=c.parse(e);if(n.lexerErrors.length>0||n.parserErrors.length>0)throw new t(n);let i=n.value;r.debug(`[ABNF Parser] Parsed rules:`,i.rules.length),h(i),r.debug(`[ABNF Parser] Parse complete`)},`parse`),parser:{yy:o}},db:o,renderer:a,styles:i};export{g as diagram};
@@ -0,0 +1 @@
1
+ import"./chunk-FOHPRMQF-DHwB1DNv.js";import{M as e}from"./mermaid-parser.core-DYWVm27N.js";export{e as createArchitectureServices};