@pasko70/pibo 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex/skills/pi-agent-harness/SKILL.md +319 -0
- package/.codex/skills/pi-agent-harness/agents/openai.yaml +4 -0
- package/README.md +318 -0
- package/context/codex-base-prompt.md +144 -0
- package/context/pibo-compaction-prompt.md +100 -0
- package/context/pibo-system-prompt.md +17 -0
- package/dist/apps/chat/agent-profiles.js +26 -0
- package/dist/apps/chat/agent-store.js +336 -0
- package/dist/apps/chat/event-log.js +307 -0
- package/dist/apps/chat/read-model.js +218 -0
- package/dist/apps/chat/rooms.js +321 -0
- package/dist/apps/chat/session-metadata.js +14 -0
- package/dist/apps/chat/stream.js +122 -0
- package/dist/apps/chat/trace.js +1182 -0
- package/dist/apps/chat/web-app.js +2569 -0
- package/dist/apps/chat-ui/assets/apl-BxEMbctQ.js +1 -0
- package/dist/apps/chat-ui/assets/asciiarmor-eFjeGRuZ.js +1 -0
- package/dist/apps/chat-ui/assets/asn1-Cfx-0pt9.js +1 -0
- package/dist/apps/chat-ui/assets/asterisk-B5BHTsBr.js +1 -0
- package/dist/apps/chat-ui/assets/brainfuck-CAA2xofr.js +1 -0
- package/dist/apps/chat-ui/assets/clike-BoDCOLzN.js +1 -0
- package/dist/apps/chat-ui/assets/clojure-kVFSWX0o.js +1 -0
- package/dist/apps/chat-ui/assets/cmake-BUPAhezI.js +1 -0
- package/dist/apps/chat-ui/assets/cobol-BfgHZgup.js +1 -0
- package/dist/apps/chat-ui/assets/coffeescript-G1Pe_1AZ.js +1 -0
- package/dist/apps/chat-ui/assets/commonlisp-B3N0CjHn.js +1 -0
- package/dist/apps/chat-ui/assets/crystal-C15ndaGM.js +1 -0
- package/dist/apps/chat-ui/assets/css-BqOeyZOV.js +1 -0
- package/dist/apps/chat-ui/assets/cypher-KjIKv-wW.js +1 -0
- package/dist/apps/chat-ui/assets/d-BlT5AEC-.js +1 -0
- package/dist/apps/chat-ui/assets/diff-oF98tbqj.js +1 -0
- package/dist/apps/chat-ui/assets/dist--55mTWk3.js +1 -0
- package/dist/apps/chat-ui/assets/dist-B5rcjVCj.js +1 -0
- package/dist/apps/chat-ui/assets/dist-BPv5MdlL.js +1 -0
- package/dist/apps/chat-ui/assets/dist-BZ39rB1W.js +1 -0
- package/dist/apps/chat-ui/assets/dist-BsedZGJo.js +1 -0
- package/dist/apps/chat-ui/assets/dist-BvO6SpaM.js +9 -0
- package/dist/apps/chat-ui/assets/dist-C5YJOwhH.js +1 -0
- package/dist/apps/chat-ui/assets/dist-C5oXtFSP.js +1 -0
- package/dist/apps/chat-ui/assets/dist-CG_gRSwv.js +23 -0
- package/dist/apps/chat-ui/assets/dist-CKM5j-iy.js +1 -0
- package/dist/apps/chat-ui/assets/dist-CUp9us2q.js +1 -0
- package/dist/apps/chat-ui/assets/dist-CZ9T4Cly.js +1 -0
- package/dist/apps/chat-ui/assets/dist-D4HhiFWB.js +6 -0
- package/dist/apps/chat-ui/assets/dist-DHE-yBLH.js +1 -0
- package/dist/apps/chat-ui/assets/dist-DSKQpPaz.js +1 -0
- package/dist/apps/chat-ui/assets/dist-L1B-KWZO.js +1 -0
- package/dist/apps/chat-ui/assets/dist-SVPsM5Oi.js +13 -0
- package/dist/apps/chat-ui/assets/dist-Zqt9kNG9.js +1 -0
- package/dist/apps/chat-ui/assets/dist-_DPv0-QF.js +1 -0
- package/dist/apps/chat-ui/assets/dist-_oM7g0eh.js +11 -0
- package/dist/apps/chat-ui/assets/dist-laadbMWg.js +1 -0
- package/dist/apps/chat-ui/assets/dist-nFui3f-r.js +2 -0
- package/dist/apps/chat-ui/assets/dist-tGfufz3b.js +1 -0
- package/dist/apps/chat-ui/assets/dockerfile-CUaqzcqp.js +1 -0
- package/dist/apps/chat-ui/assets/dtd-VCA9yr61.js +1 -0
- package/dist/apps/chat-ui/assets/dylan-O-V5Dw5W.js +1 -0
- package/dist/apps/chat-ui/assets/ebnf-SPmdBkvT.js +1 -0
- package/dist/apps/chat-ui/assets/ecl-ChfCttfI.js +1 -0
- package/dist/apps/chat-ui/assets/eiffel-cB9EbjeN.js +1 -0
- package/dist/apps/chat-ui/assets/elm-BTiVflBU.js +1 -0
- package/dist/apps/chat-ui/assets/erlang-egf0TXFm.js +1 -0
- package/dist/apps/chat-ui/assets/factor-C2tAxNob.js +1 -0
- package/dist/apps/chat-ui/assets/fcl-BiCjh1tj.js +1 -0
- package/dist/apps/chat-ui/assets/forth-C4kDGW6u.js +1 -0
- package/dist/apps/chat-ui/assets/fortran-DzkLaPnd.js +1 -0
- package/dist/apps/chat-ui/assets/gas-DMOxskQF.js +1 -0
- package/dist/apps/chat-ui/assets/gherkin-BPxBpp-k.js +1 -0
- package/dist/apps/chat-ui/assets/groovy-CkEnc0ZY.js +1 -0
- package/dist/apps/chat-ui/assets/haskell-Dadpo9-w.js +1 -0
- package/dist/apps/chat-ui/assets/haxe-CDNZL9MW.js +1 -0
- package/dist/apps/chat-ui/assets/http-jy9Zxxt3.js +1 -0
- package/dist/apps/chat-ui/assets/idl-CGSB6iiy.js +1 -0
- package/dist/apps/chat-ui/assets/index-BdcqTugD.js +151 -0
- package/dist/apps/chat-ui/assets/index-Dk-opWl3.css +1 -0
- package/dist/apps/chat-ui/assets/javascript-DSlzRUd8.js +1 -0
- package/dist/apps/chat-ui/assets/julia-DTiF9v6R.js +1 -0
- package/dist/apps/chat-ui/assets/livescript-Ci8Xxna6.js +1 -0
- package/dist/apps/chat-ui/assets/lua-eVxIrt9t.js +1 -0
- package/dist/apps/chat-ui/assets/mathematica-Da3grj36.js +1 -0
- package/dist/apps/chat-ui/assets/mbox-BWBMSafM.js +1 -0
- package/dist/apps/chat-ui/assets/mirc-CtHu9S1B.js +1 -0
- package/dist/apps/chat-ui/assets/mllike-wTFlPWXS.js +1 -0
- package/dist/apps/chat-ui/assets/modelica-cKbQ0UXu.js +1 -0
- package/dist/apps/chat-ui/assets/mscgen-C5pXQCMK.js +1 -0
- package/dist/apps/chat-ui/assets/mumps-CKBHkOQq.js +1 -0
- package/dist/apps/chat-ui/assets/nginx-B00AiQel.js +1 -0
- package/dist/apps/chat-ui/assets/nsis-SMDwKltR.js +1 -0
- package/dist/apps/chat-ui/assets/ntriples-B_36EBV0.js +1 -0
- package/dist/apps/chat-ui/assets/octave-BXPjzAif.js +1 -0
- package/dist/apps/chat-ui/assets/oz-Dedpat1M.js +1 -0
- package/dist/apps/chat-ui/assets/pascal-CMcUg72K.js +1 -0
- package/dist/apps/chat-ui/assets/perl-DoVTbnzt.js +1 -0
- package/dist/apps/chat-ui/assets/pig-CULXT1YV.js +1 -0
- package/dist/apps/chat-ui/assets/powershell-Cv5Uhf6b.js +1 -0
- package/dist/apps/chat-ui/assets/properties-CQ1C2P-M.js +1 -0
- package/dist/apps/chat-ui/assets/protobuf-SRlvzrl6.js +1 -0
- package/dist/apps/chat-ui/assets/pug-Bo3wfL-f.js +1 -0
- package/dist/apps/chat-ui/assets/puppet-ClSqCGj6.js +1 -0
- package/dist/apps/chat-ui/assets/python-C2_X1GpX.js +1 -0
- package/dist/apps/chat-ui/assets/q-B_6Gdyzl.js +1 -0
- package/dist/apps/chat-ui/assets/r-BD07NGED.js +1 -0
- package/dist/apps/chat-ui/assets/rolldown-runtime-S-ySWqyJ.js +1 -0
- package/dist/apps/chat-ui/assets/rpm-CRu5Z2Jl.js +1 -0
- package/dist/apps/chat-ui/assets/ruby-dZPnOz8h.js +1 -0
- package/dist/apps/chat-ui/assets/sas-S2t8_sDI.js +1 -0
- package/dist/apps/chat-ui/assets/scheme-WcyFWLW2.js +1 -0
- package/dist/apps/chat-ui/assets/shell-DUelnYSh.js +1 -0
- package/dist/apps/chat-ui/assets/sieve-jDjlVhNh.js +1 -0
- package/dist/apps/chat-ui/assets/simple-mode-CL04yRVp.js +1 -0
- package/dist/apps/chat-ui/assets/smalltalk-ddWDYy10.js +1 -0
- package/dist/apps/chat-ui/assets/solr-C7rQhLuW.js +1 -0
- package/dist/apps/chat-ui/assets/sparql--fPCCgVd.js +1 -0
- package/dist/apps/chat-ui/assets/spreadsheet-DjthqD5G.js +1 -0
- package/dist/apps/chat-ui/assets/sql-D_dieYbr.js +1 -0
- package/dist/apps/chat-ui/assets/stex-rHcFYcA0.js +1 -0
- package/dist/apps/chat-ui/assets/stylus-DxF70RNr.js +1 -0
- package/dist/apps/chat-ui/assets/swift-T0hDoOb-.js +1 -0
- package/dist/apps/chat-ui/assets/tcl-Dlzy1mPk.js +1 -0
- package/dist/apps/chat-ui/assets/textile-Dy5rFZe5.js +1 -0
- package/dist/apps/chat-ui/assets/tiddlywiki-DQP1OymS.js +1 -0
- package/dist/apps/chat-ui/assets/tiki-0vOj3DB2.js +1 -0
- package/dist/apps/chat-ui/assets/toml-DEltN0lI.js +1 -0
- package/dist/apps/chat-ui/assets/troff-CRbBpEqY.js +1 -0
- package/dist/apps/chat-ui/assets/ttcn-M5q1nLKg.js +1 -0
- package/dist/apps/chat-ui/assets/ttcn-cfg-Rmw9NWq9.js +1 -0
- package/dist/apps/chat-ui/assets/turtle-BCDWhJK0.js +1 -0
- package/dist/apps/chat-ui/assets/vb-QQ7LGlOz.js +1 -0
- package/dist/apps/chat-ui/assets/vbscript-BiSEdUzz.js +1 -0
- package/dist/apps/chat-ui/assets/velocity-CzMg5_6w.js +1 -0
- package/dist/apps/chat-ui/assets/verilog-BJOO83gk.js +1 -0
- package/dist/apps/chat-ui/assets/vhdl-ed4zAZAA.js +1 -0
- package/dist/apps/chat-ui/assets/webidl-Ddy6hbV6.js +1 -0
- package/dist/apps/chat-ui/assets/xquery-Bw1zwhh6.js +1 -0
- package/dist/apps/chat-ui/assets/yacas-DZdTXy3s.js +1 -0
- package/dist/apps/chat-ui/assets/z80-DMG02_YV.js +1 -0
- package/dist/apps/chat-ui/index.html +15 -0
- package/dist/apps/context-files-ui/assets/apl-14BqhLYK.js +1 -0
- package/dist/apps/context-files-ui/assets/asciiarmor-WLvjqI7d.js +1 -0
- package/dist/apps/context-files-ui/assets/asn1-Bg4FbdCg.js +1 -0
- package/dist/apps/context-files-ui/assets/asterisk-B2MO-X4d.js +1 -0
- package/dist/apps/context-files-ui/assets/brainfuck-CV9kufud.js +1 -0
- package/dist/apps/context-files-ui/assets/clike-CjmcUpt6.js +1 -0
- package/dist/apps/context-files-ui/assets/clojure-De3QGfx6.js +1 -0
- package/dist/apps/context-files-ui/assets/cmake-i2VDNaRq.js +1 -0
- package/dist/apps/context-files-ui/assets/cobol-BwO6DF08.js +1 -0
- package/dist/apps/context-files-ui/assets/coffeescript-BtivDvRz.js +1 -0
- package/dist/apps/context-files-ui/assets/commonlisp-DFkEQdLP.js +1 -0
- package/dist/apps/context-files-ui/assets/crystal-CU0NkcVL.js +1 -0
- package/dist/apps/context-files-ui/assets/css-CbMZAQ1W.js +1 -0
- package/dist/apps/context-files-ui/assets/cypher-Dke5QOzv.js +1 -0
- package/dist/apps/context-files-ui/assets/d-TPqSVaHM.js +1 -0
- package/dist/apps/context-files-ui/assets/diff-B365LSoZ.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-B5PTVnox.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-B5ZAfwf5.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-BJW3917N.js +11 -0
- package/dist/apps/context-files-ui/assets/dist-BkUONE3N.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-CKQF1zEu.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-CwbH_3RN.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-CxRLRmMx.js +2 -0
- package/dist/apps/context-files-ui/assets/dist-D1KyNDg5.js +13 -0
- package/dist/apps/context-files-ui/assets/dist-DFi2YGux.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-DKoyMSNr.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-DLMjd26T.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-DQXzt2Ng.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-DotDq_kD.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-DyfSeBMu.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-MyZgX9K2.js +9 -0
- package/dist/apps/context-files-ui/assets/dist-QQuDy4KA.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-YwR9dpb-.js +1 -0
- package/dist/apps/context-files-ui/assets/dist-dTBsFYAl.js +1 -0
- package/dist/apps/context-files-ui/assets/dockerfile-CJb2sekW.js +1 -0
- package/dist/apps/context-files-ui/assets/dtd-CBMymJ7O.js +1 -0
- package/dist/apps/context-files-ui/assets/dylan-08Azy1NK.js +1 -0
- package/dist/apps/context-files-ui/assets/ebnf-Dkum_1J8.js +1 -0
- package/dist/apps/context-files-ui/assets/ecl-dhxjHL8y.js +1 -0
- package/dist/apps/context-files-ui/assets/eiffel-C446m6dI.js +1 -0
- package/dist/apps/context-files-ui/assets/elm-po1E9de0.js +1 -0
- package/dist/apps/context-files-ui/assets/erlang-BD5LkVkR.js +1 -0
- package/dist/apps/context-files-ui/assets/factor-B2EMQZkP.js +1 -0
- package/dist/apps/context-files-ui/assets/fcl-DkEOamHd.js +1 -0
- package/dist/apps/context-files-ui/assets/forth-dCg2_HVB.js +1 -0
- package/dist/apps/context-files-ui/assets/fortran-3ZpXLFh1.js +1 -0
- package/dist/apps/context-files-ui/assets/gas-DMmxLZRI.js +1 -0
- package/dist/apps/context-files-ui/assets/gherkin-DUSFg2R6.js +1 -0
- package/dist/apps/context-files-ui/assets/groovy-Cmduloe1.js +1 -0
- package/dist/apps/context-files-ui/assets/haskell-Cyr255R9.js +1 -0
- package/dist/apps/context-files-ui/assets/haxe-BJVKtprM.js +1 -0
- package/dist/apps/context-files-ui/assets/http-DszHFpc-.js +1 -0
- package/dist/apps/context-files-ui/assets/idl-Cati9Nrv.js +1 -0
- package/dist/apps/context-files-ui/assets/index-BwRDoHMC.css +1 -0
- package/dist/apps/context-files-ui/assets/index-GwvjXytt.js +202 -0
- package/dist/apps/context-files-ui/assets/javascript-C5pDVaoP.js +1 -0
- package/dist/apps/context-files-ui/assets/julia-DlqY1cTU.js +1 -0
- package/dist/apps/context-files-ui/assets/livescript-C6p8-2W1.js +1 -0
- package/dist/apps/context-files-ui/assets/lua-BxuTHaF7.js +1 -0
- package/dist/apps/context-files-ui/assets/mathematica-nDHZUMJT.js +1 -0
- package/dist/apps/context-files-ui/assets/mbox-DAaR0Hcz.js +1 -0
- package/dist/apps/context-files-ui/assets/mirc-CCA0FRfl.js +1 -0
- package/dist/apps/context-files-ui/assets/mllike-Cw3Iccsb.js +1 -0
- package/dist/apps/context-files-ui/assets/modelica-Czx80fNR.js +1 -0
- package/dist/apps/context-files-ui/assets/mscgen-BmfuTbzG.js +1 -0
- package/dist/apps/context-files-ui/assets/mumps-Ds_ZaumL.js +1 -0
- package/dist/apps/context-files-ui/assets/nginx-D9M2PQ4U.js +1 -0
- package/dist/apps/context-files-ui/assets/nsis-DOo3SJmd.js +1 -0
- package/dist/apps/context-files-ui/assets/ntriples-DLHGTvHs.js +1 -0
- package/dist/apps/context-files-ui/assets/octave-8jj96JiC.js +1 -0
- package/dist/apps/context-files-ui/assets/oz-BmMq7iC4.js +1 -0
- package/dist/apps/context-files-ui/assets/pascal-BgMr6XpT.js +1 -0
- package/dist/apps/context-files-ui/assets/perl-D6YJObi_.js +1 -0
- package/dist/apps/context-files-ui/assets/pig-nx7uchs8.js +1 -0
- package/dist/apps/context-files-ui/assets/powershell-B4IPkVxR.js +1 -0
- package/dist/apps/context-files-ui/assets/properties-CoavQdLC.js +1 -0
- package/dist/apps/context-files-ui/assets/protobuf-D5EWhcmc.js +1 -0
- package/dist/apps/context-files-ui/assets/pug-QU72BPAa.js +1 -0
- package/dist/apps/context-files-ui/assets/puppet-B_0GFuyD.js +1 -0
- package/dist/apps/context-files-ui/assets/python-Cs7sNzy_.js +1 -0
- package/dist/apps/context-files-ui/assets/q-BIB9pPtI.js +1 -0
- package/dist/apps/context-files-ui/assets/r-CN5s4f3o.js +1 -0
- package/dist/apps/context-files-ui/assets/rpm-Ct_Ck8mQ.js +1 -0
- package/dist/apps/context-files-ui/assets/ruby-BVPradRk.js +1 -0
- package/dist/apps/context-files-ui/assets/sas-DN4j74IF.js +1 -0
- package/dist/apps/context-files-ui/assets/scheme-CvNgHAnh.js +1 -0
- package/dist/apps/context-files-ui/assets/shell-BjiMLAaM.js +1 -0
- package/dist/apps/context-files-ui/assets/sieve-C2U1O5Z4.js +1 -0
- package/dist/apps/context-files-ui/assets/simple-mode-DnMbQuKW.js +1 -0
- package/dist/apps/context-files-ui/assets/smalltalk-DkYwYufV.js +1 -0
- package/dist/apps/context-files-ui/assets/solr-BopnSD-v.js +1 -0
- package/dist/apps/context-files-ui/assets/sparql-Cpg3YQfd.js +1 -0
- package/dist/apps/context-files-ui/assets/spreadsheet-kRxtVt9J.js +1 -0
- package/dist/apps/context-files-ui/assets/sql-DYI2GwJR.js +1 -0
- package/dist/apps/context-files-ui/assets/stex-BCRT8IJ3.js +1 -0
- package/dist/apps/context-files-ui/assets/stylus-CARoeVE9.js +1 -0
- package/dist/apps/context-files-ui/assets/swift-DKNaLAK6.js +1 -0
- package/dist/apps/context-files-ui/assets/tcl-CQyXkgMH.js +1 -0
- package/dist/apps/context-files-ui/assets/textile-Yg_UWn-t.js +1 -0
- package/dist/apps/context-files-ui/assets/tiddlywiki-dqVbkfX4.js +1 -0
- package/dist/apps/context-files-ui/assets/tiki-CC_ic8g0.js +1 -0
- package/dist/apps/context-files-ui/assets/toml-B7gGzVkJ.js +1 -0
- package/dist/apps/context-files-ui/assets/troff-Bq3z6oAu.js +1 -0
- package/dist/apps/context-files-ui/assets/ttcn-GvRgs2AT.js +1 -0
- package/dist/apps/context-files-ui/assets/ttcn-cfg-CGCXz7Vo.js +1 -0
- package/dist/apps/context-files-ui/assets/turtle-CwIpz2yy.js +1 -0
- package/dist/apps/context-files-ui/assets/vb-BmcHUM2C.js +1 -0
- package/dist/apps/context-files-ui/assets/vbscript-Cs9dylre.js +1 -0
- package/dist/apps/context-files-ui/assets/velocity-CBWU0VCy.js +1 -0
- package/dist/apps/context-files-ui/assets/verilog-DVCHmufx.js +1 -0
- package/dist/apps/context-files-ui/assets/vhdl-BGDk4f1d.js +1 -0
- package/dist/apps/context-files-ui/assets/webidl-egXQEWlC.js +1 -0
- package/dist/apps/context-files-ui/assets/xquery-5f0hn7cg.js +1 -0
- package/dist/apps/context-files-ui/assets/yacas-DNs9XkmQ.js +1 -0
- package/dist/apps/context-files-ui/assets/z80-B7Dfb4UO.js +1 -0
- package/dist/apps/context-files-ui/index.html +14 -0
- package/dist/auth/better-auth.js +129 -0
- package/dist/auth/types.js +14 -0
- package/dist/bin/pibo.js +3 -0
- package/dist/channels/types.js +1 -0
- package/dist/cli-errors.js +18 -0
- package/dist/cli.js +264 -0
- package/dist/config/config.js +167 -0
- package/dist/core/base-prompt.js +104 -0
- package/dist/core/codex-compat.js +44 -0
- package/dist/core/compaction-prompt.js +258 -0
- package/dist/core/events.js +1 -0
- package/dist/core/profiles.js +138 -0
- package/dist/core/routed-session.js +538 -0
- package/dist/core/runtime.js +323 -0
- package/dist/core/session-router.js +437 -0
- package/dist/core/system-prompt-template.js +56 -0
- package/dist/core/thinking.js +9 -0
- package/dist/core/workspace.js +5 -0
- package/dist/debug/events.js +92 -0
- package/dist/debug/index.js +631 -0
- package/dist/debug/session.js +200 -0
- package/dist/debug/sql.js +238 -0
- package/dist/debug/stores.js +49 -0
- package/dist/debug/trace.js +245 -0
- package/dist/env.js +32 -0
- package/dist/gateway/client.js +200 -0
- package/dist/gateway/protocol.js +46 -0
- package/dist/gateway/request.js +146 -0
- package/dist/gateway/server.js +221 -0
- package/dist/gateway/tool.js +69 -0
- package/dist/gateway/web.js +80 -0
- package/dist/index.js +23 -0
- package/dist/local/client.js +77 -0
- package/dist/local/extension.js +548 -0
- package/dist/local/tui.js +25 -0
- package/dist/mcp/agent-context.js +123 -0
- package/dist/mcp/client.js +332 -0
- package/dist/mcp/commands/call.js +146 -0
- package/dist/mcp/commands/grep.js +145 -0
- package/dist/mcp/commands/info.js +71 -0
- package/dist/mcp/commands/list.js +94 -0
- package/dist/mcp/config-command.js +217 -0
- package/dist/mcp/config.js +440 -0
- package/dist/mcp/daemon-client.js +266 -0
- package/dist/mcp/daemon.js +327 -0
- package/dist/mcp/errors.js +287 -0
- package/dist/mcp/index.js +431 -0
- package/dist/mcp/output.js +171 -0
- package/dist/mcp/python-runtime.js +131 -0
- package/dist/mcp/registry.js +116 -0
- package/dist/mcp/version.js +5 -0
- package/dist/pi-packages/cli.js +92 -0
- package/dist/pi-packages/installer.js +70 -0
- package/dist/pi-packages/metadata.js +231 -0
- package/dist/pi-packages/runtime.js +61 -0
- package/dist/pi-packages/store.js +175 -0
- package/dist/pi-packages/types.js +1 -0
- package/dist/plugins/better-auth.js +11 -0
- package/dist/plugins/builtin.js +249 -0
- package/dist/plugins/chat-web.js +11 -0
- package/dist/plugins/codex-compat.js +72 -0
- package/dist/plugins/context-files-store.js +354 -0
- package/dist/plugins/context-files.js +999 -0
- package/dist/plugins/core-tools.js +94 -0
- package/dist/plugins/example.js +67 -0
- package/dist/plugins/registry.js +368 -0
- package/dist/plugins/remote-agent.js +9 -0
- package/dist/plugins/types.js +1 -0
- package/dist/plugins/web.js +11 -0
- package/dist/reliability/store.js +759 -0
- package/dist/remote/channel.js +176 -0
- package/dist/remote/client.js +92 -0
- package/dist/remote/examples/tui-controller.js +263 -0
- package/dist/remote/protocol.js +55 -0
- package/dist/remote/session-client.js +189 -0
- package/dist/runs/registry.js +323 -0
- package/dist/runs/tools.js +185 -0
- package/dist/sessions/bindings.js +41 -0
- package/dist/sessions/sqlite-store.js +154 -0
- package/dist/sessions/store.js +125 -0
- package/dist/shared/trace-order.js +83 -0
- package/dist/subagents/tool.js +63 -0
- package/dist/tools/browser-use-cdp.js +207 -0
- package/dist/tools/browser-use-leases.js +338 -0
- package/dist/tools/browser-use-wrapper.js +338 -0
- package/dist/tools/codex-compat.js +85 -0
- package/dist/tools/desktop-env.js +90 -0
- package/dist/tools/guides.js +276 -0
- package/dist/tools/index.js +366 -0
- package/dist/tools/python-runtime.js +154 -0
- package/dist/tools/registry.js +107 -0
- package/dist/tools/web-search.js +137 -0
- package/dist/web/auth.js +10 -0
- package/dist/web/channel.js +151 -0
- package/dist/web/http.js +110 -0
- package/dist/web/types.js +1 -0
- package/package.json +74 -0
- package/src/mcp/LICENSE.mcp-cli +21 -0
|
@@ -0,0 +1,2569 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { extname, isAbsolute, resolve } from "node:path";
|
|
4
|
+
import { brotliCompressSync, gzipSync } from "node:zlib";
|
|
5
|
+
import { PiboWebHttpError, readJsonBody, responseHtml, responseJson } from "../../web/http.js";
|
|
6
|
+
import { ChatEventLog, createDefaultChatEventLog } from "./event-log.js";
|
|
7
|
+
import { ChatWebReadModel, createDefaultChatWebReadModel } from "./read-model.js";
|
|
8
|
+
import { chatRoomIdFromMetadata, createDefaultPiboRoomStore, isDefaultPiboRoom, isPiboRoomArchived, PiboRoomStore, roomWorkspaceFromMetadata, withChatRoomId, withPiboRoomArchived, withPiboRoomWorkspace, } from "./rooms.js";
|
|
9
|
+
import { chatStreamFramesFromOutputEvent, createChatStreamState } from "./stream.js";
|
|
10
|
+
import { buildSessionNodes, buildTraceView, createTraceViewVersion, loadPiSessionMetadata } from "./trace.js";
|
|
11
|
+
import { isChatWebSessionArchived, withChatWebArchived } from "./session-metadata.js";
|
|
12
|
+
import { CustomAgentStore, createDefaultCustomAgentStore, isValidCustomAgentName, } from "./agent-store.js";
|
|
13
|
+
import { createCustomAgentProfileDefinition } from "./agent-profiles.js";
|
|
14
|
+
import { createDefaultPiboReliabilityStore, PiboReliabilityStore } from "../../reliability/store.js";
|
|
15
|
+
import { listMcpServerInfos, setMcpServerDescription } from "../../mcp/agent-context.js";
|
|
16
|
+
import { readPiboBasePrompt, savePiboCustomBasePrompt, setPiboBasePromptMode, } from "../../core/base-prompt.js";
|
|
17
|
+
import { readPiboCompactionPrompt, savePiboCustomCompactionPrompt, setPiboCompactionPromptMode, } from "../../core/compaction-prompt.js";
|
|
18
|
+
import { getDefaultPiboWorkspace } from "../../core/workspace.js";
|
|
19
|
+
import { inspectPiPackageSource } from "../../pi-packages/metadata.js";
|
|
20
|
+
import { findPiPackage, listPiPackages, removePiPackage, setPiPackageEnabled, upsertPiPackage } from "../../pi-packages/store.js";
|
|
21
|
+
export const CHAT_WEB_APP_NAME = "pibo.chat-web";
|
|
22
|
+
export const CHAT_WEB_CHANNEL = "pibo.chat-web";
|
|
23
|
+
export const CHAT_WEB_MOUNT_PATH = "/apps/chat";
|
|
24
|
+
export const CHAT_WEB_API_PREFIX = "/api/chat";
|
|
25
|
+
const CHAT_UI_DIST_DIR = resolve(process.cwd(), "dist/apps/chat-ui");
|
|
26
|
+
const compressedAssetCache = new Map();
|
|
27
|
+
const TRACE_CACHE_MAX_ENTRIES = 128;
|
|
28
|
+
function writeSse(controller, event, payload, id) {
|
|
29
|
+
const encoder = new TextEncoder();
|
|
30
|
+
if (id)
|
|
31
|
+
controller.enqueue(encoder.encode(`id: ${id}\n`));
|
|
32
|
+
controller.enqueue(encoder.encode(`event: ${event}\n`));
|
|
33
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
|
|
34
|
+
}
|
|
35
|
+
function writeSseComment(controller, comment) {
|
|
36
|
+
controller.enqueue(new TextEncoder().encode(`: ${comment}\n\n`));
|
|
37
|
+
}
|
|
38
|
+
function requireSameOriginJsonRequest(request) {
|
|
39
|
+
const contentType = request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
40
|
+
if (contentType !== "application/json") {
|
|
41
|
+
throw new PiboWebHttpError("Content-Type must be application/json", 415);
|
|
42
|
+
}
|
|
43
|
+
const origin = request.headers.get("origin");
|
|
44
|
+
if (!origin) {
|
|
45
|
+
throw new PiboWebHttpError("Origin header is required", 403);
|
|
46
|
+
}
|
|
47
|
+
if (origin !== new URL(request.url).origin) {
|
|
48
|
+
throw new PiboWebHttpError("Origin is not allowed", 403);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function isJsonValue(value) {
|
|
52
|
+
if (value === null ||
|
|
53
|
+
typeof value === "string" ||
|
|
54
|
+
typeof value === "boolean" ||
|
|
55
|
+
(typeof value === "number" && Number.isFinite(value))) {
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
if (Array.isArray(value)) {
|
|
59
|
+
return value.every(isJsonValue);
|
|
60
|
+
}
|
|
61
|
+
if (typeof value === "object") {
|
|
62
|
+
return Object.values(value).every(isJsonValue);
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
function principalIdFor(webSession) {
|
|
67
|
+
return webSession.ownerScope;
|
|
68
|
+
}
|
|
69
|
+
function roomResourcePath(pathname) {
|
|
70
|
+
const prefix = `${CHAT_WEB_API_PREFIX}/rooms/`;
|
|
71
|
+
if (!pathname.startsWith(prefix))
|
|
72
|
+
return undefined;
|
|
73
|
+
const parts = pathname
|
|
74
|
+
.slice(prefix.length)
|
|
75
|
+
.split("/")
|
|
76
|
+
.filter((part) => part.length > 0);
|
|
77
|
+
if (parts.length < 1 || parts.length > 2)
|
|
78
|
+
return undefined;
|
|
79
|
+
try {
|
|
80
|
+
const roomId = decodeURIComponent(parts[0]);
|
|
81
|
+
const child = parts[1] ? decodeURIComponent(parts[1]) : undefined;
|
|
82
|
+
if (child && child !== "events" && child !== "messages")
|
|
83
|
+
return undefined;
|
|
84
|
+
return { roomId, child };
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
throw new PiboWebHttpError("Invalid room id", 400);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function agentResourceId(pathname) {
|
|
91
|
+
const prefix = `${CHAT_WEB_API_PREFIX}/agents/`;
|
|
92
|
+
if (!pathname.startsWith(prefix))
|
|
93
|
+
return undefined;
|
|
94
|
+
const encodedId = pathname.slice(prefix.length);
|
|
95
|
+
if (!encodedId || encodedId.includes("/"))
|
|
96
|
+
return undefined;
|
|
97
|
+
try {
|
|
98
|
+
return decodeURIComponent(encodedId);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
throw new PiboWebHttpError("Invalid agent id", 400);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function piPackageResourceId(pathname) {
|
|
105
|
+
const prefix = `${CHAT_WEB_API_PREFIX}/pi-packages/`;
|
|
106
|
+
if (!pathname.startsWith(prefix))
|
|
107
|
+
return undefined;
|
|
108
|
+
const encodedId = pathname.slice(prefix.length);
|
|
109
|
+
if (!encodedId || encodedId.includes("/"))
|
|
110
|
+
return undefined;
|
|
111
|
+
try {
|
|
112
|
+
return decodeURIComponent(encodedId);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
throw new PiboWebHttpError("Invalid Pi package id", 400);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function mcpServerResourceName(pathname) {
|
|
119
|
+
const prefix = `${CHAT_WEB_API_PREFIX}/mcp-servers/`;
|
|
120
|
+
const suffix = "/description";
|
|
121
|
+
if (!pathname.startsWith(prefix) || !pathname.endsWith(suffix))
|
|
122
|
+
return undefined;
|
|
123
|
+
const encodedName = pathname.slice(prefix.length, -suffix.length);
|
|
124
|
+
if (!encodedName || encodedName.includes("/"))
|
|
125
|
+
return undefined;
|
|
126
|
+
try {
|
|
127
|
+
return decodeURIComponent(encodedName);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
throw new PiboWebHttpError("Invalid MCP server name", 400);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function etagForVersion(version) {
|
|
134
|
+
return `"${version}"`;
|
|
135
|
+
}
|
|
136
|
+
function requestMatchesVersion(request, version) {
|
|
137
|
+
const header = request.headers.get("if-none-match");
|
|
138
|
+
if (!header)
|
|
139
|
+
return false;
|
|
140
|
+
return header
|
|
141
|
+
.split(",")
|
|
142
|
+
.map((value) => value.trim())
|
|
143
|
+
.some((value) => value === "*" || value === etagForVersion(version) || value === `W/${etagForVersion(version)}`);
|
|
144
|
+
}
|
|
145
|
+
function traceCacheKey(piboSessionId, version, includeRawEvents, rawEventsLimit) {
|
|
146
|
+
return [piboSessionId, version, includeRawEvents ? "raw" : "compact", rawEventsLimit].join(":");
|
|
147
|
+
}
|
|
148
|
+
function setTraceCache(cache, key, trace) {
|
|
149
|
+
cache.delete(key);
|
|
150
|
+
cache.set(key, trace);
|
|
151
|
+
while (cache.size > TRACE_CACHE_MAX_ENTRIES) {
|
|
152
|
+
const oldestKey = cache.keys().next().value;
|
|
153
|
+
if (typeof oldestKey !== "string")
|
|
154
|
+
break;
|
|
155
|
+
cache.delete(oldestKey);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function normalizeRoomName(value, fallback = "New Chat") {
|
|
159
|
+
if (value === undefined)
|
|
160
|
+
return fallback;
|
|
161
|
+
if (typeof value !== "string")
|
|
162
|
+
throw new PiboWebHttpError("Room name must be a string", 400);
|
|
163
|
+
const name = value.replace(/\s+/g, " ").trim();
|
|
164
|
+
if (!name)
|
|
165
|
+
throw new PiboWebHttpError("Room name is required", 400);
|
|
166
|
+
if (name.length > 120)
|
|
167
|
+
throw new PiboWebHttpError("Room name is too long", 400);
|
|
168
|
+
return name;
|
|
169
|
+
}
|
|
170
|
+
function normalizeRoomTopic(value) {
|
|
171
|
+
if (value === undefined || value === null)
|
|
172
|
+
return undefined;
|
|
173
|
+
if (typeof value !== "string")
|
|
174
|
+
throw new PiboWebHttpError("Room topic must be a string", 400);
|
|
175
|
+
const topic = value.replace(/\s+/g, " ").trim();
|
|
176
|
+
if (!topic)
|
|
177
|
+
return undefined;
|
|
178
|
+
if (topic.length > 500)
|
|
179
|
+
throw new PiboWebHttpError("Room topic is too long", 400);
|
|
180
|
+
return topic;
|
|
181
|
+
}
|
|
182
|
+
function normalizeOptionalRoomTopic(value) {
|
|
183
|
+
if (value === undefined)
|
|
184
|
+
return undefined;
|
|
185
|
+
if (value === null)
|
|
186
|
+
return null;
|
|
187
|
+
return normalizeRoomTopic(value) ?? null;
|
|
188
|
+
}
|
|
189
|
+
function normalizeRoomType(value) {
|
|
190
|
+
if (value === undefined)
|
|
191
|
+
return "chat";
|
|
192
|
+
if (value === "space" || value === "chat" || value === "agent")
|
|
193
|
+
return value;
|
|
194
|
+
throw new PiboWebHttpError("Room type is invalid", 400);
|
|
195
|
+
}
|
|
196
|
+
function normalizeParentRoomId(value) {
|
|
197
|
+
if (value === undefined || value === null || value === "")
|
|
198
|
+
return undefined;
|
|
199
|
+
if (typeof value !== "string")
|
|
200
|
+
throw new PiboWebHttpError("Parent room id must be a string", 400);
|
|
201
|
+
return value;
|
|
202
|
+
}
|
|
203
|
+
function normalizeOptionalParentRoomId(value) {
|
|
204
|
+
if (value === undefined)
|
|
205
|
+
return undefined;
|
|
206
|
+
if (value === null || value === "")
|
|
207
|
+
return null;
|
|
208
|
+
if (typeof value !== "string")
|
|
209
|
+
throw new PiboWebHttpError("Parent room id must be a string", 400);
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
function normalizeRoomArchived(value) {
|
|
213
|
+
if (value === undefined)
|
|
214
|
+
return undefined;
|
|
215
|
+
if (typeof value !== "boolean")
|
|
216
|
+
throw new PiboWebHttpError("Room archived flag must be boolean", 400);
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
function normalizeRoomWorkspace(value) {
|
|
220
|
+
if (value === undefined || value === null)
|
|
221
|
+
return undefined;
|
|
222
|
+
if (typeof value !== "string")
|
|
223
|
+
throw new PiboWebHttpError("Room workspace must be a string", 400);
|
|
224
|
+
const workspace = value.trim();
|
|
225
|
+
if (!workspace)
|
|
226
|
+
return undefined;
|
|
227
|
+
if (!isAbsolute(workspace)) {
|
|
228
|
+
throw new PiboWebHttpError("Room workspace must be an absolute path", 400);
|
|
229
|
+
}
|
|
230
|
+
if (!existsSync(workspace)) {
|
|
231
|
+
throw new PiboWebHttpError(`Room workspace does not exist: ${workspace}`, 400);
|
|
232
|
+
}
|
|
233
|
+
if (!statSync(workspace).isDirectory()) {
|
|
234
|
+
throw new PiboWebHttpError(`Room workspace is not a directory: ${workspace}`, 400);
|
|
235
|
+
}
|
|
236
|
+
return workspace;
|
|
237
|
+
}
|
|
238
|
+
function normalizeOptionalRoomWorkspace(value) {
|
|
239
|
+
if (value === undefined)
|
|
240
|
+
return undefined;
|
|
241
|
+
if (value === null)
|
|
242
|
+
return null;
|
|
243
|
+
return normalizeRoomWorkspace(value) ?? null;
|
|
244
|
+
}
|
|
245
|
+
function normalizeRoomDeleteConfirmation(value) {
|
|
246
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
247
|
+
throw new PiboWebHttpError("Type the room name to permanently delete it.", 400);
|
|
248
|
+
}
|
|
249
|
+
return value.trim();
|
|
250
|
+
}
|
|
251
|
+
function normalizeAgentDisplayName(value, fallback = "new-agent") {
|
|
252
|
+
if (value === undefined)
|
|
253
|
+
return fallback;
|
|
254
|
+
if (typeof value !== "string")
|
|
255
|
+
throw new PiboWebHttpError("Agent name must be a string", 400);
|
|
256
|
+
const name = value.trim();
|
|
257
|
+
if (!name)
|
|
258
|
+
throw new PiboWebHttpError("Agent name is required", 400);
|
|
259
|
+
if (name.length > 120)
|
|
260
|
+
throw new PiboWebHttpError("Agent name is too long", 400);
|
|
261
|
+
if (!isValidCustomAgentName(name)) {
|
|
262
|
+
throw new PiboWebHttpError("Agent name must be lowercase kebab-case, for example test-agent", 400);
|
|
263
|
+
}
|
|
264
|
+
return name;
|
|
265
|
+
}
|
|
266
|
+
function normalizeAgentDescription(value) {
|
|
267
|
+
if (value === undefined || value === null)
|
|
268
|
+
return undefined;
|
|
269
|
+
if (typeof value !== "string")
|
|
270
|
+
throw new PiboWebHttpError("Agent description must be a string", 400);
|
|
271
|
+
const description = value.trim();
|
|
272
|
+
if (!description)
|
|
273
|
+
return undefined;
|
|
274
|
+
if (description.length > 1000)
|
|
275
|
+
throw new PiboWebHttpError("Agent description is too long", 400);
|
|
276
|
+
return description;
|
|
277
|
+
}
|
|
278
|
+
function normalizeNameArray(value, label) {
|
|
279
|
+
if (value === undefined)
|
|
280
|
+
return [];
|
|
281
|
+
if (!Array.isArray(value))
|
|
282
|
+
throw new PiboWebHttpError(`${label} must be an array`, 400);
|
|
283
|
+
const names = value.map((item) => {
|
|
284
|
+
if (typeof item !== "string" || item.trim().length === 0) {
|
|
285
|
+
throw new PiboWebHttpError(`${label} entries must be non-empty strings`, 400);
|
|
286
|
+
}
|
|
287
|
+
return item.trim();
|
|
288
|
+
});
|
|
289
|
+
return [...new Set(names)];
|
|
290
|
+
}
|
|
291
|
+
function normalizeRegisteredPiPackages(value) {
|
|
292
|
+
const names = normalizeNameArray(value, "piPackages");
|
|
293
|
+
const packages = listPiPackages();
|
|
294
|
+
const registered = new Map(packages.flatMap((pkg) => [[pkg.id, pkg.id], [pkg.name, pkg.id]]));
|
|
295
|
+
for (const name of names) {
|
|
296
|
+
if (!registered.has(name))
|
|
297
|
+
throw new PiboWebHttpError(`Unknown Pi package "${name}"`, 400);
|
|
298
|
+
}
|
|
299
|
+
return [...new Set(names.map((name) => registered.get(name) ?? name))];
|
|
300
|
+
}
|
|
301
|
+
function normalizePiPackageWebSource(value) {
|
|
302
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
303
|
+
throw new PiboWebHttpError("Pi package source is required", 400);
|
|
304
|
+
}
|
|
305
|
+
const source = value.trim();
|
|
306
|
+
let url;
|
|
307
|
+
try {
|
|
308
|
+
url = new URL(source);
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
throw new PiboWebHttpError("Pi package source must be a https://pi.dev/packages/... URL", 400);
|
|
312
|
+
}
|
|
313
|
+
if (url.origin !== "https://pi.dev" || !url.pathname.startsWith("/packages/") || url.pathname === "/packages/") {
|
|
314
|
+
throw new PiboWebHttpError("Pi package source must be a https://pi.dev/packages/... URL", 400);
|
|
315
|
+
}
|
|
316
|
+
return source;
|
|
317
|
+
}
|
|
318
|
+
function normalizeBuiltinTools(value) {
|
|
319
|
+
if (value === undefined)
|
|
320
|
+
return "default";
|
|
321
|
+
if (value === "default" || value === "disabled")
|
|
322
|
+
return value;
|
|
323
|
+
throw new PiboWebHttpError("builtinTools must be default or disabled", 400);
|
|
324
|
+
}
|
|
325
|
+
function normalizeBuiltinToolNames(value) {
|
|
326
|
+
if (value === undefined)
|
|
327
|
+
return undefined;
|
|
328
|
+
return normalizeNameArray(value, "builtinToolNames");
|
|
329
|
+
}
|
|
330
|
+
function normalizeAutoContextFiles(value) {
|
|
331
|
+
if (value === undefined)
|
|
332
|
+
return true;
|
|
333
|
+
if (typeof value !== "boolean")
|
|
334
|
+
throw new PiboWebHttpError("autoContextFiles must be a boolean", 400);
|
|
335
|
+
return value;
|
|
336
|
+
}
|
|
337
|
+
function normalizeRunControl(value) {
|
|
338
|
+
if (value === undefined)
|
|
339
|
+
return false;
|
|
340
|
+
if (typeof value !== "boolean")
|
|
341
|
+
throw new PiboWebHttpError("runControl must be a boolean", 400);
|
|
342
|
+
return value;
|
|
343
|
+
}
|
|
344
|
+
function normalizeMcpServerDescriptionBody(value) {
|
|
345
|
+
if (typeof value !== "string")
|
|
346
|
+
throw new PiboWebHttpError("MCP server description must be a string", 400);
|
|
347
|
+
const description = value.replace(/\s+/g, " ").trim();
|
|
348
|
+
if (!description)
|
|
349
|
+
throw new PiboWebHttpError("MCP server description is required", 400);
|
|
350
|
+
if (description.length > 480)
|
|
351
|
+
throw new PiboWebHttpError("MCP server description is too long", 400);
|
|
352
|
+
return description;
|
|
353
|
+
}
|
|
354
|
+
function normalizeBasePromptMode(value) {
|
|
355
|
+
if (value === "library" || value === "custom")
|
|
356
|
+
return value;
|
|
357
|
+
throw new PiboWebHttpError("mode must be library or custom", 400);
|
|
358
|
+
}
|
|
359
|
+
function normalizeCompactionPromptMode(value) {
|
|
360
|
+
if (value === "library" || value === "custom")
|
|
361
|
+
return value;
|
|
362
|
+
throw new PiboWebHttpError("mode must be library or custom", 400);
|
|
363
|
+
}
|
|
364
|
+
function normalizeBasePromptMarkdown(value) {
|
|
365
|
+
if (typeof value !== "string")
|
|
366
|
+
throw new PiboWebHttpError("markdown must be a string", 400);
|
|
367
|
+
return value;
|
|
368
|
+
}
|
|
369
|
+
function normalizeCompactionPromptMarkdown(value) {
|
|
370
|
+
if (typeof value !== "string")
|
|
371
|
+
throw new PiboWebHttpError("markdown must be a string", 400);
|
|
372
|
+
return value;
|
|
373
|
+
}
|
|
374
|
+
function normalizeAgentArchived(value) {
|
|
375
|
+
if (value === undefined)
|
|
376
|
+
return undefined;
|
|
377
|
+
if (typeof value !== "boolean")
|
|
378
|
+
throw new PiboWebHttpError("archived must be a boolean", 400);
|
|
379
|
+
return value;
|
|
380
|
+
}
|
|
381
|
+
function normalizeAgentSubagents(value) {
|
|
382
|
+
if (value === undefined)
|
|
383
|
+
return [];
|
|
384
|
+
if (!Array.isArray(value))
|
|
385
|
+
throw new PiboWebHttpError("subagents must be an array", 400);
|
|
386
|
+
return value.map((item) => {
|
|
387
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
388
|
+
throw new PiboWebHttpError("subagent entries must be objects", 400);
|
|
389
|
+
}
|
|
390
|
+
const raw = item;
|
|
391
|
+
const name = normalizeAgentDisplayName(raw.name, "");
|
|
392
|
+
if (typeof raw.targetProfile !== "string" || raw.targetProfile.trim().length === 0) {
|
|
393
|
+
throw new PiboWebHttpError("subagent targetProfile is required", 400);
|
|
394
|
+
}
|
|
395
|
+
const subagent = {
|
|
396
|
+
name,
|
|
397
|
+
targetProfile: raw.targetProfile.trim(),
|
|
398
|
+
};
|
|
399
|
+
const description = normalizeAgentDescription(raw.description);
|
|
400
|
+
if (description)
|
|
401
|
+
subagent.description = description;
|
|
402
|
+
if (raw.timeoutMs !== undefined) {
|
|
403
|
+
if (typeof raw.timeoutMs !== "number" || !Number.isFinite(raw.timeoutMs) || raw.timeoutMs <= 0) {
|
|
404
|
+
throw new PiboWebHttpError("subagent timeoutMs must be a positive number", 400);
|
|
405
|
+
}
|
|
406
|
+
subagent.timeoutMs = Math.round(raw.timeoutMs);
|
|
407
|
+
}
|
|
408
|
+
if (raw.maxDepth !== undefined) {
|
|
409
|
+
if (typeof raw.maxDepth !== "number" || !Number.isFinite(raw.maxDepth) || raw.maxDepth < 1) {
|
|
410
|
+
throw new PiboWebHttpError("subagent maxDepth must be a positive number", 400);
|
|
411
|
+
}
|
|
412
|
+
subagent.maxDepth = Math.round(raw.maxDepth);
|
|
413
|
+
}
|
|
414
|
+
return subagent;
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
function normalizeClientTxnId(value) {
|
|
418
|
+
if (value === undefined)
|
|
419
|
+
return undefined;
|
|
420
|
+
if (typeof value !== "string")
|
|
421
|
+
throw new PiboWebHttpError("clientTxnId must be a string", 400);
|
|
422
|
+
const id = value.trim();
|
|
423
|
+
if (!id)
|
|
424
|
+
throw new PiboWebHttpError("clientTxnId must be a non-empty string", 400);
|
|
425
|
+
if (id.length > 160)
|
|
426
|
+
throw new PiboWebHttpError("clientTxnId is too long", 400);
|
|
427
|
+
return id;
|
|
428
|
+
}
|
|
429
|
+
function normalizeSessionDeleteConfirmation(value) {
|
|
430
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
431
|
+
throw new PiboWebHttpError('Type "Delete this session" to permanently delete it.', 400);
|
|
432
|
+
}
|
|
433
|
+
return value.trim();
|
|
434
|
+
}
|
|
435
|
+
function normalizeMessageText(value) {
|
|
436
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
437
|
+
throw new PiboWebHttpError("Message text is required", 400);
|
|
438
|
+
}
|
|
439
|
+
return value;
|
|
440
|
+
}
|
|
441
|
+
function accessDenied(error) {
|
|
442
|
+
if (error instanceof Error)
|
|
443
|
+
throw new PiboWebHttpError(error.message, 404);
|
|
444
|
+
throw new PiboWebHttpError("Room is not available for this user", 404);
|
|
445
|
+
}
|
|
446
|
+
function createReadModel(path) {
|
|
447
|
+
return path ? new ChatWebReadModel(path) : createDefaultChatWebReadModel();
|
|
448
|
+
}
|
|
449
|
+
function createEventLog(path) {
|
|
450
|
+
return path ? new ChatEventLog(path) : createDefaultChatEventLog();
|
|
451
|
+
}
|
|
452
|
+
function createRoomStore(path) {
|
|
453
|
+
return path ? new PiboRoomStore(path) : createDefaultPiboRoomStore();
|
|
454
|
+
}
|
|
455
|
+
function createAgentStore(path) {
|
|
456
|
+
return path ? new CustomAgentStore(path) : createDefaultCustomAgentStore();
|
|
457
|
+
}
|
|
458
|
+
function createReliabilityStore(path) {
|
|
459
|
+
return path ? new PiboReliabilityStore(path) : createDefaultPiboReliabilityStore();
|
|
460
|
+
}
|
|
461
|
+
function ensureEventIndexing(state, context) {
|
|
462
|
+
if (state.subscribedContext === context && state.unsubscribe)
|
|
463
|
+
return;
|
|
464
|
+
state.unsubscribe?.();
|
|
465
|
+
state.subscribedContext = context;
|
|
466
|
+
state.unsubscribe = context.channelContext.subscribe((event) => {
|
|
467
|
+
const session = context.channelContext.getSession(event.piboSessionId);
|
|
468
|
+
state.readModel.recordEvent(event, session);
|
|
469
|
+
state.reliabilityStore.append({
|
|
470
|
+
topic: "pibo.output",
|
|
471
|
+
key: event.piboSessionId,
|
|
472
|
+
eventId: `pibo.output:${event.piboSessionId}:${event.type}:${randomUUID()}`,
|
|
473
|
+
retentionClass: reliabilityRetentionClassForOutputEvent(event),
|
|
474
|
+
payload: event,
|
|
475
|
+
});
|
|
476
|
+
const room = session ? ensureSessionRoom(state, context, session) : undefined;
|
|
477
|
+
const stored = state.eventLog.appendOutputEvent(event, {
|
|
478
|
+
roomId: room?.id,
|
|
479
|
+
actorId: session?.ownerScope,
|
|
480
|
+
});
|
|
481
|
+
for (const listener of state.liveListeners)
|
|
482
|
+
listener(stored);
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
function reliabilityRetentionClassForOutputEvent(event) {
|
|
486
|
+
if (event.type === "assistant_delta" || event.type === "thinking_delta")
|
|
487
|
+
return "live_delta";
|
|
488
|
+
if (event.type === "assistant_message" || event.type === "message_started" || event.type === "message_finished") {
|
|
489
|
+
return "chat_message";
|
|
490
|
+
}
|
|
491
|
+
return "trace_event";
|
|
492
|
+
}
|
|
493
|
+
function listOwnedSessions(context, webSession) {
|
|
494
|
+
return (context.channelContext.listSessions?.() ?? [])
|
|
495
|
+
.filter((session) => session.ownerScope === webSession.ownerScope)
|
|
496
|
+
.map((session) => canonicalizeSessionProfile(context, session))
|
|
497
|
+
.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
498
|
+
}
|
|
499
|
+
function canonicalizeSessionProfile(context, session) {
|
|
500
|
+
const canonicalProfile = canonicalProfileName(context, session.profile);
|
|
501
|
+
if (!canonicalProfile || canonicalProfile === session.profile)
|
|
502
|
+
return session;
|
|
503
|
+
return context.channelContext.updateSession?.(session.id, { profile: canonicalProfile }) ?? {
|
|
504
|
+
...session,
|
|
505
|
+
profile: canonicalProfile,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
function canonicalProfileName(context, profileName) {
|
|
509
|
+
const matched = context.channelContext.getProfiles?.().find((profile) => profile.name === profileName || profile.aliases.includes(profileName));
|
|
510
|
+
return matched?.name;
|
|
511
|
+
}
|
|
512
|
+
function visibleOwnedSessions(sessions, selectedSession, includeArchived) {
|
|
513
|
+
if (includeArchived)
|
|
514
|
+
return sessions;
|
|
515
|
+
const byId = new Map(sessions.map((session) => [session.id, session]));
|
|
516
|
+
return sessions.filter((session) => session.id === selectedSession.id || !hasArchivedSessionInPath(session, byId));
|
|
517
|
+
}
|
|
518
|
+
function sessionsInRoom(sessions, roomId) {
|
|
519
|
+
return sessions.filter((session) => chatRoomIdFromMetadata(session.metadata) === roomId);
|
|
520
|
+
}
|
|
521
|
+
function visibleSessionsInRoom(input) {
|
|
522
|
+
const roomSessions = [];
|
|
523
|
+
const defaultRoom = input.state.roomStore.ensureDefaultRoom({
|
|
524
|
+
ownerScope: input.webSession.ownerScope,
|
|
525
|
+
principalId: principalIdFor(input.webSession),
|
|
526
|
+
});
|
|
527
|
+
const selectedRoomIsDefault = input.selectedRoomId === defaultRoom.id;
|
|
528
|
+
for (const session of input.sessions) {
|
|
529
|
+
const roomId = chatRoomIdFromMetadata(session.metadata);
|
|
530
|
+
if (roomId === input.selectedRoomId || (selectedRoomIsDefault && !roomId)) {
|
|
531
|
+
roomSessions.push(roomSessionWithRoom(session, input.selectedRoomId));
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
if (!roomSessions.some((session) => session.id === input.selectedSession.id)) {
|
|
535
|
+
roomSessions.push(roomSessionWithRoom(input.selectedSession, input.selectedRoomId));
|
|
536
|
+
}
|
|
537
|
+
return visibleOwnedSessions(roomSessions, input.selectedSession, input.includeArchived);
|
|
538
|
+
}
|
|
539
|
+
function roomSessionWithRoom(session, roomId) {
|
|
540
|
+
return chatRoomIdFromMetadata(session.metadata) === roomId
|
|
541
|
+
? session
|
|
542
|
+
: { ...session, metadata: withChatRoomId(session.metadata, roomId) };
|
|
543
|
+
}
|
|
544
|
+
function selectedRoomIdForSession(state, context, session) {
|
|
545
|
+
return ensureSessionRoom(state, context, session).id;
|
|
546
|
+
}
|
|
547
|
+
function hasArchivedSessionInPath(session, byId) {
|
|
548
|
+
let current = session;
|
|
549
|
+
while (current) {
|
|
550
|
+
if (isChatWebSessionArchived(current))
|
|
551
|
+
return true;
|
|
552
|
+
current = current.parentId ? byId.get(current.parentId) : undefined;
|
|
553
|
+
}
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
function ensureDefaultChatSession(state, context, webSession, defaultProfile, roomId) {
|
|
557
|
+
const room = roomId
|
|
558
|
+
? requireRoom(state, roomId, webSession, "read")
|
|
559
|
+
: state.roomStore.ensureDefaultRoom({
|
|
560
|
+
ownerScope: webSession.ownerScope,
|
|
561
|
+
principalId: principalIdFor(webSession),
|
|
562
|
+
});
|
|
563
|
+
const existing = listOwnedSessions(context, webSession).find((session) => !session.parentId &&
|
|
564
|
+
!isChatWebSessionArchived(session) &&
|
|
565
|
+
chatRoomIdFromMetadata(session.metadata) === room.id);
|
|
566
|
+
if (existing)
|
|
567
|
+
return existing;
|
|
568
|
+
if (isPiboRoomArchived(room)) {
|
|
569
|
+
const archivedExisting = listOwnedSessions(context, webSession).find((session) => !session.parentId && chatRoomIdFromMetadata(session.metadata) === room.id);
|
|
570
|
+
if (archivedExisting)
|
|
571
|
+
return archivedExisting;
|
|
572
|
+
throw new PiboWebHttpError("Archived room has no sessions", 404);
|
|
573
|
+
}
|
|
574
|
+
return createPersonalChatSession(context, webSession, defaultProfile, room);
|
|
575
|
+
}
|
|
576
|
+
function ensureSessionRoom(state, context, session, webSession) {
|
|
577
|
+
const roomId = chatRoomIdFromMetadata(session.metadata);
|
|
578
|
+
const existingRoom = roomId ? state.roomStore.getRoom(roomId) : undefined;
|
|
579
|
+
if (existingRoom)
|
|
580
|
+
return existingRoom;
|
|
581
|
+
const ownerScope = session.ownerScope ?? webSession?.ownerScope;
|
|
582
|
+
if (!ownerScope) {
|
|
583
|
+
return state.roomStore.ensureDefaultRoom({ ownerScope: "system:unknown", principalId: "system:unknown" });
|
|
584
|
+
}
|
|
585
|
+
const principalId = webSession ? principalIdFor(webSession) : ownerScope;
|
|
586
|
+
const room = state.roomStore.ensureDefaultRoom({ ownerScope, principalId });
|
|
587
|
+
if (!chatRoomIdFromMetadata(session.metadata)) {
|
|
588
|
+
context.channelContext.updateSession?.(session.id, { metadata: withChatRoomId(session.metadata, room.id) });
|
|
589
|
+
}
|
|
590
|
+
return room;
|
|
591
|
+
}
|
|
592
|
+
function requireRoom(state, roomId, webSession, action = "read") {
|
|
593
|
+
let room;
|
|
594
|
+
try {
|
|
595
|
+
room = state.roomStore.requireRoomAccess(roomId, principalIdFor(webSession), action);
|
|
596
|
+
}
|
|
597
|
+
catch (error) {
|
|
598
|
+
accessDenied(error);
|
|
599
|
+
}
|
|
600
|
+
if (action === "write" && isPiboRoomArchived(room)) {
|
|
601
|
+
throw new PiboWebHttpError("Archived rooms are read-only", 403);
|
|
602
|
+
}
|
|
603
|
+
return room;
|
|
604
|
+
}
|
|
605
|
+
function createPersonalChatSession(context, webSession, profile, room) {
|
|
606
|
+
return context.channelContext.createSession({
|
|
607
|
+
channel: CHAT_WEB_CHANNEL,
|
|
608
|
+
kind: "chat",
|
|
609
|
+
profile,
|
|
610
|
+
ownerScope: webSession.ownerScope,
|
|
611
|
+
workspace: roomWorkspaceFromMetadata(room.metadata) ?? getDefaultPiboWorkspace(),
|
|
612
|
+
metadata: withChatRoomId(undefined, room.id),
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
function parseBooleanSearchParam(url, name) {
|
|
616
|
+
return url.searchParams.get(name) === "true";
|
|
617
|
+
}
|
|
618
|
+
function parsePositiveIntSearchParam(url, name, fallback, max) {
|
|
619
|
+
const raw = url.searchParams.get(name);
|
|
620
|
+
if (!raw)
|
|
621
|
+
return fallback;
|
|
622
|
+
const parsed = Number.parseInt(raw, 10);
|
|
623
|
+
if (!Number.isFinite(parsed) || parsed <= 0)
|
|
624
|
+
return fallback;
|
|
625
|
+
return Math.min(parsed, max);
|
|
626
|
+
}
|
|
627
|
+
function sessionResourceId(pathname) {
|
|
628
|
+
const prefix = `${CHAT_WEB_API_PREFIX}/sessions/`;
|
|
629
|
+
if (!pathname.startsWith(prefix))
|
|
630
|
+
return undefined;
|
|
631
|
+
const encodedId = pathname.slice(prefix.length);
|
|
632
|
+
if (!encodedId || encodedId.includes("/"))
|
|
633
|
+
return undefined;
|
|
634
|
+
try {
|
|
635
|
+
return decodeURIComponent(encodedId);
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
throw new PiboWebHttpError("Invalid session id", 400);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
function normalizeSessionTitle(value) {
|
|
642
|
+
if (value === undefined)
|
|
643
|
+
return undefined;
|
|
644
|
+
if (value === null)
|
|
645
|
+
return null;
|
|
646
|
+
if (typeof value !== "string") {
|
|
647
|
+
throw new PiboWebHttpError("Session title must be a string or null", 400);
|
|
648
|
+
}
|
|
649
|
+
const title = value.replace(/\s+/g, " ").trim();
|
|
650
|
+
if (!title)
|
|
651
|
+
return null;
|
|
652
|
+
if (title.length > 120) {
|
|
653
|
+
throw new PiboWebHttpError("Session title is too long", 400);
|
|
654
|
+
}
|
|
655
|
+
return title;
|
|
656
|
+
}
|
|
657
|
+
function metadataWithArchiveState(session, archived) {
|
|
658
|
+
if (archived === undefined)
|
|
659
|
+
return undefined;
|
|
660
|
+
if (typeof archived !== "boolean") {
|
|
661
|
+
throw new PiboWebHttpError("Session archived flag must be boolean", 400);
|
|
662
|
+
}
|
|
663
|
+
return withChatWebArchived(session.metadata, archived);
|
|
664
|
+
}
|
|
665
|
+
function createSessionUpdate(context, session, body) {
|
|
666
|
+
const update = {};
|
|
667
|
+
const title = normalizeSessionTitle(body.title);
|
|
668
|
+
if (title !== undefined)
|
|
669
|
+
update.title = title;
|
|
670
|
+
const metadata = metadataWithArchiveState(session, body.archived);
|
|
671
|
+
if (metadata)
|
|
672
|
+
update.metadata = metadata;
|
|
673
|
+
if (body.profile !== undefined) {
|
|
674
|
+
update.profile = resolveCreateSessionProfile(context, session.profile, body.profile);
|
|
675
|
+
}
|
|
676
|
+
if (!("title" in update) && !("metadata" in update) && !("profile" in update)) {
|
|
677
|
+
throw new PiboWebHttpError("No session update fields provided", 400);
|
|
678
|
+
}
|
|
679
|
+
return update;
|
|
680
|
+
}
|
|
681
|
+
function createRoomUpdate(room, body) {
|
|
682
|
+
if (isDefaultPiboRoom(room)) {
|
|
683
|
+
throw new PiboWebHttpError("Personal Chat cannot be changed", 400);
|
|
684
|
+
}
|
|
685
|
+
const update = {};
|
|
686
|
+
if (body.name !== undefined)
|
|
687
|
+
update.name = normalizeRoomName(body.name);
|
|
688
|
+
if (body.topic !== undefined)
|
|
689
|
+
update.topic = normalizeOptionalRoomTopic(body.topic);
|
|
690
|
+
if (body.parentRoomId !== undefined)
|
|
691
|
+
update.parentRoomId = normalizeOptionalParentRoomId(body.parentRoomId);
|
|
692
|
+
const archived = normalizeRoomArchived(body.archived);
|
|
693
|
+
const workspace = normalizeOptionalRoomWorkspace(body.workspace);
|
|
694
|
+
let metadata = room.metadata;
|
|
695
|
+
let metadataChanged = false;
|
|
696
|
+
if (archived !== undefined) {
|
|
697
|
+
metadata = withPiboRoomArchived(metadata, archived);
|
|
698
|
+
metadataChanged = true;
|
|
699
|
+
}
|
|
700
|
+
if (workspace !== undefined) {
|
|
701
|
+
metadata = withPiboRoomWorkspace(metadata, workspace ?? undefined);
|
|
702
|
+
metadataChanged = true;
|
|
703
|
+
}
|
|
704
|
+
if (metadataChanged)
|
|
705
|
+
update.metadata = metadata;
|
|
706
|
+
if (Object.keys(update).length === 0) {
|
|
707
|
+
throw new PiboWebHttpError("No room update fields provided", 400);
|
|
708
|
+
}
|
|
709
|
+
return update;
|
|
710
|
+
}
|
|
711
|
+
function ensureCustomAgentProfiles(state, context) {
|
|
712
|
+
if (!context.channelContext.upsertProfile)
|
|
713
|
+
return;
|
|
714
|
+
for (const agent of state.agentStore.list()) {
|
|
715
|
+
context.channelContext.upsertProfile(createCustomAgentProfileDefinition(agent));
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
function createAgentInput(ownerScope, body) {
|
|
719
|
+
return {
|
|
720
|
+
ownerScope,
|
|
721
|
+
displayName: normalizeAgentDisplayName(body.displayName),
|
|
722
|
+
description: normalizeAgentDescription(body.description),
|
|
723
|
+
nativeTools: normalizeNameArray(body.nativeTools, "nativeTools"),
|
|
724
|
+
skills: normalizeNameArray(body.skills, "skills"),
|
|
725
|
+
contextFiles: normalizeNameArray(body.contextFiles, "contextFiles"),
|
|
726
|
+
subagents: normalizeAgentSubagents(body.subagents),
|
|
727
|
+
mcpServers: normalizeNameArray(body.mcpServers, "mcpServers"),
|
|
728
|
+
piPackages: normalizeRegisteredPiPackages(body.piPackages),
|
|
729
|
+
builtinTools: normalizeBuiltinTools(body.builtinTools),
|
|
730
|
+
builtinToolNames: normalizeBuiltinToolNames(body.builtinToolNames),
|
|
731
|
+
autoContextFiles: normalizeAutoContextFiles(body.autoContextFiles),
|
|
732
|
+
runControl: normalizeRunControl(body.runControl),
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function createAgentUpdate(body) {
|
|
736
|
+
const update = {};
|
|
737
|
+
if (body.displayName !== undefined)
|
|
738
|
+
update.displayName = normalizeAgentDisplayName(body.displayName);
|
|
739
|
+
if (body.description !== undefined)
|
|
740
|
+
update.description = normalizeAgentDescription(body.description);
|
|
741
|
+
if (body.nativeTools !== undefined)
|
|
742
|
+
update.nativeTools = normalizeNameArray(body.nativeTools, "nativeTools");
|
|
743
|
+
if (body.skills !== undefined)
|
|
744
|
+
update.skills = normalizeNameArray(body.skills, "skills");
|
|
745
|
+
if (body.contextFiles !== undefined)
|
|
746
|
+
update.contextFiles = normalizeNameArray(body.contextFiles, "contextFiles");
|
|
747
|
+
if (body.subagents !== undefined)
|
|
748
|
+
update.subagents = normalizeAgentSubagents(body.subagents);
|
|
749
|
+
if (body.mcpServers !== undefined)
|
|
750
|
+
update.mcpServers = normalizeNameArray(body.mcpServers, "mcpServers");
|
|
751
|
+
if (body.piPackages !== undefined)
|
|
752
|
+
update.piPackages = normalizeRegisteredPiPackages(body.piPackages);
|
|
753
|
+
if (body.builtinTools !== undefined)
|
|
754
|
+
update.builtinTools = normalizeBuiltinTools(body.builtinTools);
|
|
755
|
+
if (body.builtinToolNames !== undefined)
|
|
756
|
+
update.builtinToolNames = normalizeBuiltinToolNames(body.builtinToolNames);
|
|
757
|
+
if (body.autoContextFiles !== undefined)
|
|
758
|
+
update.autoContextFiles = normalizeAutoContextFiles(body.autoContextFiles);
|
|
759
|
+
if (body.runControl !== undefined)
|
|
760
|
+
update.runControl = normalizeRunControl(body.runControl);
|
|
761
|
+
if (Object.keys(update).length === 0 && body.archived === undefined) {
|
|
762
|
+
throw new PiboWebHttpError("No agent update fields provided", 400);
|
|
763
|
+
}
|
|
764
|
+
return update;
|
|
765
|
+
}
|
|
766
|
+
function requireAgentProfileNameAvailable(state, context, profileName, currentAgentId) {
|
|
767
|
+
const currentAgent = currentAgentId ? state.agentStore.get(currentAgentId) : undefined;
|
|
768
|
+
if (currentAgent?.profileName === profileName)
|
|
769
|
+
return;
|
|
770
|
+
for (const agent of state.agentStore.list(undefined, { includeArchived: true })) {
|
|
771
|
+
if (agent.id !== currentAgentId && agent.profileName === profileName) {
|
|
772
|
+
throw new PiboWebHttpError(`Agent name "${profileName}" already exists`, 400);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
const matchedProfile = context.channelContext.getProfiles?.().find((profile) => profile.name === profileName || profile.aliases.includes(profileName));
|
|
776
|
+
if (matchedProfile)
|
|
777
|
+
throw new PiboWebHttpError(`Agent name "${profileName}" conflicts with an existing profile`, 400);
|
|
778
|
+
}
|
|
779
|
+
function requireOwnedAgent(agent, webSession) {
|
|
780
|
+
if (!agent || agent.ownerScope !== webSession.ownerScope) {
|
|
781
|
+
throw new PiboWebHttpError("Agent is not available for this user", 404);
|
|
782
|
+
}
|
|
783
|
+
return agent;
|
|
784
|
+
}
|
|
785
|
+
async function buildAgentCatalog(context) {
|
|
786
|
+
return {
|
|
787
|
+
...(context.channelContext.getCapabilityCatalog?.() ?? {
|
|
788
|
+
nativeTools: [],
|
|
789
|
+
skills: [],
|
|
790
|
+
subagents: [],
|
|
791
|
+
contextFiles: [],
|
|
792
|
+
packages: [],
|
|
793
|
+
piboTools: [],
|
|
794
|
+
mcpServers: [],
|
|
795
|
+
piPackages: [],
|
|
796
|
+
}),
|
|
797
|
+
mcpServers: await listMcpServerInfos(),
|
|
798
|
+
piPackages: listPiPackages(),
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
function agentsSelectingPiPackage(state, packageId) {
|
|
802
|
+
const pkg = findPiPackage(packageId);
|
|
803
|
+
const aliases = new Set([packageId, ...(pkg ? [pkg.id, pkg.name] : [])]);
|
|
804
|
+
return state.agentStore
|
|
805
|
+
.list(undefined, { includeArchived: true })
|
|
806
|
+
.filter((agent) => agent.piPackages.some((selected) => aliases.has(selected)));
|
|
807
|
+
}
|
|
808
|
+
function normalizeAgentDeleteConfirmation(value) {
|
|
809
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
810
|
+
throw new PiboWebHttpError("Type the agent name to permanently delete it.", 400);
|
|
811
|
+
}
|
|
812
|
+
return value.trim();
|
|
813
|
+
}
|
|
814
|
+
function deleteSessionsForAgentProfile(state, context, webSession, profileName) {
|
|
815
|
+
const deleteSession = context.channelContext.deleteSession;
|
|
816
|
+
if (!deleteSession)
|
|
817
|
+
throw new PiboWebHttpError("Session deletion is not available", 501);
|
|
818
|
+
const ownedSessions = listOwnedSessions(context, webSession);
|
|
819
|
+
const sessionsById = new Map(ownedSessions.map((session) => [session.id, session]));
|
|
820
|
+
const ids = new Set(ownedSessions.filter((session) => session.profile === profileName).map((session) => session.id));
|
|
821
|
+
let changed = true;
|
|
822
|
+
while (changed) {
|
|
823
|
+
changed = false;
|
|
824
|
+
for (const session of ownedSessions) {
|
|
825
|
+
if (session.parentId && ids.has(session.parentId) && !ids.has(session.id)) {
|
|
826
|
+
ids.add(session.id);
|
|
827
|
+
changed = true;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
const orderedIds = [...ids].sort((left, right) => sessionDepth(sessionsById.get(right), sessionsById) - sessionDepth(sessionsById.get(left), sessionsById));
|
|
832
|
+
state.readModel.deleteSessions(orderedIds);
|
|
833
|
+
state.eventLog.deleteSessions(orderedIds);
|
|
834
|
+
for (const id of orderedIds)
|
|
835
|
+
deleteSession(id);
|
|
836
|
+
return orderedIds;
|
|
837
|
+
}
|
|
838
|
+
function deleteSessionSubtree(state, context, webSession, rootSession) {
|
|
839
|
+
const deleteSession = context.channelContext.deleteSession;
|
|
840
|
+
if (!deleteSession)
|
|
841
|
+
throw new PiboWebHttpError("Session deletion is not available", 501);
|
|
842
|
+
const ownedSessions = listOwnedSessions(context, webSession);
|
|
843
|
+
const sessionsById = new Map(ownedSessions.map((session) => [session.id, session]));
|
|
844
|
+
const ids = new Set([rootSession.id]);
|
|
845
|
+
let changed = true;
|
|
846
|
+
while (changed) {
|
|
847
|
+
changed = false;
|
|
848
|
+
for (const session of ownedSessions) {
|
|
849
|
+
if (session.parentId && ids.has(session.parentId) && !ids.has(session.id)) {
|
|
850
|
+
ids.add(session.id);
|
|
851
|
+
changed = true;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
const orderedIds = [...ids].sort((left, right) => sessionDepth(sessionsById.get(right), sessionsById) - sessionDepth(sessionsById.get(left), sessionsById));
|
|
856
|
+
state.readModel.deleteSessions(orderedIds);
|
|
857
|
+
state.eventLog.deleteSessions(orderedIds);
|
|
858
|
+
for (const id of orderedIds)
|
|
859
|
+
deleteSession(id);
|
|
860
|
+
return orderedIds;
|
|
861
|
+
}
|
|
862
|
+
function deleteRoomTree(state, context, webSession, room, confirmName) {
|
|
863
|
+
if (isDefaultPiboRoom(room))
|
|
864
|
+
throw new PiboWebHttpError("Personal Chat cannot be deleted", 400);
|
|
865
|
+
if (!isPiboRoomArchived(room))
|
|
866
|
+
throw new PiboWebHttpError("Archive the room before permanently deleting it.", 400);
|
|
867
|
+
if (confirmName !== room.name)
|
|
868
|
+
throw new PiboWebHttpError(`Type "${room.name}" to permanently delete this room.`, 400);
|
|
869
|
+
const deleteSession = context.channelContext.deleteSession;
|
|
870
|
+
if (!deleteSession)
|
|
871
|
+
throw new PiboWebHttpError("Session deletion is not available", 501);
|
|
872
|
+
const rooms = state.roomStore.listRoomSubtree(room.id);
|
|
873
|
+
const roomIds = rooms.map((item) => item.id);
|
|
874
|
+
const roomIdSet = new Set(roomIds);
|
|
875
|
+
const ownedSessions = listOwnedSessions(context, webSession);
|
|
876
|
+
const sessionsById = new Map(ownedSessions.map((session) => [session.id, session]));
|
|
877
|
+
const ids = new Set(ownedSessions
|
|
878
|
+
.filter((session) => {
|
|
879
|
+
const roomId = chatRoomIdFromMetadata(session.metadata);
|
|
880
|
+
return roomId ? roomIdSet.has(roomId) : false;
|
|
881
|
+
})
|
|
882
|
+
.map((session) => session.id));
|
|
883
|
+
let changed = true;
|
|
884
|
+
while (changed) {
|
|
885
|
+
changed = false;
|
|
886
|
+
for (const session of ownedSessions) {
|
|
887
|
+
if (session.parentId && ids.has(session.parentId) && !ids.has(session.id)) {
|
|
888
|
+
ids.add(session.id);
|
|
889
|
+
changed = true;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const orderedSessionIds = [...ids].sort((left, right) => sessionDepth(sessionsById.get(right), sessionsById) - sessionDepth(sessionsById.get(left), sessionsById));
|
|
894
|
+
state.readModel.deleteSessions(orderedSessionIds);
|
|
895
|
+
state.eventLog.deleteSessions(orderedSessionIds);
|
|
896
|
+
state.eventLog.deleteRooms(roomIds);
|
|
897
|
+
for (const id of orderedSessionIds)
|
|
898
|
+
deleteSession(id);
|
|
899
|
+
const orderedRoomIds = [...roomIds].reverse();
|
|
900
|
+
state.roomStore.deleteRooms(orderedRoomIds);
|
|
901
|
+
return { deletedRoomIds: orderedRoomIds, deletedSessionIds: orderedSessionIds };
|
|
902
|
+
}
|
|
903
|
+
function sessionDepth(session, sessionsById) {
|
|
904
|
+
let depth = 0;
|
|
905
|
+
let current = session;
|
|
906
|
+
while (current?.parentId) {
|
|
907
|
+
depth += 1;
|
|
908
|
+
current = sessionsById.get(current.parentId);
|
|
909
|
+
}
|
|
910
|
+
return depth;
|
|
911
|
+
}
|
|
912
|
+
function resolveRequestedSession(state, context, webSession, defaultProfile, piboSessionId, roomId) {
|
|
913
|
+
if (!piboSessionId)
|
|
914
|
+
return ensureDefaultChatSession(state, context, webSession, defaultProfile, roomId);
|
|
915
|
+
const selected = context.channelContext.getSession(piboSessionId);
|
|
916
|
+
if (!selected || selected.ownerScope !== webSession.ownerScope) {
|
|
917
|
+
throw new PiboWebHttpError("Session is not available for this user", 404);
|
|
918
|
+
}
|
|
919
|
+
const canonicalSelected = canonicalizeSessionProfile(context, selected);
|
|
920
|
+
const selectedRoom = ensureSessionRoom(state, context, canonicalSelected, webSession);
|
|
921
|
+
if (roomId && selectedRoom.id !== roomId)
|
|
922
|
+
throw new PiboWebHttpError("Session is not available in this room", 404);
|
|
923
|
+
return canonicalSelected;
|
|
924
|
+
}
|
|
925
|
+
function resolveCreateSessionProfile(context, defaultProfile, requestedProfile) {
|
|
926
|
+
if (requestedProfile === undefined)
|
|
927
|
+
return defaultProfile;
|
|
928
|
+
if (typeof requestedProfile !== "string" || requestedProfile.trim().length === 0) {
|
|
929
|
+
throw new PiboWebHttpError("Profile must be a non-empty string", 400);
|
|
930
|
+
}
|
|
931
|
+
const profileName = requestedProfile.trim();
|
|
932
|
+
const profiles = context.channelContext.getProfiles?.() ?? [];
|
|
933
|
+
if (!profiles.length) {
|
|
934
|
+
if (profileName === defaultProfile)
|
|
935
|
+
return defaultProfile;
|
|
936
|
+
throw new PiboWebHttpError(`Unknown profile "${profileName}"`, 400);
|
|
937
|
+
}
|
|
938
|
+
const matched = profiles.find((profile) => profile.name === profileName || profile.aliases.includes(profileName));
|
|
939
|
+
if (!matched) {
|
|
940
|
+
throw new PiboWebHttpError(`Unknown profile "${profileName}"`, 400);
|
|
941
|
+
}
|
|
942
|
+
return matched.name;
|
|
943
|
+
}
|
|
944
|
+
function indexOwnedSessions(readModel, sessions) {
|
|
945
|
+
for (const session of sessions)
|
|
946
|
+
readModel.upsertSession(session);
|
|
947
|
+
}
|
|
948
|
+
function markSessionsRead(state, sessions, principalId) {
|
|
949
|
+
for (const session of sessions) {
|
|
950
|
+
const latestStreamId = state.eventLog.getLatestStreamId({ piboSessionId: session.id });
|
|
951
|
+
if (latestStreamId !== undefined)
|
|
952
|
+
state.eventLog.markSessionRead(session.id, principalId, latestStreamId);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
function markRoomRead(state, roomId, principalId) {
|
|
956
|
+
const latestStreamId = state.eventLog.getLatestStreamId({ roomId });
|
|
957
|
+
if (latestStreamId !== undefined)
|
|
958
|
+
state.roomStore.updateReadCursor(roomId, principalId, latestStreamId);
|
|
959
|
+
}
|
|
960
|
+
function buildSessionUnreadCounts(state, sessions, principalId) {
|
|
961
|
+
const counts = new Map();
|
|
962
|
+
for (const session of sessions) {
|
|
963
|
+
const lastReadStreamId = state.eventLog.getSessionReadCursor(session.id, principalId) ?? 0;
|
|
964
|
+
const unreadCount = state.eventLog.countUnreadMessages({
|
|
965
|
+
piboSessionId: session.id,
|
|
966
|
+
principalId,
|
|
967
|
+
afterStreamId: lastReadStreamId,
|
|
968
|
+
});
|
|
969
|
+
if (unreadCount > 0)
|
|
970
|
+
counts.set(session.id, unreadCount);
|
|
971
|
+
}
|
|
972
|
+
return counts;
|
|
973
|
+
}
|
|
974
|
+
function buildRoomUnreadCounts(state, rooms, principalId) {
|
|
975
|
+
const counts = new Map();
|
|
976
|
+
for (const room of flattenRoomNodes(rooms)) {
|
|
977
|
+
const lastReadStreamId = state.roomStore.getMember(room.id, principalId)?.lastReadStreamId ?? 0;
|
|
978
|
+
const unreadCount = state.eventLog.countUnreadMessages({
|
|
979
|
+
roomId: room.id,
|
|
980
|
+
principalId,
|
|
981
|
+
afterStreamId: lastReadStreamId,
|
|
982
|
+
});
|
|
983
|
+
if (unreadCount > 0)
|
|
984
|
+
counts.set(room.id, unreadCount);
|
|
985
|
+
}
|
|
986
|
+
return counts;
|
|
987
|
+
}
|
|
988
|
+
function flattenRoomNodes(rooms) {
|
|
989
|
+
return rooms.flatMap((room) => [room, ...flattenRoomNodes(room.children ?? [])]);
|
|
990
|
+
}
|
|
991
|
+
function roomsWithUnreadCounts(rooms, directCounts) {
|
|
992
|
+
return rooms.map((room) => {
|
|
993
|
+
const children = roomsWithUnreadCounts(room.children ?? [], directCounts);
|
|
994
|
+
const childCount = children.reduce((sum, child) => sum + (child.unreadCount ?? 0), 0);
|
|
995
|
+
const unreadCount = (directCounts.get(room.id) ?? 0) + childCount;
|
|
996
|
+
return {
|
|
997
|
+
...room,
|
|
998
|
+
...(unreadCount > 0 ? { unreadCount } : {}),
|
|
999
|
+
children,
|
|
1000
|
+
};
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
function parseSseCursor(value) {
|
|
1004
|
+
if (!value)
|
|
1005
|
+
return undefined;
|
|
1006
|
+
const [stream, frame] = value.split(":");
|
|
1007
|
+
const streamId = Number(stream);
|
|
1008
|
+
const frameIndex = frame === undefined ? -1 : Number(frame);
|
|
1009
|
+
if (!Number.isInteger(streamId) || streamId < 0)
|
|
1010
|
+
return undefined;
|
|
1011
|
+
if (!Number.isInteger(frameIndex) || frameIndex < -1)
|
|
1012
|
+
return undefined;
|
|
1013
|
+
return { streamId, frameIndex };
|
|
1014
|
+
}
|
|
1015
|
+
function isPiboOutputEvent(value) {
|
|
1016
|
+
return !!value && typeof value === "object" && !Array.isArray(value) && typeof value.type === "string";
|
|
1017
|
+
}
|
|
1018
|
+
function storedEventMatches(stored, input) {
|
|
1019
|
+
if (input.roomId && stored.roomId !== input.roomId)
|
|
1020
|
+
return false;
|
|
1021
|
+
if (input.piboSessionId && stored.piboSessionId !== input.piboSessionId)
|
|
1022
|
+
return false;
|
|
1023
|
+
return true;
|
|
1024
|
+
}
|
|
1025
|
+
function writeStoredChatEventFrames(controller, stored, state, cursor) {
|
|
1026
|
+
if (!isPiboOutputEvent(stored.payload))
|
|
1027
|
+
return;
|
|
1028
|
+
const piboSessionId = stored.piboSessionId ?? stored.payload.piboSessionId;
|
|
1029
|
+
const frames = chatStreamFramesFromOutputEvent(stored.payload, state);
|
|
1030
|
+
for (let index = 0; index < frames.length; index += 1) {
|
|
1031
|
+
if (cursor && stored.streamId === cursor.streamId && index <= cursor.frameIndex)
|
|
1032
|
+
continue;
|
|
1033
|
+
writeSse(controller, "pibo", { ...frames[index], piboSessionId }, `${stored.streamId}:${index}`);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
function createEventStream(input) {
|
|
1037
|
+
let unsubscribe;
|
|
1038
|
+
let heartbeat;
|
|
1039
|
+
const stream = new ReadableStream({
|
|
1040
|
+
start(controller) {
|
|
1041
|
+
const streamState = createChatStreamState();
|
|
1042
|
+
writeSse(controller, "pibo", {
|
|
1043
|
+
type: "ready",
|
|
1044
|
+
piboSessionId: input.piboSessionId ?? "",
|
|
1045
|
+
});
|
|
1046
|
+
for (const stored of input.state.eventLog.listEvents({
|
|
1047
|
+
roomId: input.roomId,
|
|
1048
|
+
piboSessionId: input.piboSessionId,
|
|
1049
|
+
afterStreamId: input.cursor ? Math.max(0, input.cursor.streamId - 1) : undefined,
|
|
1050
|
+
limit: 1000,
|
|
1051
|
+
})) {
|
|
1052
|
+
writeStoredChatEventFrames(controller, stored, streamState, input.cursor);
|
|
1053
|
+
}
|
|
1054
|
+
const listener = (stored) => {
|
|
1055
|
+
if (!storedEventMatches(stored, input))
|
|
1056
|
+
return;
|
|
1057
|
+
writeStoredChatEventFrames(controller, stored, streamState);
|
|
1058
|
+
};
|
|
1059
|
+
input.state.liveListeners.add(listener);
|
|
1060
|
+
unsubscribe = () => {
|
|
1061
|
+
input.state.liveListeners.delete(listener);
|
|
1062
|
+
};
|
|
1063
|
+
heartbeat = setInterval(() => writeSseComment(controller, "heartbeat"), 25000);
|
|
1064
|
+
},
|
|
1065
|
+
cancel() {
|
|
1066
|
+
unsubscribe?.();
|
|
1067
|
+
unsubscribe = undefined;
|
|
1068
|
+
if (heartbeat)
|
|
1069
|
+
clearInterval(heartbeat);
|
|
1070
|
+
heartbeat = undefined;
|
|
1071
|
+
},
|
|
1072
|
+
});
|
|
1073
|
+
return new Response(stream, {
|
|
1074
|
+
headers: {
|
|
1075
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
1076
|
+
"cache-control": "no-cache, no-transform",
|
|
1077
|
+
connection: "keep-alive",
|
|
1078
|
+
},
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
async function sendChatMessage(input) {
|
|
1082
|
+
const text = normalizeMessageText(input.body.text);
|
|
1083
|
+
const clientTxnId = normalizeClientTxnId(input.body.clientTxnId);
|
|
1084
|
+
const requestedRoomId = input.forcedRoomId ?? (typeof input.body.roomId === "string" ? input.body.roomId : undefined);
|
|
1085
|
+
const selectedSession = resolveRequestedSession(input.state, input.context, input.webSession, input.defaultProfile, typeof input.body.piboSessionId === "string" ? input.body.piboSessionId : undefined, requestedRoomId);
|
|
1086
|
+
const room = ensureSessionRoom(input.state, input.context, selectedSession, input.webSession);
|
|
1087
|
+
if (requestedRoomId && room.id !== requestedRoomId) {
|
|
1088
|
+
throw new PiboWebHttpError("Session is not available in this room", 404);
|
|
1089
|
+
}
|
|
1090
|
+
if (isPiboRoomArchived(room)) {
|
|
1091
|
+
throw new PiboWebHttpError("Archived rooms are read-only", 403);
|
|
1092
|
+
}
|
|
1093
|
+
input.state.readModel.upsertSession(selectedSession);
|
|
1094
|
+
const actorId = principalIdFor(input.webSession);
|
|
1095
|
+
const duplicate = clientTxnId ? input.state.eventLog.findByClientTxn(room.id, actorId, clientTxnId) : undefined;
|
|
1096
|
+
if (duplicate)
|
|
1097
|
+
return responseJson({ duplicate: true, event: duplicate });
|
|
1098
|
+
const accepted = input.state.eventLog.appendEvent({
|
|
1099
|
+
roomId: room.id,
|
|
1100
|
+
piboSessionId: selectedSession.id,
|
|
1101
|
+
eventType: "user.message.accepted",
|
|
1102
|
+
actorType: "user",
|
|
1103
|
+
actorId,
|
|
1104
|
+
clientTxnId,
|
|
1105
|
+
retentionClass: "chat_message",
|
|
1106
|
+
payload: {
|
|
1107
|
+
type: "user.message.accepted",
|
|
1108
|
+
piboSessionId: selectedSession.id,
|
|
1109
|
+
roomId: room.id,
|
|
1110
|
+
text,
|
|
1111
|
+
...(clientTxnId ? { clientTxnId } : {}),
|
|
1112
|
+
},
|
|
1113
|
+
});
|
|
1114
|
+
for (const listener of input.state.liveListeners)
|
|
1115
|
+
listener(accepted);
|
|
1116
|
+
const messageId = randomUUID();
|
|
1117
|
+
let output;
|
|
1118
|
+
try {
|
|
1119
|
+
output = await input.context.channelContext.emit({
|
|
1120
|
+
type: "message",
|
|
1121
|
+
piboSessionId: selectedSession.id,
|
|
1122
|
+
id: messageId,
|
|
1123
|
+
text,
|
|
1124
|
+
source: "user",
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
catch (error) {
|
|
1128
|
+
const failed = input.state.eventLog.appendEvent({
|
|
1129
|
+
roomId: room.id,
|
|
1130
|
+
piboSessionId: selectedSession.id,
|
|
1131
|
+
eventType: "user.message.failed",
|
|
1132
|
+
actorType: "system",
|
|
1133
|
+
actorId,
|
|
1134
|
+
retentionClass: "audit_event",
|
|
1135
|
+
payload: {
|
|
1136
|
+
type: "user.message.failed",
|
|
1137
|
+
piboSessionId: selectedSession.id,
|
|
1138
|
+
roomId: room.id,
|
|
1139
|
+
...(clientTxnId ? { clientTxnId } : {}),
|
|
1140
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1141
|
+
},
|
|
1142
|
+
});
|
|
1143
|
+
for (const listener of input.state.liveListeners)
|
|
1144
|
+
listener(failed);
|
|
1145
|
+
throw error;
|
|
1146
|
+
}
|
|
1147
|
+
return responseJson({ output, event: accepted });
|
|
1148
|
+
}
|
|
1149
|
+
function responseBuiltChatIndex() {
|
|
1150
|
+
const indexPath = resolve(CHAT_UI_DIST_DIR, "index.html");
|
|
1151
|
+
if (!existsSync(indexPath))
|
|
1152
|
+
return undefined;
|
|
1153
|
+
return responseHtml(readFileSync(indexPath, "utf8"));
|
|
1154
|
+
}
|
|
1155
|
+
function responseBuiltChatAsset(request, pathname) {
|
|
1156
|
+
if (!pathname.startsWith(`${CHAT_WEB_MOUNT_PATH}/assets/`))
|
|
1157
|
+
return undefined;
|
|
1158
|
+
const relativePath = pathname.slice(`${CHAT_WEB_MOUNT_PATH}/`.length);
|
|
1159
|
+
const filePath = resolve(CHAT_UI_DIST_DIR, relativePath);
|
|
1160
|
+
if (!filePath.startsWith(CHAT_UI_DIST_DIR) || !existsSync(filePath))
|
|
1161
|
+
return undefined;
|
|
1162
|
+
const body = readFileSync(filePath);
|
|
1163
|
+
const headers = {
|
|
1164
|
+
"content-type": contentTypeFor(filePath),
|
|
1165
|
+
"cache-control": "public, max-age=31536000, immutable",
|
|
1166
|
+
};
|
|
1167
|
+
const encoding = preferredAssetEncoding(request.headers.get("accept-encoding"), filePath);
|
|
1168
|
+
if (!encoding)
|
|
1169
|
+
return new Response(body, { headers });
|
|
1170
|
+
headers["content-encoding"] = encoding;
|
|
1171
|
+
headers["vary"] = "accept-encoding";
|
|
1172
|
+
return new Response(compressedAssetBody(filePath, body, encoding), { headers });
|
|
1173
|
+
}
|
|
1174
|
+
function isChatAppPath(pathname) {
|
|
1175
|
+
if (pathname.startsWith(`${CHAT_WEB_MOUNT_PATH}/assets/`))
|
|
1176
|
+
return false;
|
|
1177
|
+
return pathname === CHAT_WEB_MOUNT_PATH || pathname.startsWith(`${CHAT_WEB_MOUNT_PATH}/`);
|
|
1178
|
+
}
|
|
1179
|
+
function contentTypeFor(path) {
|
|
1180
|
+
switch (extname(path)) {
|
|
1181
|
+
case ".js":
|
|
1182
|
+
return "text/javascript; charset=utf-8";
|
|
1183
|
+
case ".css":
|
|
1184
|
+
return "text/css; charset=utf-8";
|
|
1185
|
+
case ".svg":
|
|
1186
|
+
return "image/svg+xml";
|
|
1187
|
+
case ".png":
|
|
1188
|
+
return "image/png";
|
|
1189
|
+
default:
|
|
1190
|
+
return "application/octet-stream";
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
function preferredAssetEncoding(acceptEncoding, path) {
|
|
1194
|
+
if (!isCompressibleAsset(path) || !acceptEncoding)
|
|
1195
|
+
return undefined;
|
|
1196
|
+
if (/\bbr\b/.test(acceptEncoding))
|
|
1197
|
+
return "br";
|
|
1198
|
+
if (/\bgzip\b/.test(acceptEncoding))
|
|
1199
|
+
return "gzip";
|
|
1200
|
+
return undefined;
|
|
1201
|
+
}
|
|
1202
|
+
function isCompressibleAsset(path) {
|
|
1203
|
+
const extension = extname(path);
|
|
1204
|
+
return extension === ".js" || extension === ".css" || extension === ".html" || extension === ".json";
|
|
1205
|
+
}
|
|
1206
|
+
function compressedAssetBody(path, body, encoding) {
|
|
1207
|
+
const cacheKey = `${encoding}:${path}`;
|
|
1208
|
+
const cached = compressedAssetCache.get(cacheKey);
|
|
1209
|
+
if (cached)
|
|
1210
|
+
return cached;
|
|
1211
|
+
const compressed = encoding === "br" ? brotliCompressSync(body) : gzipSync(body);
|
|
1212
|
+
compressedAssetCache.set(cacheKey, compressed);
|
|
1213
|
+
return compressed;
|
|
1214
|
+
}
|
|
1215
|
+
function createChatHtml() {
|
|
1216
|
+
return `<!doctype html>
|
|
1217
|
+
<html lang="de">
|
|
1218
|
+
<head>
|
|
1219
|
+
<meta charset="utf-8">
|
|
1220
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1221
|
+
<title>Pibo Web Chat</title>
|
|
1222
|
+
<style>
|
|
1223
|
+
:root { color-scheme: dark; font-family: "Public Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #101d22; color: #d8e3e7; }
|
|
1224
|
+
* { box-sizing: border-box; }
|
|
1225
|
+
body { margin: 0; height: 100vh; overflow: hidden; background: #101d22; }
|
|
1226
|
+
button, textarea { font: inherit; }
|
|
1227
|
+
button { border: 1px solid #334155; background: #151f24; color: #d8e3e7; border-radius: 3px; padding: 7px 10px; cursor: pointer; }
|
|
1228
|
+
button:hover { border-color: #11a4d4; color: #ffffff; }
|
|
1229
|
+
button.primary { background: #11a4d4; border-color: #11a4d4; color: #ffffff; }
|
|
1230
|
+
button.ghost { background: transparent; }
|
|
1231
|
+
.app { display: grid; grid-template-rows: 56px 1fr; height: 100vh; }
|
|
1232
|
+
.topbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 0 16px; background: #1a262b; border-bottom: 1px solid #1e293b; }
|
|
1233
|
+
.brand { font-size: 17px; font-weight: 800; letter-spacing: .08em; color: #e7f7fb; text-transform: uppercase; white-space: nowrap; }
|
|
1234
|
+
.tabs { display: flex; gap: 6px; }
|
|
1235
|
+
.tab { height: 32px; text-transform: uppercase; font-size: 12px; letter-spacing: .06em; }
|
|
1236
|
+
.tab.active { border-color: #11a4d4; color: #11a4d4; background: rgba(17,164,212,.08); }
|
|
1237
|
+
.userbar { display: flex; align-items: center; gap: 8px; min-width: 0; color: #94a3b8; font-size: 12px; }
|
|
1238
|
+
.workspace { display: grid; grid-template-columns: 300px minmax(0,1fr) 320px; min-height: 0; }
|
|
1239
|
+
.sidebar, .inspector { background: #1a262b; border-right: 1px solid #1e293b; min-height: 0; overflow: auto; }
|
|
1240
|
+
.inspector { border-right: 0; border-left: 1px solid #1e293b; background: #0e1116; }
|
|
1241
|
+
.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 42px; padding: 10px 12px; border-bottom: 1px solid #1e293b; color: #cbd5e1; font-size: 12px; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; }
|
|
1242
|
+
.panel-actions { display: flex; align-items: center; gap: 6px; }
|
|
1243
|
+
.icon-button { width: 28px; height: 28px; padding: 0; display: grid; place-items: center; line-height: 1; }
|
|
1244
|
+
.session-tree { padding: 8px; }
|
|
1245
|
+
.session-row { width: 100%; display: grid; grid-template-columns: 28px minmax(0,1fr); align-items: center; margin-bottom: 4px; border: 1px solid transparent; border-radius: 3px; background: transparent; padding: 0 8px 0 0; }
|
|
1246
|
+
.session-row.active { border-color: #11a4d4; background: rgba(17,164,212,.10); }
|
|
1247
|
+
.session-toggle, .session-select { border: 0; background: transparent; border-radius: 0; padding: 0; }
|
|
1248
|
+
.session-toggle { width: 28px; height: 32px; display: grid; place-items: center; color: #64748b; }
|
|
1249
|
+
.session-toggle:hover { color: #11a4d4; border-color: transparent; }
|
|
1250
|
+
.session-select { min-width: 0; display: grid; grid-template-columns: minmax(0,1fr) auto; gap: 7px; align-items: center; text-align: left; padding: 7px 0; }
|
|
1251
|
+
.session-select:hover { border-color: transparent; }
|
|
1252
|
+
.session-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; color: #e2e8f0; }
|
|
1253
|
+
.session-id { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 10px; color: #64748b; }
|
|
1254
|
+
.status-dot { width: 7px; height: 7px; border-radius: 999px; background: #64748b; }
|
|
1255
|
+
.status-dot.running { background: #0bda57; box-shadow: 0 0 10px rgba(11,218,87,.35); }
|
|
1256
|
+
.status-dot.error { background: #ef4444; }
|
|
1257
|
+
.main { min-height: 0; display: grid; grid-template-rows: auto 1fr auto; background: #101d22; }
|
|
1258
|
+
.session-head { min-height: 58px; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 14px; border-bottom: 1px solid #1e293b; background: #151f24; }
|
|
1259
|
+
.session-name { margin: 0; font-size: 16px; line-height: 1.2; }
|
|
1260
|
+
.session-meta { margin-top: 4px; color: #64748b; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; }
|
|
1261
|
+
.trace-controls { display: flex; flex-wrap: wrap; gap: 6px; justify-content: flex-end; }
|
|
1262
|
+
.content { min-height: 0; overflow: auto; padding: 14px; }
|
|
1263
|
+
.trace-list { min-width: 620px; display: flex; flex-direction: column; gap: 9px; }
|
|
1264
|
+
/* Ported from pydantic-tracing SpanNode/JsonRenderer visual structure. */
|
|
1265
|
+
.span-card { border: 1px solid #334155; border-radius: 3px; background: #1a262b; overflow: hidden; }
|
|
1266
|
+
.span-card.ok { border-color: rgba(11,218,87,.30); }
|
|
1267
|
+
.span-card.running { border-color: rgba(17,164,212,.50); box-shadow: 0 0 10px rgba(17,164,212,.10); }
|
|
1268
|
+
.span-card.error { border-color: rgba(255,107,0,.50); }
|
|
1269
|
+
.span-card[data-span-type="tool.call"] { border-color: rgba(168,85,247,.52); }
|
|
1270
|
+
.span-card[data-span-type="tool.result"] { border-color: rgba(34,197,94,.42); }
|
|
1271
|
+
.span-card[data-span-type="model.reasoning"] { border-color: rgba(245,158,11,.48); }
|
|
1272
|
+
.span-card[data-span-type="agent.delegation"] { border-color: rgba(249,115,22,.58); }
|
|
1273
|
+
.span-card[data-span-type="user.prompt"] { border-color: rgba(6,182,212,.48); }
|
|
1274
|
+
.span-header { width: 100%; display: grid; grid-template-columns: 18px 22px minmax(0,1fr) auto; align-items: center; gap: 8px; padding: 9px 10px; background: #151f24; border: 0; text-align: left; }
|
|
1275
|
+
.span-card.ok > .span-header { background: rgba(11,218,87,.05); }
|
|
1276
|
+
.span-card.running > .span-header { background: rgba(17,164,212,.05); }
|
|
1277
|
+
.span-card.error > .span-header { background: rgba(255,107,0,.05); }
|
|
1278
|
+
.span-chevron { color: #64748b; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
|
|
1279
|
+
.span-icon { width: 18px; height: 18px; display: grid; place-items: center; border-radius: 999px; background: rgba(17,164,212,.20); color: #11a4d4; font: 11px ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1280
|
+
.span-card[data-span-type="tool.call"] .span-icon { background: rgba(168,85,247,.20); color: #a855f7; }
|
|
1281
|
+
.span-card[data-span-type="tool.result"] .span-icon { background: rgba(34,197,94,.20); color: #22c55e; }
|
|
1282
|
+
.span-card[data-span-type="model.reasoning"] .span-icon { background: rgba(245,158,11,.20); color: #f59e0b; }
|
|
1283
|
+
.span-card[data-span-type="agent.delegation"] .span-icon { background: rgba(249,115,22,.20); color: #f97316; }
|
|
1284
|
+
.span-card[data-span-type="user.prompt"] .span-icon { background: rgba(6,182,212,.20); color: #06b6d4; }
|
|
1285
|
+
.span-type-label { color: #cbd5e1; font-size: 11px; font-weight: 800; letter-spacing: .07em; text-transform: uppercase; }
|
|
1286
|
+
.span-title { color: #94a3b8; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1287
|
+
.span-meta { display: flex; align-items: center; gap: 6px; }
|
|
1288
|
+
.span-body { display: none; border-top: 1px solid #1e293b; }
|
|
1289
|
+
.span-card.open > .span-body { display: block; }
|
|
1290
|
+
.span-actions { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 10px; border-bottom: 1px solid #1e293b; background: rgba(15,23,42,.18); }
|
|
1291
|
+
.span-quote { padding: 14px; color: #cbd5e1; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }
|
|
1292
|
+
.span-code-well { padding: 12px 14px; background: #0e1116; border-bottom: 1px solid #1e293b; overflow: auto; }
|
|
1293
|
+
.span-function { font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; color: #22c55e; white-space: pre-wrap; }
|
|
1294
|
+
.syntax-keyword { color: #c084fc; }
|
|
1295
|
+
.syntax-name { color: #fde047; }
|
|
1296
|
+
.syntax-key { color: #60a5fa; }
|
|
1297
|
+
.syntax-string { color: #86efac; }
|
|
1298
|
+
.span-output-summary { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 8px 14px; background: rgba(15,23,42,.28); border-bottom: 1px solid #1e293b; color: #94a3b8; font-size: 12px; }
|
|
1299
|
+
.span-output-summary code { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #cbd5e1; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1300
|
+
.span-section { padding: 12px 14px; background: #0e1116; border-top: 1px solid rgba(51,65,85,.55); }
|
|
1301
|
+
.span-section-title { margin-bottom: 7px; color: #60a5fa; font-size: 10px; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; }
|
|
1302
|
+
.span-section-title.output { color: #22c55e; }
|
|
1303
|
+
.reasoning-block { padding: 14px; background: rgba(245,158,11,.06); color: #cbd5e1; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; }
|
|
1304
|
+
.reasoning-comment { color: rgba(245,158,11,.75); }
|
|
1305
|
+
.delegation-card { padding: 14px; background: rgba(249,115,22,.06); border-bottom: 1px solid rgba(249,115,22,.20); }
|
|
1306
|
+
.delegation-title { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; color: #f97316; font-size: 13px; font-weight: 700; }
|
|
1307
|
+
.delegation-query { color: #94a3b8; font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1308
|
+
.json-renderer { margin: 0; max-height: 24rem; overflow: auto; white-space: pre-wrap; color: #dbeafe; font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1309
|
+
.trace-node { border: 1px solid #334155; border-radius: 3px; background: #1a262b; overflow: hidden; }
|
|
1310
|
+
.trace-node[data-type="user.message"] { border-color: rgba(6,182,212,.42); }
|
|
1311
|
+
.trace-node[data-type="assistant.message"] { border-color: rgba(34,197,94,.35); }
|
|
1312
|
+
.trace-node[data-type="model.reasoning"] { border-color: rgba(245,158,11,.45); }
|
|
1313
|
+
.trace-node[data-type="tool.call"] { border-color: rgba(168,85,247,.45); }
|
|
1314
|
+
.trace-node[data-type="agent.delegation"] { border-color: rgba(249,115,22,.55); }
|
|
1315
|
+
.trace-node[data-type="agent.async"] { border-color: rgba(249,115,22,.55); }
|
|
1316
|
+
.trace-node[data-type="execution.command"] { border-color: rgba(17,164,212,.42); }
|
|
1317
|
+
.trace-node[data-type="error"] { border-color: rgba(239,68,68,.65); }
|
|
1318
|
+
.trace-header { width: 100%; display: grid; grid-template-columns: 22px 1fr auto; align-items: center; gap: 8px; padding: 9px 10px; background: #151f24; border: 0; text-align: left; }
|
|
1319
|
+
.trace-icon { width: 18px; height: 18px; display: grid; place-items: center; border-radius: 999px; background: rgba(17,164,212,.14); color: #11a4d4; font-size: 11px; }
|
|
1320
|
+
.trace-label { color: #cbd5e1; font-size: 11px; font-weight: 800; letter-spacing: .07em; text-transform: uppercase; }
|
|
1321
|
+
.trace-summary { margin-top: 3px; color: #94a3b8; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1322
|
+
.trace-actions { display: flex; align-items: center; gap: 6px; }
|
|
1323
|
+
.badge { border: 1px solid #334155; border-radius: 999px; padding: 2px 6px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 10px; color: #94a3b8; }
|
|
1324
|
+
.badge.running { color: #0bda57; border-color: rgba(11,218,87,.35); }
|
|
1325
|
+
.badge.error { color: #ef4444; border-color: rgba(239,68,68,.45); }
|
|
1326
|
+
.trace-body { display: none; padding: 10px; border-top: 1px solid #1e293b; }
|
|
1327
|
+
.trace-node.open > .trace-body { display: block; }
|
|
1328
|
+
.payload { margin: 0; white-space: pre-wrap; overflow: auto; max-height: 360px; padding: 10px; border: 1px solid #1e293b; border-radius: 3px; background: #0e1116; color: #dbeafe; font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1329
|
+
.children { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-left: 12px; border-left: 1px solid #334155; }
|
|
1330
|
+
.composer-wrap { position: relative; padding: 10px 12px; border-top: 1px solid #1e293b; background: #151f24; }
|
|
1331
|
+
.composer { display: grid; grid-template-columns: 1fr auto; gap: 8px; }
|
|
1332
|
+
textarea { width: 100%; min-height: 48px; max-height: 150px; resize: vertical; border: 1px solid #334155; border-radius: 3px; padding: 10px; background: #0e1116; color: #e2e8f0; }
|
|
1333
|
+
.command-menu { position: absolute; left: 12px; bottom: 74px; width: min(520px, calc(100% - 24px)); max-height: 280px; overflow: auto; background: #0e1116; border: 1px solid #11a4d4; border-radius: 3px; box-shadow: 0 12px 30px rgba(0,0,0,.35); z-index: 20; }
|
|
1334
|
+
.command-item { display: grid; grid-template-columns: 120px 1fr; gap: 10px; width: 100%; padding: 9px 10px; border: 0; border-bottom: 1px solid #1e293b; text-align: left; background: transparent; }
|
|
1335
|
+
.command-item.active { background: rgba(17,164,212,.13); }
|
|
1336
|
+
.command-name { color: #11a4d4; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
1337
|
+
.command-desc { color: #94a3b8; font-size: 12px; }
|
|
1338
|
+
.inspector-log { padding: 10px; display: flex; flex-direction: column; gap: 8px; }
|
|
1339
|
+
.raw-event { border-left: 2px solid #11a4d4; padding: 8px; background: #151f24; }
|
|
1340
|
+
.raw-event-type { color: #11a4d4; font: 11px ui-monospace, SFMono-Regular, Menlo, monospace; margin-bottom: 5px; }
|
|
1341
|
+
.placeholder { padding: 18px; color: #94a3b8; }
|
|
1342
|
+
.modal-backdrop { position: fixed; inset: 0; display: grid; place-items: center; background: rgba(0,0,0,.62); z-index: 50; }
|
|
1343
|
+
.modal { width: min(420px, calc(100vw - 32px)); border: 1px solid #334155; border-radius: 4px; background: #1a262b; padding: 16px; }
|
|
1344
|
+
.modal h2 { margin: 0 0 8px; font-size: 15px; }
|
|
1345
|
+
.modal p { margin: 0 0 14px; color: #94a3b8; font-size: 13px; }
|
|
1346
|
+
.modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
|
|
1347
|
+
.hidden { display: none !important; }
|
|
1348
|
+
@media (max-width: 980px) {
|
|
1349
|
+
.workspace { grid-template-columns: 240px minmax(0,1fr); }
|
|
1350
|
+
.inspector { display: none; }
|
|
1351
|
+
}
|
|
1352
|
+
@media (max-width: 720px) {
|
|
1353
|
+
body { overflow: auto; }
|
|
1354
|
+
.app { height: auto; min-height: 100vh; }
|
|
1355
|
+
.topbar { flex-wrap: wrap; height: auto; min-height: 56px; padding: 10px; }
|
|
1356
|
+
.workspace { grid-template-columns: 1fr; }
|
|
1357
|
+
.sidebar { max-height: 260px; }
|
|
1358
|
+
.main { min-height: 70vh; }
|
|
1359
|
+
.trace-list { min-width: 0; }
|
|
1360
|
+
.composer { grid-template-columns: 1fr; }
|
|
1361
|
+
}
|
|
1362
|
+
</style>
|
|
1363
|
+
</head>
|
|
1364
|
+
<body>
|
|
1365
|
+
<div class="app">
|
|
1366
|
+
<header class="topbar">
|
|
1367
|
+
<div class="brand">Pibo Chat</div>
|
|
1368
|
+
<nav class="tabs">
|
|
1369
|
+
<button class="tab active" data-area="sessions">Sessions</button>
|
|
1370
|
+
<button class="tab" data-area="agents">Agents</button>
|
|
1371
|
+
<button class="tab" data-area="settings">Settings</button>
|
|
1372
|
+
</nav>
|
|
1373
|
+
<div class="userbar" id="user"></div>
|
|
1374
|
+
</header>
|
|
1375
|
+
<div class="workspace">
|
|
1376
|
+
<aside class="sidebar">
|
|
1377
|
+
<div class="panel-head">
|
|
1378
|
+
<span id="sidebar-title">Sessions</span>
|
|
1379
|
+
<div class="panel-actions">
|
|
1380
|
+
<button class="ghost icon-button" id="new-session" title="New Session" aria-label="New Session">+</button>
|
|
1381
|
+
<button class="ghost" id="refresh">Refresh</button>
|
|
1382
|
+
</div>
|
|
1383
|
+
</div>
|
|
1384
|
+
<div class="session-tree" id="session-tree"></div>
|
|
1385
|
+
</aside>
|
|
1386
|
+
<main class="main">
|
|
1387
|
+
<div class="session-head">
|
|
1388
|
+
<div>
|
|
1389
|
+
<h1 class="session-name" id="session-title">Loading</h1>
|
|
1390
|
+
<div class="session-meta" id="session-meta"></div>
|
|
1391
|
+
</div>
|
|
1392
|
+
<div class="trace-controls">
|
|
1393
|
+
<button class="ghost" id="thinking-toggle">Thinking Off</button>
|
|
1394
|
+
<button class="ghost" id="collapse-all">Collapse All</button>
|
|
1395
|
+
<button class="ghost" id="expand-one">Depth 1</button>
|
|
1396
|
+
<button class="ghost" id="expand-all">Expand All</button>
|
|
1397
|
+
</div>
|
|
1398
|
+
</div>
|
|
1399
|
+
<section class="content" id="content"></section>
|
|
1400
|
+
<div class="composer-wrap" id="composer-wrap">
|
|
1401
|
+
<div class="command-menu hidden" id="command-menu"></div>
|
|
1402
|
+
<form class="composer" id="composer">
|
|
1403
|
+
<textarea id="message" name="message" placeholder="Message selected session or type /"></textarea>
|
|
1404
|
+
<button class="primary" type="submit">Send</button>
|
|
1405
|
+
</form>
|
|
1406
|
+
</div>
|
|
1407
|
+
</main>
|
|
1408
|
+
<aside class="inspector">
|
|
1409
|
+
<div class="panel-head"><span>Raw Events</span><button class="ghost" id="clear-local">Clear UI</button></div>
|
|
1410
|
+
<div class="inspector-log" id="raw-log"></div>
|
|
1411
|
+
</aside>
|
|
1412
|
+
</div>
|
|
1413
|
+
</div>
|
|
1414
|
+
<div class="modal-backdrop hidden" id="fork-modal">
|
|
1415
|
+
<div class="modal">
|
|
1416
|
+
<h2>Zur geforkten Session wechseln?</h2>
|
|
1417
|
+
<p>Der Fork wurde erstellt. Wenn du wechselst, wird die neue Session geladen.</p>
|
|
1418
|
+
<div class="modal-actions">
|
|
1419
|
+
<button id="fork-stay">Nein</button>
|
|
1420
|
+
<button class="primary" id="fork-switch">Ja</button>
|
|
1421
|
+
</div>
|
|
1422
|
+
</div>
|
|
1423
|
+
</div>
|
|
1424
|
+
<script>
|
|
1425
|
+
const userEl = document.querySelector("#user");
|
|
1426
|
+
const sessionTreeEl = document.querySelector("#session-tree");
|
|
1427
|
+
const sessionTitleEl = document.querySelector("#session-title");
|
|
1428
|
+
const sessionMetaEl = document.querySelector("#session-meta");
|
|
1429
|
+
const contentEl = document.querySelector("#content");
|
|
1430
|
+
const rawLogEl = document.querySelector("#raw-log");
|
|
1431
|
+
const composer = document.querySelector("#composer");
|
|
1432
|
+
const messageInput = document.querySelector("#message");
|
|
1433
|
+
const commandMenu = document.querySelector("#command-menu");
|
|
1434
|
+
const forkModal = document.querySelector("#fork-modal");
|
|
1435
|
+
const newSessionButton = document.querySelector("#new-session");
|
|
1436
|
+
let eventSource;
|
|
1437
|
+
let bootstrap;
|
|
1438
|
+
let selectedPiboSessionId;
|
|
1439
|
+
let area = "sessions";
|
|
1440
|
+
let pendingForkResult;
|
|
1441
|
+
let pendingForkComposerText;
|
|
1442
|
+
let showThinking = localStorage.getItem("pibo.chat.showThinking") === "true";
|
|
1443
|
+
let selectedAgentProfile = localStorage.getItem("pibo.chat.newSessionProfile") || "";
|
|
1444
|
+
let openNodes = new Set(JSON.parse(localStorage.getItem("pibo.chat.openNodes") || "[]"));
|
|
1445
|
+
let openSessionNodes = new Set();
|
|
1446
|
+
let commandIndex = 0;
|
|
1447
|
+
|
|
1448
|
+
function saveOpenNodes() {
|
|
1449
|
+
localStorage.setItem("pibo.chat.openNodes", JSON.stringify(Array.from(openNodes)));
|
|
1450
|
+
}
|
|
1451
|
+
function escapeText(value) {
|
|
1452
|
+
return String(value == null ? "" : value).replace(/[&<>"']/g, function(ch) {
|
|
1453
|
+
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[ch];
|
|
1454
|
+
});
|
|
1455
|
+
}
|
|
1456
|
+
function pretty(value) {
|
|
1457
|
+
if (value == null || value === "") return "";
|
|
1458
|
+
if (typeof value === "string") return value;
|
|
1459
|
+
try { return JSON.stringify(value, null, 2); } catch { return String(value); }
|
|
1460
|
+
}
|
|
1461
|
+
function short(value, n) {
|
|
1462
|
+
const text = String(value || "").replace(/\\s+/g, " ").trim();
|
|
1463
|
+
return text.length > n ? text.slice(0, n - 1) + "…" : text;
|
|
1464
|
+
}
|
|
1465
|
+
function nodeLabel(type) {
|
|
1466
|
+
return {
|
|
1467
|
+
"user.message": "User Message",
|
|
1468
|
+
"assistant.message": "Agent Message",
|
|
1469
|
+
"agent.turn": "Agent Turn",
|
|
1470
|
+
"model.reasoning": "Reasoning",
|
|
1471
|
+
"tool.call": "Tool Call",
|
|
1472
|
+
"tool.result": "Tool Result",
|
|
1473
|
+
"agent.delegation": "Agent Delegation",
|
|
1474
|
+
"agent.async": "Async Agent",
|
|
1475
|
+
"execution.command": "Execution Command",
|
|
1476
|
+
"yielded.run": "Yielded Run",
|
|
1477
|
+
"error": "Error"
|
|
1478
|
+
}[type] || type;
|
|
1479
|
+
}
|
|
1480
|
+
function nodeIcon(type) {
|
|
1481
|
+
return {
|
|
1482
|
+
"user.message": "U",
|
|
1483
|
+
"assistant.message": "A",
|
|
1484
|
+
"agent.turn": "R",
|
|
1485
|
+
"model.reasoning": "?",
|
|
1486
|
+
"tool.call": "T",
|
|
1487
|
+
"tool.result": "O",
|
|
1488
|
+
"agent.delegation": "D",
|
|
1489
|
+
"agent.async": "A",
|
|
1490
|
+
"execution.command": "$",
|
|
1491
|
+
"yielded.run": "Y",
|
|
1492
|
+
"error": "!"
|
|
1493
|
+
}[type] || "*";
|
|
1494
|
+
}
|
|
1495
|
+
function spanType(type) {
|
|
1496
|
+
return {
|
|
1497
|
+
"user.message": "user.prompt",
|
|
1498
|
+
"assistant.message": "model.response",
|
|
1499
|
+
"agent.turn": "agent.run",
|
|
1500
|
+
"model.reasoning": "model.reasoning",
|
|
1501
|
+
"tool.call": "tool.call",
|
|
1502
|
+
"tool.result": "tool.result",
|
|
1503
|
+
"agent.delegation": "agent.delegation",
|
|
1504
|
+
"agent.async": "agent.async",
|
|
1505
|
+
"execution.command": "tool.result",
|
|
1506
|
+
"yielded.run": "tool.call",
|
|
1507
|
+
"error": "tool.result"
|
|
1508
|
+
}[type] || "agent.run";
|
|
1509
|
+
}
|
|
1510
|
+
function spanLabel(type) {
|
|
1511
|
+
const mapped = spanType(type);
|
|
1512
|
+
return {
|
|
1513
|
+
"agent.run": "Agent Run",
|
|
1514
|
+
"tool.call": "Tool Call",
|
|
1515
|
+
"tool.result": "Tool Result",
|
|
1516
|
+
"model.response": "Model Response",
|
|
1517
|
+
"model.reasoning": "Reasoning",
|
|
1518
|
+
"agent.delegation": "Agent Delegation",
|
|
1519
|
+
"agent.async": "Async Agent",
|
|
1520
|
+
"user.prompt": "User Prompt"
|
|
1521
|
+
}[mapped] || mapped;
|
|
1522
|
+
}
|
|
1523
|
+
function spanStatusClass(status) {
|
|
1524
|
+
if (status === "error") return "error";
|
|
1525
|
+
if (status === "running") return "running";
|
|
1526
|
+
return "ok";
|
|
1527
|
+
}
|
|
1528
|
+
function renderJson(value) {
|
|
1529
|
+
return '<pre class="json-renderer">' + escapeText(pretty(value)) + '</pre>';
|
|
1530
|
+
}
|
|
1531
|
+
function functionSignature(name, args) {
|
|
1532
|
+
const input = args && typeof args === "object" && !Array.isArray(args) ? args : {};
|
|
1533
|
+
const params = Object.entries(input).map(function(entry) {
|
|
1534
|
+
const key = entry[0];
|
|
1535
|
+
const value = entry[1];
|
|
1536
|
+
const raw = typeof value === "string" ? "'" + short(value, 50) + "'" : short(pretty(value), 50);
|
|
1537
|
+
return '<span class="syntax-key">' + escapeText(key) + '</span>=<span class="syntax-string">' + escapeText(raw) + '</span>';
|
|
1538
|
+
}).join(", ");
|
|
1539
|
+
return '<code class="span-function"><span class="syntax-keyword">def</span> <span class="syntax-name">' + escapeText(name || "tool") + '</span>(' + params + ')</code>';
|
|
1540
|
+
}
|
|
1541
|
+
function renderSpanContent(node) {
|
|
1542
|
+
const actionHtml = [];
|
|
1543
|
+
if (node.type === "user.message" && node.entryId) actionHtml.push('<button class="ghost fork-button" data-entry-id="' + escapeText(node.entryId) + '">Fork From Here</button>');
|
|
1544
|
+
if (node.linkedPiboSessionId) actionHtml.push('<button class="ghost session-link" data-pibo-session-id="' + escapeText(node.linkedPiboSessionId) + '">Open Child Session</button>');
|
|
1545
|
+
const actions = actionHtml.length ? '<div class="span-actions">' + actionHtml.join("") + '</div>' : "";
|
|
1546
|
+
|
|
1547
|
+
if (node.type === "user.message") {
|
|
1548
|
+
return actions + '<div class="span-quote">' + escapeText(node.output || node.summary || "") + '</div>';
|
|
1549
|
+
}
|
|
1550
|
+
if (node.type === "assistant.message") {
|
|
1551
|
+
return actions + '<div class="span-section"><div class="span-section-title output">Structured Output</div>' + renderJson(node.output || node.summary || "") + '</div>';
|
|
1552
|
+
}
|
|
1553
|
+
if (node.type === "model.reasoning") {
|
|
1554
|
+
return actions + '<div class="reasoning-block"><span class="reasoning-comment">// Model reasoning</span>\\n' + escapeText(node.output || node.summary || "") + '</div>';
|
|
1555
|
+
}
|
|
1556
|
+
if (node.type === "tool.call" || node.type === "yielded.run") {
|
|
1557
|
+
return actions +
|
|
1558
|
+
'<div class="span-code-well">' + functionSignature(node.title, node.input || {}) + '</div>' +
|
|
1559
|
+
(node.output !== undefined ? '<div class="span-output-summary"><span>Output:</span><code>' + escapeText(short(pretty(node.output), 120)) + '</code></div>' : "") +
|
|
1560
|
+
'<div class="span-section"><div class="span-section-title">Input</div>' + renderJson(node.input || {}) + '</div>' +
|
|
1561
|
+
(node.output !== undefined ? '<div class="span-section"><div class="span-section-title output">Output</div>' + renderJson(node.output) + '</div>' : "");
|
|
1562
|
+
}
|
|
1563
|
+
if (node.type === "tool.result" || node.type === "execution.command") {
|
|
1564
|
+
return actions + '<div class="span-section"><div class="span-section-title output">Output</div>' + renderJson(node.output || node.input || "") + '</div>';
|
|
1565
|
+
}
|
|
1566
|
+
if (node.type === "agent.delegation") {
|
|
1567
|
+
return actions +
|
|
1568
|
+
'<div class="delegation-card"><div class="delegation-title">Agent Delegation · ' + escapeText(node.title || "subagent") + '</div><div class="delegation-query">' + escapeText(short(node.summary || pretty(node.input), 220)) + '</div></div>' +
|
|
1569
|
+
'<div class="span-section"><div class="span-section-title">Input</div>' + renderJson(node.input || {}) + '</div>' +
|
|
1570
|
+
(node.output !== undefined ? '<div class="span-section"><div class="span-section-title output">Output</div>' + renderJson(node.output) + '</div>' : "");
|
|
1571
|
+
}
|
|
1572
|
+
if (node.type === "agent.async") {
|
|
1573
|
+
const input = node.input && typeof node.input === "object" ? node.input : {};
|
|
1574
|
+
const startedBy = input.startedBy || "pibo_run_start";
|
|
1575
|
+
const runId = input.runId || node.runId || "";
|
|
1576
|
+
return actions +
|
|
1577
|
+
'<div class="delegation-card"><div class="delegation-title">Async Agent · ' + escapeText(node.title || "subagent") + '</div><div class="delegation-query">Started by ' + escapeText(startedBy) + (runId ? ' · ' + escapeText(runId) : "") + '</div></div>' +
|
|
1578
|
+
'<div class="span-section"><div class="span-section-title">Input</div>' + renderJson(node.input || {}) + '</div>' +
|
|
1579
|
+
(node.output !== undefined ? '<div class="span-section"><div class="span-section-title output">Run</div>' + renderJson(node.output) + '</div>' : "");
|
|
1580
|
+
}
|
|
1581
|
+
if (node.type === "error") {
|
|
1582
|
+
return actions + '<div class="span-section"><div class="span-section-title">Error</div>' + renderJson(node.error || node.output || "") + '</div>';
|
|
1583
|
+
}
|
|
1584
|
+
return actions + '<div class="span-section">' + renderJson(node.output || node.input || node.summary || "") + '</div>';
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
async function signIn() {
|
|
1588
|
+
const response = await fetch("/api/auth/sign-in/social", {
|
|
1589
|
+
method: "POST",
|
|
1590
|
+
headers: { "content-type": "application/json" },
|
|
1591
|
+
body: JSON.stringify({ provider: "google", callbackURL: "/apps/chat", disableRedirect: true }),
|
|
1592
|
+
});
|
|
1593
|
+
const data = await response.json();
|
|
1594
|
+
if (!response.ok || !data.url) {
|
|
1595
|
+
renderSignedOut(data.message || data.error || "Could not start Google sign in.");
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
location.href = data.url;
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
async function clearAuthSession() {
|
|
1602
|
+
await fetch("/api/auth/sign-out", {
|
|
1603
|
+
method: "POST",
|
|
1604
|
+
credentials: "same-origin",
|
|
1605
|
+
headers: { "content-type": "application/json" },
|
|
1606
|
+
body: "{}",
|
|
1607
|
+
});
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
async function signOut() {
|
|
1611
|
+
await clearAuthSession();
|
|
1612
|
+
location.reload();
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
function renderSignedOut(message) {
|
|
1616
|
+
userEl.replaceChildren();
|
|
1617
|
+
sessionTreeEl.innerHTML = "";
|
|
1618
|
+
contentEl.innerHTML = '<div class="placeholder">' + escapeText(message || "Sign in to start a Pibo session.") + '</div>';
|
|
1619
|
+
composer.closest(".composer-wrap").classList.add("hidden");
|
|
1620
|
+
const button = document.createElement("button");
|
|
1621
|
+
button.className = "primary";
|
|
1622
|
+
button.textContent = "Sign in with Google";
|
|
1623
|
+
button.addEventListener("click", signIn);
|
|
1624
|
+
userEl.append(button);
|
|
1625
|
+
sessionTitleEl.textContent = "Signed Out";
|
|
1626
|
+
sessionMetaEl.textContent = "";
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
function renderSignedIn(data) {
|
|
1630
|
+
userEl.replaceChildren();
|
|
1631
|
+
const label = document.createElement("span");
|
|
1632
|
+
label.textContent = data.identity.email || data.identity.name || data.identity.userId;
|
|
1633
|
+
userEl.append(label);
|
|
1634
|
+
const button = document.createElement("button");
|
|
1635
|
+
button.textContent = "Sign out";
|
|
1636
|
+
button.addEventListener("click", signOut);
|
|
1637
|
+
userEl.append(button);
|
|
1638
|
+
composer.closest(".composer-wrap").classList.remove("hidden");
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
function connectEvents() {
|
|
1642
|
+
if (eventSource) eventSource.close();
|
|
1643
|
+
if (!selectedPiboSessionId) return;
|
|
1644
|
+
eventSource = new EventSource("/api/chat/events?piboSessionId=" + encodeURIComponent(selectedPiboSessionId));
|
|
1645
|
+
eventSource.addEventListener("pibo", (event) => {
|
|
1646
|
+
const payload = JSON.parse(event.data);
|
|
1647
|
+
appendRawEvent({ type: payload.type, payload });
|
|
1648
|
+
if (payload.type !== "TEXT_MESSAGE_CONTENT" && payload.type !== "REASONING_MESSAGE_CONTENT") {
|
|
1649
|
+
void refreshTrace();
|
|
1650
|
+
}
|
|
1651
|
+
});
|
|
1652
|
+
eventSource.onerror = () => appendRawEvent({ type: "stream_error", payload: "Event stream disconnected." });
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
async function loadSession() {
|
|
1656
|
+
const response = await fetch("/api/chat/bootstrap");
|
|
1657
|
+
if (response.status === 401) {
|
|
1658
|
+
renderSignedOut();
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
const data = await response.json();
|
|
1662
|
+
if (response.status === 403) {
|
|
1663
|
+
await clearAuthSession().catch(() => {});
|
|
1664
|
+
renderSignedOut("Not authorized. Sign in with an allowed Google account.");
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
if (!response.ok) {
|
|
1668
|
+
renderSignedOut(data.error || "Could not load session.");
|
|
1669
|
+
return;
|
|
1670
|
+
}
|
|
1671
|
+
bootstrap = data;
|
|
1672
|
+
selectedPiboSessionId = selectedPiboSessionId || data.selectedPiboSessionId;
|
|
1673
|
+
ensureSelectedAgentProfile();
|
|
1674
|
+
renderSignedIn(data);
|
|
1675
|
+
renderArea();
|
|
1676
|
+
connectEvents();
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
function ensureSelectedAgentProfile() {
|
|
1680
|
+
const agents = (bootstrap && bootstrap.agents) || [];
|
|
1681
|
+
if (!agents.length) return "";
|
|
1682
|
+
const exists = agents.some(function(agent) {
|
|
1683
|
+
return agent.name === selectedAgentProfile || (agent.aliases || []).includes(selectedAgentProfile);
|
|
1684
|
+
});
|
|
1685
|
+
if (!selectedAgentProfile || !exists) {
|
|
1686
|
+
selectedAgentProfile = bootstrap.session && bootstrap.session.profile || agents[0].name;
|
|
1687
|
+
}
|
|
1688
|
+
localStorage.setItem("pibo.chat.newSessionProfile", selectedAgentProfile);
|
|
1689
|
+
return selectedAgentProfile;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
function renderArea() {
|
|
1693
|
+
document.querySelectorAll(".tab").forEach(function(tab) {
|
|
1694
|
+
tab.classList.toggle("active", tab.dataset.area === area);
|
|
1695
|
+
});
|
|
1696
|
+
document.querySelector("#sidebar-title").textContent = area[0].toUpperCase() + area.slice(1);
|
|
1697
|
+
newSessionButton.classList.toggle("hidden", area !== "sessions");
|
|
1698
|
+
if (area === "sessions") {
|
|
1699
|
+
renderSessions();
|
|
1700
|
+
void refreshTrace();
|
|
1701
|
+
return;
|
|
1702
|
+
}
|
|
1703
|
+
if (area === "agents") {
|
|
1704
|
+
renderAgents();
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
renderSettings();
|
|
1708
|
+
}
|
|
1709
|
+
function renderSessions() {
|
|
1710
|
+
sessionTreeEl.innerHTML = "";
|
|
1711
|
+
(bootstrap.sessions || []).forEach(function(node) { sessionTreeEl.append(renderSessionNode(node, 0)); });
|
|
1712
|
+
}
|
|
1713
|
+
function renderSessionNode(node, depth) {
|
|
1714
|
+
const children = node.children || [];
|
|
1715
|
+
const hasChildren = children.length > 0;
|
|
1716
|
+
if (sessionTreeHasSession(children, selectedPiboSessionId)) {
|
|
1717
|
+
openSessionNodes.add(node.piboSessionId);
|
|
1718
|
+
}
|
|
1719
|
+
const expanded = openSessionNodes.has(node.piboSessionId);
|
|
1720
|
+
const wrap = document.createElement("div");
|
|
1721
|
+
const row = document.createElement("div");
|
|
1722
|
+
row.className = "session-row" + (node.piboSessionId === selectedPiboSessionId ? " active" : "");
|
|
1723
|
+
row.style.paddingLeft = 8 + depth * 14 + "px";
|
|
1724
|
+
row.title = node.piboSessionId;
|
|
1725
|
+
if (hasChildren) {
|
|
1726
|
+
const toggle = document.createElement("button");
|
|
1727
|
+
toggle.type = "button";
|
|
1728
|
+
toggle.className = "session-toggle";
|
|
1729
|
+
toggle.textContent = expanded ? "v" : ">";
|
|
1730
|
+
toggle.setAttribute("aria-expanded", String(expanded));
|
|
1731
|
+
toggle.setAttribute("aria-label", expanded ? "Collapse Subsessions" : "Expand Subsessions");
|
|
1732
|
+
toggle.title = expanded ? "Collapse Subsessions" : "Expand Subsessions";
|
|
1733
|
+
toggle.addEventListener("click", function() {
|
|
1734
|
+
if (openSessionNodes.has(node.piboSessionId)) openSessionNodes.delete(node.piboSessionId);
|
|
1735
|
+
else openSessionNodes.add(node.piboSessionId);
|
|
1736
|
+
renderSessions();
|
|
1737
|
+
});
|
|
1738
|
+
row.append(toggle);
|
|
1739
|
+
} else {
|
|
1740
|
+
row.append(document.createElement("span"));
|
|
1741
|
+
}
|
|
1742
|
+
const select = document.createElement("button");
|
|
1743
|
+
select.type = "button";
|
|
1744
|
+
select.className = "session-select";
|
|
1745
|
+
select.innerHTML =
|
|
1746
|
+
'<span><span class="session-title">' + escapeText(node.title) + '</span><span class="session-id">' + escapeText(node.piboSessionId) + '</span></span>' +
|
|
1747
|
+
'<span class="status-dot ' + escapeText(node.status) + '"></span>';
|
|
1748
|
+
select.addEventListener("click", function() { selectSession(node.piboSessionId); });
|
|
1749
|
+
row.append(select);
|
|
1750
|
+
wrap.append(row);
|
|
1751
|
+
if (expanded) children.forEach(function(child) { wrap.append(renderSessionNode(child, depth + 1)); });
|
|
1752
|
+
return wrap;
|
|
1753
|
+
}
|
|
1754
|
+
function sessionTreeHasSession(nodes, piboSessionId) {
|
|
1755
|
+
return (nodes || []).some(function(node) {
|
|
1756
|
+
return node.piboSessionId === piboSessionId || sessionTreeHasSession(node.children, piboSessionId);
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
async function selectSession(piboSessionId) {
|
|
1760
|
+
selectedPiboSessionId = piboSessionId;
|
|
1761
|
+
connectEvents();
|
|
1762
|
+
await refreshBootstrap(false);
|
|
1763
|
+
renderArea();
|
|
1764
|
+
}
|
|
1765
|
+
async function createSession(profile) {
|
|
1766
|
+
const selectedProfile = profile || ensureSelectedAgentProfile();
|
|
1767
|
+
const created = await postJson("/api/chat/sessions", selectedProfile ? { profile: selectedProfile } : {});
|
|
1768
|
+
selectedPiboSessionId = created.session && created.session.id;
|
|
1769
|
+
connectEvents();
|
|
1770
|
+
await refreshBootstrap(false);
|
|
1771
|
+
renderArea();
|
|
1772
|
+
}
|
|
1773
|
+
async function refreshBootstrap(keepTrace) {
|
|
1774
|
+
const response = await fetch("/api/chat/bootstrap?piboSessionId=" + encodeURIComponent(selectedPiboSessionId || ""));
|
|
1775
|
+
if (!response.ok) return;
|
|
1776
|
+
bootstrap = await response.json();
|
|
1777
|
+
selectedPiboSessionId = bootstrap.selectedPiboSessionId;
|
|
1778
|
+
if (!keepTrace) renderSessions();
|
|
1779
|
+
}
|
|
1780
|
+
async function refreshTrace() {
|
|
1781
|
+
if (!selectedPiboSessionId) return;
|
|
1782
|
+
const response = await fetch("/api/chat/trace?piboSessionId=" + encodeURIComponent(selectedPiboSessionId) + "&includeRawEvents=true&rawEventsLimit=80");
|
|
1783
|
+
if (!response.ok) return;
|
|
1784
|
+
const trace = await response.json();
|
|
1785
|
+
sessionTitleEl.textContent = trace.title || selectedPiboSessionId;
|
|
1786
|
+
sessionMetaEl.textContent = trace.piboSessionId + " · " + trace.piSessionId;
|
|
1787
|
+
renderTrace(trace.nodes || []);
|
|
1788
|
+
renderRawEvents(trace.rawEvents || []);
|
|
1789
|
+
}
|
|
1790
|
+
function renderTrace(nodes) {
|
|
1791
|
+
const visible = nodes.filter(function(node) { return showThinking || node.type !== "model.reasoning"; });
|
|
1792
|
+
if (!visible.length) {
|
|
1793
|
+
contentEl.innerHTML = '<div class="placeholder">No trace events yet.</div>';
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
const list = document.createElement("div");
|
|
1797
|
+
list.className = "trace-list";
|
|
1798
|
+
visible.forEach(function(node) { list.append(renderTraceNode(node, 0)); });
|
|
1799
|
+
contentEl.replaceChildren(list);
|
|
1800
|
+
}
|
|
1801
|
+
function renderTraceNode(node, depth) {
|
|
1802
|
+
const wrapper = document.createElement("article");
|
|
1803
|
+
const mappedSpanType = spanType(node.type);
|
|
1804
|
+
wrapper.className = "span-card " + spanStatusClass(node.status) + (openNodes.has(node.id) ? " open" : "");
|
|
1805
|
+
wrapper.dataset.spanType = mappedSpanType;
|
|
1806
|
+
wrapper.dataset.nodeId = node.id;
|
|
1807
|
+
wrapper.style.marginLeft = Math.min(depth * 12, 96) + "px";
|
|
1808
|
+
const header = document.createElement("button");
|
|
1809
|
+
header.className = "span-header";
|
|
1810
|
+
const statusClass = node.status === "running" ? "running" : node.status === "error" ? "error" : "";
|
|
1811
|
+
header.innerHTML =
|
|
1812
|
+
'<span class="span-chevron">' + (openNodes.has(node.id) ? "v" : ">") + '</span>' +
|
|
1813
|
+
'<span class="span-icon">' + escapeText(nodeIcon(node.type)) + '</span>' +
|
|
1814
|
+
'<span><span class="span-type-label">' + escapeText(spanLabel(node.type)) + '</span><span class="span-title">' + escapeText(node.title || "") + (node.summary ? " · " + escapeText(short(node.summary, 160)) : "") + '</span></span>' +
|
|
1815
|
+
'<span class="span-meta"><span class="badge ' + statusClass + '">' + escapeText(node.status) + '</span></span>';
|
|
1816
|
+
header.addEventListener("click", function() {
|
|
1817
|
+
if (openNodes.has(node.id)) openNodes.delete(node.id); else openNodes.add(node.id);
|
|
1818
|
+
saveOpenNodes();
|
|
1819
|
+
wrapper.classList.toggle("open");
|
|
1820
|
+
header.querySelector(".span-chevron").textContent = wrapper.classList.contains("open") ? "v" : ">";
|
|
1821
|
+
});
|
|
1822
|
+
wrapper.append(header);
|
|
1823
|
+
const body = document.createElement("div");
|
|
1824
|
+
body.className = "span-body";
|
|
1825
|
+
body.innerHTML = renderSpanContent(node);
|
|
1826
|
+
body.querySelectorAll(".fork-button").forEach(function(button) {
|
|
1827
|
+
button.addEventListener("click", function(event) {
|
|
1828
|
+
event.stopPropagation();
|
|
1829
|
+
void forkFrom(button.dataset.entryId);
|
|
1830
|
+
});
|
|
1831
|
+
});
|
|
1832
|
+
body.querySelectorAll(".session-link").forEach(function(button) {
|
|
1833
|
+
button.addEventListener("click", function(event) {
|
|
1834
|
+
event.stopPropagation();
|
|
1835
|
+
void selectSession(button.dataset.piboSessionId);
|
|
1836
|
+
});
|
|
1837
|
+
});
|
|
1838
|
+
if (node.children && node.children.length) {
|
|
1839
|
+
const childWrap = document.createElement("div");
|
|
1840
|
+
childWrap.className = "children span-children";
|
|
1841
|
+
node.children.filter(function(child) { return showThinking || child.type !== "model.reasoning"; }).forEach(function(child) {
|
|
1842
|
+
childWrap.append(renderTraceNode(child, depth + 1));
|
|
1843
|
+
});
|
|
1844
|
+
body.append(childWrap);
|
|
1845
|
+
}
|
|
1846
|
+
wrapper.append(body);
|
|
1847
|
+
return wrapper;
|
|
1848
|
+
}
|
|
1849
|
+
function appendRawEvent(event) {
|
|
1850
|
+
const item = document.createElement("div");
|
|
1851
|
+
item.className = "raw-event";
|
|
1852
|
+
item.innerHTML = '<div class="raw-event-type">' + escapeText(event.type) + '</div><pre class="payload">' + escapeText(pretty(event.payload)) + '</pre>';
|
|
1853
|
+
rawLogEl.prepend(item);
|
|
1854
|
+
}
|
|
1855
|
+
function renderRawEvents(events) {
|
|
1856
|
+
rawLogEl.innerHTML = "";
|
|
1857
|
+
events.slice(-80).reverse().forEach(appendRawEvent);
|
|
1858
|
+
}
|
|
1859
|
+
function renderAgents() {
|
|
1860
|
+
sessionTitleEl.textContent = "Agents";
|
|
1861
|
+
sessionMetaEl.textContent = "Profile selection";
|
|
1862
|
+
const agents = (bootstrap && bootstrap.agents) || [];
|
|
1863
|
+
ensureSelectedAgentProfile();
|
|
1864
|
+
sessionTreeEl.innerHTML = agents.map(function(agent) {
|
|
1865
|
+
const active = agent.name === selectedAgentProfile ? " active" : "";
|
|
1866
|
+
return '<button class="session-row' + active + '" data-profile="' + escapeText(agent.name) + '"><span></span><span><span class="session-title">' + escapeText(agent.name) + '</span><span class="session-id">' + escapeText((agent.aliases || []).join(", ") || "profile") + '</span></span><span class="status-dot"></span></button>';
|
|
1867
|
+
}).join("");
|
|
1868
|
+
sessionTreeEl.querySelectorAll("[data-profile]").forEach(function(button) {
|
|
1869
|
+
button.addEventListener("click", function() {
|
|
1870
|
+
selectedAgentProfile = button.dataset.profile;
|
|
1871
|
+
localStorage.setItem("pibo.chat.newSessionProfile", selectedAgentProfile);
|
|
1872
|
+
renderAgents();
|
|
1873
|
+
});
|
|
1874
|
+
});
|
|
1875
|
+
contentEl.innerHTML = '<div class="trace-list">' + agents.map(function(agent) {
|
|
1876
|
+
const selected = agent.name === selectedAgentProfile ? "selected" : "available";
|
|
1877
|
+
return '<article class="trace-node open" data-type="agent.turn"><div class="trace-header"><span class="trace-icon">A</span><span><span class="trace-label">' + escapeText(agent.name) + '</span><span class="trace-summary">' + escapeText(agent.description || "No description") + '</span></span><span class="trace-actions"><button class="ghost profile-select" data-profile="' + escapeText(agent.name) + '">' + selected + '</button><button class="ghost profile-create" data-profile="' + escapeText(agent.name) + '">New Session</button></span></div><div class="trace-body"><pre class="payload">' + escapeText(pretty(agent)) + '</pre></div></article>';
|
|
1878
|
+
}).join("") + '</div>';
|
|
1879
|
+
contentEl.querySelectorAll(".profile-select").forEach(function(button) {
|
|
1880
|
+
button.addEventListener("click", function() {
|
|
1881
|
+
selectedAgentProfile = button.dataset.profile;
|
|
1882
|
+
localStorage.setItem("pibo.chat.newSessionProfile", selectedAgentProfile);
|
|
1883
|
+
renderAgents();
|
|
1884
|
+
});
|
|
1885
|
+
});
|
|
1886
|
+
contentEl.querySelectorAll(".profile-create").forEach(function(button) {
|
|
1887
|
+
button.addEventListener("click", function() {
|
|
1888
|
+
selectedAgentProfile = button.dataset.profile;
|
|
1889
|
+
localStorage.setItem("pibo.chat.newSessionProfile", selectedAgentProfile);
|
|
1890
|
+
void createSession(selectedAgentProfile);
|
|
1891
|
+
});
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
function renderSettings() {
|
|
1895
|
+
sessionTitleEl.textContent = "Settings";
|
|
1896
|
+
sessionMetaEl.textContent = "Browser-local V1 settings";
|
|
1897
|
+
sessionTreeEl.innerHTML = '<div class="placeholder">Settings navigation placeholder.</div>';
|
|
1898
|
+
contentEl.innerHTML = '<div class="placeholder">Thinking display and trace expansion state are stored in this browser.</div>';
|
|
1899
|
+
}
|
|
1900
|
+
function availableCommands() {
|
|
1901
|
+
const actions = (bootstrap && bootstrap.capabilities && bootstrap.capabilities.actions) || [];
|
|
1902
|
+
const commands = [];
|
|
1903
|
+
actions.forEach(function(action) {
|
|
1904
|
+
(action.slashCommands || []).forEach(function(command) {
|
|
1905
|
+
if (command !== "tree") commands.push({ slash: "/" + command, action: action.name, description: action.description || action.name });
|
|
1906
|
+
});
|
|
1907
|
+
});
|
|
1908
|
+
commands.push({ slash: "/thinking-show", action: "thinking-show", description: "Toggle historical thinking display in this browser." });
|
|
1909
|
+
return commands;
|
|
1910
|
+
}
|
|
1911
|
+
function renderCommandMenu() {
|
|
1912
|
+
const query = messageInput.value.trim();
|
|
1913
|
+
if (!query.startsWith("/")) { commandMenu.classList.add("hidden"); return; }
|
|
1914
|
+
const commands = availableCommands().filter(function(command) { return command.slash.startsWith(query.split(/\\s+/)[0]); });
|
|
1915
|
+
if (!commands.length) { commandMenu.classList.add("hidden"); return; }
|
|
1916
|
+
commandIndex = Math.min(commandIndex, commands.length - 1);
|
|
1917
|
+
commandMenu.innerHTML = "";
|
|
1918
|
+
commands.forEach(function(command, index) {
|
|
1919
|
+
const item = document.createElement("button");
|
|
1920
|
+
item.type = "button";
|
|
1921
|
+
item.className = "command-item" + (index === commandIndex ? " active" : "");
|
|
1922
|
+
item.innerHTML = '<span class="command-name">' + escapeText(command.slash) + '</span><span class="command-desc">' + escapeText(command.description) + '</span>';
|
|
1923
|
+
item.addEventListener("click", function() { void runCommand(command); });
|
|
1924
|
+
commandMenu.append(item);
|
|
1925
|
+
});
|
|
1926
|
+
commandMenu.classList.remove("hidden");
|
|
1927
|
+
}
|
|
1928
|
+
async function runCommand(command) {
|
|
1929
|
+
commandMenu.classList.add("hidden");
|
|
1930
|
+
const text = messageInput.value.trim();
|
|
1931
|
+
messageInput.value = "";
|
|
1932
|
+
if (command.action === "thinking-show") {
|
|
1933
|
+
showThinking = !showThinking;
|
|
1934
|
+
localStorage.setItem("pibo.chat.showThinking", String(showThinking));
|
|
1935
|
+
updateThinkingButton();
|
|
1936
|
+
await refreshTrace();
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
const levelMatch = text.match(/^\\/thinking\\s+(\\S+)/);
|
|
1940
|
+
const params = levelMatch ? { level: levelMatch[1] } : undefined;
|
|
1941
|
+
const result = await postJson("/api/chat/action", { piboSessionId: selectedPiboSessionId, action: command.action, params: params });
|
|
1942
|
+
appendRawEvent({ type: "command_result", payload: result });
|
|
1943
|
+
if (command.action === "session.clone" && result && result.result && result.result.piboSessionId) {
|
|
1944
|
+
await selectSession(result.result.piboSessionId);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
async function forkFrom(entryId) {
|
|
1948
|
+
const result = await postJson("/api/chat/action", { piboSessionId: selectedPiboSessionId, action: "session.fork", params: { entryId: entryId } });
|
|
1949
|
+
appendRawEvent({ type: "fork_result", payload: result });
|
|
1950
|
+
pendingForkResult = result && result.result ? result.result : undefined;
|
|
1951
|
+
if (pendingForkResult && typeof pendingForkResult.selectedText === "string") {
|
|
1952
|
+
messageInput.value = pendingForkResult.selectedText;
|
|
1953
|
+
messageInput.focus();
|
|
1954
|
+
}
|
|
1955
|
+
if (pendingForkResult && pendingForkResult.piboSessionId) {
|
|
1956
|
+
await selectSession(pendingForkResult.piboSessionId);
|
|
1957
|
+
} else {
|
|
1958
|
+
await refreshBootstrap(false);
|
|
1959
|
+
await refreshTrace();
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
async function postJson(url, payload) {
|
|
1963
|
+
const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload) });
|
|
1964
|
+
const data = await response.json().catch(function() { return { error: "Request failed" }; });
|
|
1965
|
+
if (!response.ok) throw new Error(data.error || "Request failed");
|
|
1966
|
+
return data;
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
newSessionButton.addEventListener("click", function() { void createSession(); });
|
|
1970
|
+
composer.addEventListener("submit", async (event) => {
|
|
1971
|
+
event.preventDefault();
|
|
1972
|
+
const text = messageInput.value.trim();
|
|
1973
|
+
if (!text) return;
|
|
1974
|
+
const command = availableCommands().find(function(candidate) { return text.split(/\\s+/)[0] === candidate.slash; });
|
|
1975
|
+
if (text.startsWith("/") && command) {
|
|
1976
|
+
await runCommand(command);
|
|
1977
|
+
return;
|
|
1978
|
+
}
|
|
1979
|
+
messageInput.value = "";
|
|
1980
|
+
await postJson("/api/chat/message", { piboSessionId: selectedPiboSessionId, text: text });
|
|
1981
|
+
await refreshTrace();
|
|
1982
|
+
});
|
|
1983
|
+
messageInput.addEventListener("input", renderCommandMenu);
|
|
1984
|
+
messageInput.addEventListener("keydown", function(event) {
|
|
1985
|
+
if (commandMenu.classList.contains("hidden")) {
|
|
1986
|
+
if (event.key === "Enter" && !event.shiftKey) {
|
|
1987
|
+
event.preventDefault();
|
|
1988
|
+
composer.requestSubmit();
|
|
1989
|
+
}
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1992
|
+
const count = commandMenu.querySelectorAll(".command-item").length;
|
|
1993
|
+
if (event.key === "ArrowDown") { event.preventDefault(); commandIndex = (commandIndex + 1) % count; renderCommandMenu(); }
|
|
1994
|
+
if (event.key === "ArrowUp") { event.preventDefault(); commandIndex = (commandIndex - 1 + count) % count; renderCommandMenu(); }
|
|
1995
|
+
if (event.key === "Enter" && !event.shiftKey) {
|
|
1996
|
+
const item = commandMenu.querySelectorAll(".command-item")[commandIndex];
|
|
1997
|
+
if (item) { event.preventDefault(); item.click(); }
|
|
1998
|
+
}
|
|
1999
|
+
});
|
|
2000
|
+
document.querySelectorAll(".tab").forEach(function(tab) {
|
|
2001
|
+
tab.addEventListener("click", function() { area = tab.dataset.area; renderArea(); });
|
|
2002
|
+
});
|
|
2003
|
+
document.querySelector("#refresh").addEventListener("click", function() { void refreshBootstrap(false).then(renderArea); });
|
|
2004
|
+
document.querySelector("#clear-local").addEventListener("click", function() { rawLogEl.innerHTML = ""; });
|
|
2005
|
+
document.querySelector("#collapse-all").addEventListener("click", function() { openNodes.clear(); saveOpenNodes(); void refreshTrace(); });
|
|
2006
|
+
document.querySelector("#expand-all").addEventListener("click", function() {
|
|
2007
|
+
contentEl.querySelectorAll(".span-card").forEach(function(node) {
|
|
2008
|
+
if (node.dataset.nodeId) openNodes.add(node.dataset.nodeId);
|
|
2009
|
+
node.classList.add("open");
|
|
2010
|
+
const chevron = node.querySelector(".span-chevron");
|
|
2011
|
+
if (chevron) chevron.textContent = "v";
|
|
2012
|
+
});
|
|
2013
|
+
saveOpenNodes();
|
|
2014
|
+
});
|
|
2015
|
+
document.querySelector("#expand-one").addEventListener("click", function() {
|
|
2016
|
+
openNodes.clear();
|
|
2017
|
+
contentEl.querySelectorAll(".trace-list > .span-card").forEach(function(node) {
|
|
2018
|
+
if (node.dataset.nodeId) openNodes.add(node.dataset.nodeId);
|
|
2019
|
+
node.classList.add("open");
|
|
2020
|
+
const chevron = node.querySelector(".span-chevron");
|
|
2021
|
+
if (chevron) chevron.textContent = "v";
|
|
2022
|
+
});
|
|
2023
|
+
saveOpenNodes();
|
|
2024
|
+
});
|
|
2025
|
+
function updateThinkingButton() {
|
|
2026
|
+
document.querySelector("#thinking-toggle").textContent = showThinking ? "Thinking On" : "Thinking Off";
|
|
2027
|
+
}
|
|
2028
|
+
document.querySelector("#thinking-toggle").addEventListener("click", async function() {
|
|
2029
|
+
showThinking = !showThinking;
|
|
2030
|
+
localStorage.setItem("pibo.chat.showThinking", String(showThinking));
|
|
2031
|
+
updateThinkingButton();
|
|
2032
|
+
await refreshTrace();
|
|
2033
|
+
});
|
|
2034
|
+
document.querySelector("#fork-stay").addEventListener("click", function() {
|
|
2035
|
+
forkModal.classList.add("hidden");
|
|
2036
|
+
const previousFile = pendingForkResult && pendingForkResult.previous && pendingForkResult.previous.sessionFile;
|
|
2037
|
+
const targetPiboSessionId = pendingForkResult && pendingForkResult.piboSessionId ? pendingForkResult.piboSessionId : selectedPiboSessionId;
|
|
2038
|
+
pendingForkResult = undefined;
|
|
2039
|
+
messageInput.value = pendingForkComposerText || "";
|
|
2040
|
+
pendingForkComposerText = undefined;
|
|
2041
|
+
if (previousFile) {
|
|
2042
|
+
void postJson("/api/chat/action", { piboSessionId: targetPiboSessionId, action: "session.switch", params: { sessionFile: previousFile } })
|
|
2043
|
+
.then(function(result) { appendRawEvent({ type: "fork_restore", payload: result }); return refreshTrace(); })
|
|
2044
|
+
.catch(function(error) { appendRawEvent({ type: "fork_restore_error", payload: String(error) }); });
|
|
2045
|
+
}
|
|
2046
|
+
});
|
|
2047
|
+
document.querySelector("#fork-switch").addEventListener("click", async function() {
|
|
2048
|
+
forkModal.classList.add("hidden");
|
|
2049
|
+
const targetPiboSessionId = pendingForkResult && pendingForkResult.piboSessionId ? pendingForkResult.piboSessionId : selectedPiboSessionId;
|
|
2050
|
+
pendingForkResult = undefined;
|
|
2051
|
+
pendingForkComposerText = undefined;
|
|
2052
|
+
if (targetPiboSessionId) await selectSession(targetPiboSessionId);
|
|
2053
|
+
});
|
|
2054
|
+
|
|
2055
|
+
updateThinkingButton();
|
|
2056
|
+
loadSession();
|
|
2057
|
+
</script>
|
|
2058
|
+
</body>
|
|
2059
|
+
</html>`;
|
|
2060
|
+
}
|
|
2061
|
+
export function createChatWebApp(options = {}) {
|
|
2062
|
+
const defaultProfile = options.defaultProfile ?? "pibo-minimal";
|
|
2063
|
+
const storagePath = options.readModelPath;
|
|
2064
|
+
const state = {
|
|
2065
|
+
readModel: createReadModel(storagePath),
|
|
2066
|
+
eventLog: createEventLog(options.eventLogPath ?? storagePath),
|
|
2067
|
+
roomStore: createRoomStore(options.roomStorePath ?? storagePath),
|
|
2068
|
+
agentStore: createAgentStore(options.agentStorePath ?? storagePath),
|
|
2069
|
+
reliabilityStore: createReliabilityStore(options.reliabilityStorePath),
|
|
2070
|
+
traceCache: new Map(),
|
|
2071
|
+
liveListeners: new Set(),
|
|
2072
|
+
};
|
|
2073
|
+
const requireSession = (request, context) => context.requireSession({
|
|
2074
|
+
request,
|
|
2075
|
+
});
|
|
2076
|
+
return {
|
|
2077
|
+
name: CHAT_WEB_APP_NAME,
|
|
2078
|
+
mountPath: CHAT_WEB_MOUNT_PATH,
|
|
2079
|
+
apiPrefix: CHAT_WEB_API_PREFIX,
|
|
2080
|
+
async handleRequest(request, context) {
|
|
2081
|
+
const url = new URL(request.url);
|
|
2082
|
+
ensureEventIndexing(state, context);
|
|
2083
|
+
ensureCustomAgentProfiles(state, context);
|
|
2084
|
+
const builtAsset = responseBuiltChatAsset(request, url.pathname);
|
|
2085
|
+
if (builtAsset)
|
|
2086
|
+
return builtAsset;
|
|
2087
|
+
if (isChatAppPath(url.pathname) && request.method === "GET") {
|
|
2088
|
+
return responseBuiltChatIndex() ?? responseHtml(createChatHtml());
|
|
2089
|
+
}
|
|
2090
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/bootstrap` && request.method === "GET") {
|
|
2091
|
+
const webSession = await requireSession(request, context);
|
|
2092
|
+
const includeArchived = parseBooleanSearchParam(url, "includeArchived");
|
|
2093
|
+
const markRead = parseBooleanSearchParam(url, "markRead");
|
|
2094
|
+
const requestedRoomId = url.searchParams.get("roomId") || undefined;
|
|
2095
|
+
const principalId = principalIdFor(webSession);
|
|
2096
|
+
const selectedSession = resolveRequestedSession(state, context, webSession, defaultProfile, url.searchParams.get("piboSessionId") || undefined, requestedRoomId);
|
|
2097
|
+
const selectedRoomId = selectedRoomIdForSession(state, context, selectedSession);
|
|
2098
|
+
const ownedSessions = listOwnedSessions(context, webSession);
|
|
2099
|
+
const roomSessions = visibleSessionsInRoom({
|
|
2100
|
+
state,
|
|
2101
|
+
context,
|
|
2102
|
+
webSession,
|
|
2103
|
+
sessions: ownedSessions,
|
|
2104
|
+
selectedSession,
|
|
2105
|
+
selectedRoomId,
|
|
2106
|
+
includeArchived,
|
|
2107
|
+
});
|
|
2108
|
+
state.roomStore.ensureDefaultRoom({
|
|
2109
|
+
ownerScope: webSession.ownerScope,
|
|
2110
|
+
principalId,
|
|
2111
|
+
});
|
|
2112
|
+
if (markRead) {
|
|
2113
|
+
markRoomRead(state, selectedRoomId, principalId);
|
|
2114
|
+
markSessionsRead(state, roomSessions, principalId);
|
|
2115
|
+
}
|
|
2116
|
+
indexOwnedSessions(state.readModel, roomSessions);
|
|
2117
|
+
const sessionUnreadCounts = buildSessionUnreadCounts(state, ownedSessions, principalId);
|
|
2118
|
+
const sessions = await buildSessionNodes(roomSessions, state.readModel.listSessions(), process.cwd(), sessionUnreadCounts);
|
|
2119
|
+
const roomTree = state.roomStore.listRoomTree(webSession.ownerScope);
|
|
2120
|
+
const roomUnreadCounts = buildRoomUnreadCounts(state, roomTree, principalId);
|
|
2121
|
+
const rooms = roomsWithUnreadCounts(roomTree, roomUnreadCounts);
|
|
2122
|
+
return responseJson({
|
|
2123
|
+
identity: webSession.authSession.identity,
|
|
2124
|
+
session: selectedSession,
|
|
2125
|
+
room: state.roomStore.getRoom(selectedRoomId),
|
|
2126
|
+
selectedRoomId,
|
|
2127
|
+
selectedPiboSessionId: selectedSession.id,
|
|
2128
|
+
rooms,
|
|
2129
|
+
sessions,
|
|
2130
|
+
agents: context.channelContext.getProfiles?.() ?? [],
|
|
2131
|
+
customAgents: state.agentStore.list(webSession.ownerScope, { includeArchived: true }),
|
|
2132
|
+
agentCatalog: await buildAgentCatalog(context),
|
|
2133
|
+
capabilities: {
|
|
2134
|
+
actions: context.channelContext.getGatewayActions(),
|
|
2135
|
+
},
|
|
2136
|
+
});
|
|
2137
|
+
}
|
|
2138
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/agent-catalog` && request.method === "GET") {
|
|
2139
|
+
await requireSession(request, context);
|
|
2140
|
+
return responseJson({
|
|
2141
|
+
catalog: await buildAgentCatalog(context),
|
|
2142
|
+
profiles: context.channelContext.getProfiles?.() ?? [],
|
|
2143
|
+
});
|
|
2144
|
+
}
|
|
2145
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/pi-packages` && request.method === "GET") {
|
|
2146
|
+
await requireSession(request, context);
|
|
2147
|
+
return responseJson({ packages: listPiPackages() });
|
|
2148
|
+
}
|
|
2149
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/pi-packages` && request.method === "POST") {
|
|
2150
|
+
requireSameOriginJsonRequest(request);
|
|
2151
|
+
await requireSession(request, context);
|
|
2152
|
+
const body = await readJsonBody(request);
|
|
2153
|
+
const source = normalizePiPackageWebSource(body.source);
|
|
2154
|
+
const pkg = upsertPiPackage(await inspectPiPackageSource(source, process.cwd()), process.cwd());
|
|
2155
|
+
return responseJson({ package: pkg }, { status: 201 });
|
|
2156
|
+
}
|
|
2157
|
+
const piPackageId = piPackageResourceId(url.pathname);
|
|
2158
|
+
if (piPackageId && request.method === "GET") {
|
|
2159
|
+
await requireSession(request, context);
|
|
2160
|
+
const pkg = findPiPackage(piPackageId);
|
|
2161
|
+
if (!pkg)
|
|
2162
|
+
throw new PiboWebHttpError("Pi package is not registered", 404);
|
|
2163
|
+
return responseJson({ package: pkg });
|
|
2164
|
+
}
|
|
2165
|
+
if (piPackageId && request.method === "PATCH") {
|
|
2166
|
+
requireSameOriginJsonRequest(request);
|
|
2167
|
+
await requireSession(request, context);
|
|
2168
|
+
const existing = findPiPackage(piPackageId);
|
|
2169
|
+
if (!existing)
|
|
2170
|
+
throw new PiboWebHttpError("Pi package is not registered", 404);
|
|
2171
|
+
const body = await readJsonBody(request);
|
|
2172
|
+
let pkg = existing;
|
|
2173
|
+
let changed = false;
|
|
2174
|
+
if (body.source !== undefined) {
|
|
2175
|
+
const source = normalizePiPackageWebSource(body.source);
|
|
2176
|
+
pkg = upsertPiPackage(await inspectPiPackageSource(source, process.cwd()), process.cwd());
|
|
2177
|
+
changed = true;
|
|
2178
|
+
}
|
|
2179
|
+
if (body.enabled !== undefined) {
|
|
2180
|
+
if (typeof body.enabled !== "boolean")
|
|
2181
|
+
throw new PiboWebHttpError("enabled must be a boolean", 400);
|
|
2182
|
+
const updated = setPiPackageEnabled(pkg.id, body.enabled);
|
|
2183
|
+
if (!updated)
|
|
2184
|
+
throw new PiboWebHttpError("Pi package is not registered", 404);
|
|
2185
|
+
pkg = updated;
|
|
2186
|
+
changed = true;
|
|
2187
|
+
}
|
|
2188
|
+
if (!changed)
|
|
2189
|
+
throw new PiboWebHttpError("No Pi package update fields provided", 400);
|
|
2190
|
+
return responseJson({ package: pkg });
|
|
2191
|
+
}
|
|
2192
|
+
if (piPackageId && request.method === "DELETE") {
|
|
2193
|
+
requireSameOriginJsonRequest(request);
|
|
2194
|
+
await requireSession(request, context);
|
|
2195
|
+
const existing = findPiPackage(piPackageId);
|
|
2196
|
+
if (!existing)
|
|
2197
|
+
throw new PiboWebHttpError("Pi package is not registered", 404);
|
|
2198
|
+
const affectedAgents = agentsSelectingPiPackage(state, piPackageId);
|
|
2199
|
+
if (affectedAgents.length > 0) {
|
|
2200
|
+
throw new PiboWebHttpError(`Pi package is selected by custom agents: ${affectedAgents.map((agent) => agent.profileName).join(", ")}`, 409);
|
|
2201
|
+
}
|
|
2202
|
+
const removed = removePiPackage(piPackageId);
|
|
2203
|
+
return responseJson({ removedPackage: removed });
|
|
2204
|
+
}
|
|
2205
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/base-prompt` && request.method === "GET") {
|
|
2206
|
+
await requireSession(request, context);
|
|
2207
|
+
return responseJson({ basePrompt: await readPiboBasePrompt(process.cwd()) });
|
|
2208
|
+
}
|
|
2209
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/base-prompt` && request.method === "PATCH") {
|
|
2210
|
+
requireSameOriginJsonRequest(request);
|
|
2211
|
+
await requireSession(request, context);
|
|
2212
|
+
const body = await readJsonBody(request);
|
|
2213
|
+
return responseJson({ basePrompt: setPiboBasePromptMode(normalizeBasePromptMode(body.mode), process.cwd()) });
|
|
2214
|
+
}
|
|
2215
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/base-prompt/custom` && request.method === "PUT") {
|
|
2216
|
+
requireSameOriginJsonRequest(request);
|
|
2217
|
+
await requireSession(request, context);
|
|
2218
|
+
const body = await readJsonBody(request);
|
|
2219
|
+
return responseJson({ basePrompt: await savePiboCustomBasePrompt(normalizeBasePromptMarkdown(body.markdown), process.cwd()) });
|
|
2220
|
+
}
|
|
2221
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/compaction-prompt` && request.method === "GET") {
|
|
2222
|
+
await requireSession(request, context);
|
|
2223
|
+
return responseJson({ compactionPrompt: await readPiboCompactionPrompt(process.cwd()) });
|
|
2224
|
+
}
|
|
2225
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/compaction-prompt` && request.method === "PATCH") {
|
|
2226
|
+
requireSameOriginJsonRequest(request);
|
|
2227
|
+
await requireSession(request, context);
|
|
2228
|
+
const body = await readJsonBody(request);
|
|
2229
|
+
return responseJson({ compactionPrompt: setPiboCompactionPromptMode(normalizeCompactionPromptMode(body.mode), process.cwd()) });
|
|
2230
|
+
}
|
|
2231
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/compaction-prompt/custom` && request.method === "PUT") {
|
|
2232
|
+
requireSameOriginJsonRequest(request);
|
|
2233
|
+
await requireSession(request, context);
|
|
2234
|
+
const body = await readJsonBody(request);
|
|
2235
|
+
return responseJson({ compactionPrompt: await savePiboCustomCompactionPrompt(normalizeCompactionPromptMarkdown(body.markdown), process.cwd()) });
|
|
2236
|
+
}
|
|
2237
|
+
const mcpServerName = mcpServerResourceName(url.pathname);
|
|
2238
|
+
if (mcpServerName && request.method === "PATCH") {
|
|
2239
|
+
requireSameOriginJsonRequest(request);
|
|
2240
|
+
await requireSession(request, context);
|
|
2241
|
+
const body = await readJsonBody(request);
|
|
2242
|
+
const server = await setMcpServerDescription(mcpServerName, normalizeMcpServerDescriptionBody(body.description));
|
|
2243
|
+
return responseJson({ server });
|
|
2244
|
+
}
|
|
2245
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/agents` && request.method === "GET") {
|
|
2246
|
+
const webSession = await requireSession(request, context);
|
|
2247
|
+
const includeArchived = parseBooleanSearchParam(url, "includeArchived");
|
|
2248
|
+
return responseJson({ agents: state.agentStore.list(webSession.ownerScope, { includeArchived }) });
|
|
2249
|
+
}
|
|
2250
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/agents` && request.method === "POST") {
|
|
2251
|
+
requireSameOriginJsonRequest(request);
|
|
2252
|
+
const webSession = await requireSession(request, context);
|
|
2253
|
+
const body = await readJsonBody(request);
|
|
2254
|
+
const input = createAgentInput(webSession.ownerScope, body);
|
|
2255
|
+
requireAgentProfileNameAvailable(state, context, input.displayName);
|
|
2256
|
+
const agent = state.agentStore.create(input);
|
|
2257
|
+
context.channelContext.upsertProfile?.(createCustomAgentProfileDefinition(agent));
|
|
2258
|
+
return responseJson({ agent }, { status: 201 });
|
|
2259
|
+
}
|
|
2260
|
+
const patchAgentId = agentResourceId(url.pathname);
|
|
2261
|
+
if (patchAgentId && request.method === "PATCH") {
|
|
2262
|
+
requireSameOriginJsonRequest(request);
|
|
2263
|
+
const webSession = await requireSession(request, context);
|
|
2264
|
+
const existing = requireOwnedAgent(state.agentStore.get(patchAgentId), webSession);
|
|
2265
|
+
const body = await readJsonBody(request);
|
|
2266
|
+
const update = createAgentUpdate(body);
|
|
2267
|
+
const archived = normalizeAgentArchived(body.archived);
|
|
2268
|
+
if (update.displayName)
|
|
2269
|
+
requireAgentProfileNameAvailable(state, context, update.displayName, existing.id);
|
|
2270
|
+
const updated = Object.keys(update).length ? state.agentStore.update(patchAgentId, update) : existing;
|
|
2271
|
+
const afterUpdate = requireOwnedAgent(updated, webSession);
|
|
2272
|
+
const agent = archived === undefined ? afterUpdate : state.agentStore.setArchived(patchAgentId, archived);
|
|
2273
|
+
const owned = requireOwnedAgent(agent, webSession);
|
|
2274
|
+
if (existing.profileName !== owned.profileName)
|
|
2275
|
+
context.channelContext.removeProfile?.(existing.profileName);
|
|
2276
|
+
if (owned.archivedAt) {
|
|
2277
|
+
context.channelContext.removeProfile?.(owned.profileName);
|
|
2278
|
+
}
|
|
2279
|
+
else {
|
|
2280
|
+
context.channelContext.upsertProfile?.(createCustomAgentProfileDefinition(owned));
|
|
2281
|
+
}
|
|
2282
|
+
return responseJson({ agent: owned });
|
|
2283
|
+
}
|
|
2284
|
+
if (patchAgentId && request.method === "DELETE") {
|
|
2285
|
+
requireSameOriginJsonRequest(request);
|
|
2286
|
+
const webSession = await requireSession(request, context);
|
|
2287
|
+
const agent = requireOwnedAgent(state.agentStore.get(patchAgentId), webSession);
|
|
2288
|
+
if (!agent.archivedAt)
|
|
2289
|
+
throw new PiboWebHttpError("Archive the agent before permanently deleting it.", 400);
|
|
2290
|
+
const body = await readJsonBody(request);
|
|
2291
|
+
const confirmName = normalizeAgentDeleteConfirmation(body.confirmName);
|
|
2292
|
+
if (confirmName !== agent.profileName) {
|
|
2293
|
+
throw new PiboWebHttpError(`Type "${agent.profileName}" to permanently delete this agent and its sessions.`, 400);
|
|
2294
|
+
}
|
|
2295
|
+
const deletedSessionIds = deleteSessionsForAgentProfile(state, context, webSession, agent.profileName);
|
|
2296
|
+
state.agentStore.delete(agent.id);
|
|
2297
|
+
context.channelContext.removeProfile?.(agent.profileName);
|
|
2298
|
+
return responseJson({ deletedAgentId: agent.id, deletedSessionIds });
|
|
2299
|
+
}
|
|
2300
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/session` && request.method === "GET") {
|
|
2301
|
+
const webSession = await requireSession(request, context);
|
|
2302
|
+
const selectedSession = ensureDefaultChatSession(state, context, webSession, defaultProfile);
|
|
2303
|
+
state.readModel.upsertSession(selectedSession);
|
|
2304
|
+
return responseJson({
|
|
2305
|
+
identity: webSession.authSession.identity,
|
|
2306
|
+
session: selectedSession,
|
|
2307
|
+
room: state.roomStore.getRoom(selectedRoomIdForSession(state, context, selectedSession)),
|
|
2308
|
+
capabilities: {
|
|
2309
|
+
actions: context.channelContext.getGatewayActions(),
|
|
2310
|
+
},
|
|
2311
|
+
});
|
|
2312
|
+
}
|
|
2313
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/sessions` && request.method === "GET") {
|
|
2314
|
+
const webSession = await requireSession(request, context);
|
|
2315
|
+
const includeArchived = parseBooleanSearchParam(url, "includeArchived");
|
|
2316
|
+
const roomId = url.searchParams.get("roomId") || undefined;
|
|
2317
|
+
const selectedSession = ensureDefaultChatSession(state, context, webSession, defaultProfile, roomId);
|
|
2318
|
+
const selectedRoomId = selectedRoomIdForSession(state, context, selectedSession);
|
|
2319
|
+
const ownedSessions = listOwnedSessions(context, webSession);
|
|
2320
|
+
const roomSessions = visibleSessionsInRoom({
|
|
2321
|
+
state,
|
|
2322
|
+
context,
|
|
2323
|
+
webSession,
|
|
2324
|
+
sessions: ownedSessions,
|
|
2325
|
+
selectedSession,
|
|
2326
|
+
selectedRoomId,
|
|
2327
|
+
includeArchived,
|
|
2328
|
+
});
|
|
2329
|
+
indexOwnedSessions(state.readModel, roomSessions);
|
|
2330
|
+
return responseJson(await buildSessionNodes(roomSessions, state.readModel.listSessions()));
|
|
2331
|
+
}
|
|
2332
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/sessions` && request.method === "POST") {
|
|
2333
|
+
requireSameOriginJsonRequest(request);
|
|
2334
|
+
const webSession = await requireSession(request, context);
|
|
2335
|
+
const body = await readJsonBody(request);
|
|
2336
|
+
const profile = resolveCreateSessionProfile(context, defaultProfile, body.profile);
|
|
2337
|
+
const room = typeof body.roomId === "string"
|
|
2338
|
+
? requireRoom(state, body.roomId, webSession, "write")
|
|
2339
|
+
: state.roomStore.ensureDefaultRoom({
|
|
2340
|
+
ownerScope: webSession.ownerScope,
|
|
2341
|
+
principalId: principalIdFor(webSession),
|
|
2342
|
+
});
|
|
2343
|
+
const created = createPersonalChatSession(context, webSession, profile, room);
|
|
2344
|
+
state.readModel.upsertSession(created);
|
|
2345
|
+
return responseJson({ session: created }, { status: 201 });
|
|
2346
|
+
}
|
|
2347
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/rooms` && request.method === "GET") {
|
|
2348
|
+
const webSession = await requireSession(request, context);
|
|
2349
|
+
state.roomStore.ensureDefaultRoom({
|
|
2350
|
+
ownerScope: webSession.ownerScope,
|
|
2351
|
+
principalId: principalIdFor(webSession),
|
|
2352
|
+
});
|
|
2353
|
+
return responseJson({ rooms: state.roomStore.listRoomTree(webSession.ownerScope) });
|
|
2354
|
+
}
|
|
2355
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/rooms` && request.method === "POST") {
|
|
2356
|
+
requireSameOriginJsonRequest(request);
|
|
2357
|
+
const webSession = await requireSession(request, context);
|
|
2358
|
+
const body = await readJsonBody(request);
|
|
2359
|
+
const parentRoomId = normalizeParentRoomId(body.parentRoomId);
|
|
2360
|
+
if (parentRoomId)
|
|
2361
|
+
requireRoom(state, parentRoomId, webSession, "admin");
|
|
2362
|
+
const room = state.roomStore.createRoom({
|
|
2363
|
+
ownerScope: webSession.ownerScope,
|
|
2364
|
+
name: normalizeRoomName(body.name),
|
|
2365
|
+
topic: normalizeRoomTopic(body.topic),
|
|
2366
|
+
metadata: withPiboRoomWorkspace(undefined, normalizeRoomWorkspace(body.workspace)),
|
|
2367
|
+
type: normalizeRoomType(body.type),
|
|
2368
|
+
parentRoomId,
|
|
2369
|
+
});
|
|
2370
|
+
state.roomStore.ensureMember({ roomId: room.id, principalId: principalIdFor(webSession), role: "owner" });
|
|
2371
|
+
return responseJson({ room }, { status: 201 });
|
|
2372
|
+
}
|
|
2373
|
+
const roomResource = roomResourcePath(url.pathname);
|
|
2374
|
+
if (roomResource && roomResource.child === undefined && request.method === "GET") {
|
|
2375
|
+
const webSession = await requireSession(request, context);
|
|
2376
|
+
const room = requireRoom(state, roomResource.roomId, webSession, "read");
|
|
2377
|
+
const ownedSessions = sessionsInRoom(listOwnedSessions(context, webSession), room.id);
|
|
2378
|
+
indexOwnedSessions(state.readModel, ownedSessions);
|
|
2379
|
+
return responseJson({
|
|
2380
|
+
room,
|
|
2381
|
+
member: state.roomStore.getMember(room.id, principalIdFor(webSession)),
|
|
2382
|
+
sessions: await buildSessionNodes(ownedSessions, state.readModel.listSessions()),
|
|
2383
|
+
});
|
|
2384
|
+
}
|
|
2385
|
+
if (roomResource && roomResource.child === undefined && request.method === "PATCH") {
|
|
2386
|
+
requireSameOriginJsonRequest(request);
|
|
2387
|
+
const webSession = await requireSession(request, context);
|
|
2388
|
+
const existingRoom = requireRoom(state, roomResource.roomId, webSession, "admin");
|
|
2389
|
+
const body = await readJsonBody(request);
|
|
2390
|
+
const update = createRoomUpdate(existingRoom, body);
|
|
2391
|
+
if (update.parentRoomId)
|
|
2392
|
+
requireRoom(state, update.parentRoomId, webSession, "admin");
|
|
2393
|
+
const room = state.roomStore.updateRoom(roomResource.roomId, update);
|
|
2394
|
+
if (!room)
|
|
2395
|
+
throw new PiboWebHttpError("Room not found", 404);
|
|
2396
|
+
return responseJson({ room });
|
|
2397
|
+
}
|
|
2398
|
+
if (roomResource && roomResource.child === undefined && request.method === "DELETE") {
|
|
2399
|
+
requireSameOriginJsonRequest(request);
|
|
2400
|
+
const webSession = await requireSession(request, context);
|
|
2401
|
+
const room = requireRoom(state, roomResource.roomId, webSession, "admin");
|
|
2402
|
+
const body = await readJsonBody(request);
|
|
2403
|
+
const deleted = deleteRoomTree(state, context, webSession, room, normalizeRoomDeleteConfirmation(body.confirmName));
|
|
2404
|
+
return responseJson(deleted);
|
|
2405
|
+
}
|
|
2406
|
+
if (roomResource && roomResource.child === "events" && request.method === "GET") {
|
|
2407
|
+
const webSession = await requireSession(request, context);
|
|
2408
|
+
requireRoom(state, roomResource.roomId, webSession, "read");
|
|
2409
|
+
const cursor = parseSseCursor(url.searchParams.get("since"));
|
|
2410
|
+
return responseJson({
|
|
2411
|
+
events: state.eventLog.listEvents({
|
|
2412
|
+
roomId: roomResource.roomId,
|
|
2413
|
+
afterStreamId: cursor?.streamId,
|
|
2414
|
+
limit: 1000,
|
|
2415
|
+
}),
|
|
2416
|
+
});
|
|
2417
|
+
}
|
|
2418
|
+
if (roomResource && roomResource.child === "messages" && request.method === "POST") {
|
|
2419
|
+
requireSameOriginJsonRequest(request);
|
|
2420
|
+
const webSession = await requireSession(request, context);
|
|
2421
|
+
requireRoom(state, roomResource.roomId, webSession, "write");
|
|
2422
|
+
const body = await readJsonBody(request);
|
|
2423
|
+
return sendChatMessage({
|
|
2424
|
+
state,
|
|
2425
|
+
context,
|
|
2426
|
+
webSession,
|
|
2427
|
+
defaultProfile,
|
|
2428
|
+
body,
|
|
2429
|
+
forcedRoomId: roomResource.roomId,
|
|
2430
|
+
});
|
|
2431
|
+
}
|
|
2432
|
+
const patchSessionId = sessionResourceId(url.pathname);
|
|
2433
|
+
if (patchSessionId && request.method === "PATCH") {
|
|
2434
|
+
requireSameOriginJsonRequest(request);
|
|
2435
|
+
const webSession = await requireSession(request, context);
|
|
2436
|
+
const selectedSession = resolveRequestedSession(state, context, webSession, defaultProfile, patchSessionId);
|
|
2437
|
+
const body = await readJsonBody(request);
|
|
2438
|
+
const updateSession = context.channelContext.updateSession;
|
|
2439
|
+
if (!updateSession) {
|
|
2440
|
+
throw new PiboWebHttpError("Session updates are not available", 501);
|
|
2441
|
+
}
|
|
2442
|
+
if (body.profile !== undefined) {
|
|
2443
|
+
const ownedSessions = listOwnedSessions(context, webSession);
|
|
2444
|
+
const indexedSession = state.readModel.listSessions().find((item) => item.piboSessionId === selectedSession.id);
|
|
2445
|
+
const trace = await buildTraceView({
|
|
2446
|
+
session: selectedSession,
|
|
2447
|
+
sessions: ownedSessions,
|
|
2448
|
+
events: state.readModel.listAllEvents(selectedSession.id),
|
|
2449
|
+
status: indexedSession?.status,
|
|
2450
|
+
includeRawEvents: false,
|
|
2451
|
+
});
|
|
2452
|
+
if (trace.nodes.length > 0) {
|
|
2453
|
+
throw new PiboWebHttpError("Session profile can only be changed before the first message.", 400);
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
const updated = updateSession(selectedSession.id, createSessionUpdate(context, selectedSession, body));
|
|
2457
|
+
if (!updated)
|
|
2458
|
+
throw new PiboWebHttpError("Session not found", 404);
|
|
2459
|
+
state.readModel.upsertSession(updated);
|
|
2460
|
+
return responseJson({ session: updated });
|
|
2461
|
+
}
|
|
2462
|
+
if (patchSessionId && request.method === "DELETE") {
|
|
2463
|
+
requireSameOriginJsonRequest(request);
|
|
2464
|
+
const webSession = await requireSession(request, context);
|
|
2465
|
+
const selectedSession = resolveRequestedSession(state, context, webSession, defaultProfile, patchSessionId);
|
|
2466
|
+
if (!isChatWebSessionArchived(selectedSession)) {
|
|
2467
|
+
throw new PiboWebHttpError("Archive the session before permanently deleting it.", 400);
|
|
2468
|
+
}
|
|
2469
|
+
const body = await readJsonBody(request);
|
|
2470
|
+
const confirmText = normalizeSessionDeleteConfirmation(body.confirmText);
|
|
2471
|
+
if (confirmText !== "Delete this session") {
|
|
2472
|
+
throw new PiboWebHttpError('Type "Delete this session" to permanently delete this session.', 400);
|
|
2473
|
+
}
|
|
2474
|
+
const deletedSessionIds = deleteSessionSubtree(state, context, webSession, selectedSession);
|
|
2475
|
+
return responseJson({ deletedSessionIds });
|
|
2476
|
+
}
|
|
2477
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/trace` && request.method === "GET") {
|
|
2478
|
+
const webSession = await requireSession(request, context);
|
|
2479
|
+
const includeRawEvents = parseBooleanSearchParam(url, "includeRawEvents");
|
|
2480
|
+
const rawEventsLimit = parsePositiveIntSearchParam(url, "rawEventsLimit", 80, 1000);
|
|
2481
|
+
const selectedSession = resolveRequestedSession(state, context, webSession, defaultProfile, url.searchParams.get("piboSessionId") || undefined);
|
|
2482
|
+
state.readModel.upsertSession(selectedSession);
|
|
2483
|
+
const ownedSessions = listOwnedSessions(context, webSession);
|
|
2484
|
+
const indexedSession = state.readModel
|
|
2485
|
+
.listSessions()
|
|
2486
|
+
.find((item) => item.piboSessionId === selectedSession.id);
|
|
2487
|
+
const metadata = await loadPiSessionMetadata(selectedSession, selectedSession.workspace ?? process.cwd());
|
|
2488
|
+
const lastEventSequence = state.readModel.getLatestEventSequence(selectedSession.id);
|
|
2489
|
+
const latestStreamId = state.eventLog.getLatestStreamId({ piboSessionId: selectedSession.id });
|
|
2490
|
+
const version = createTraceViewVersion({
|
|
2491
|
+
session: selectedSession,
|
|
2492
|
+
sessions: ownedSessions,
|
|
2493
|
+
events: lastEventSequence > 0
|
|
2494
|
+
? [{ id: `seq:${lastEventSequence}`, eventSequence: lastEventSequence, createdAt: indexedSession?.lastActivityAt ?? "" }]
|
|
2495
|
+
: [],
|
|
2496
|
+
status: indexedSession?.status,
|
|
2497
|
+
metadata,
|
|
2498
|
+
latestStreamId,
|
|
2499
|
+
});
|
|
2500
|
+
const headers = { etag: etagForVersion(version), "x-pibo-trace-version": version };
|
|
2501
|
+
if (requestMatchesVersion(request, version)) {
|
|
2502
|
+
return new Response(null, { status: 304, headers });
|
|
2503
|
+
}
|
|
2504
|
+
const cacheKey = traceCacheKey(selectedSession.id, version, includeRawEvents, rawEventsLimit);
|
|
2505
|
+
const cached = state.traceCache.get(cacheKey);
|
|
2506
|
+
if (cached)
|
|
2507
|
+
return responseJson(cached, { headers });
|
|
2508
|
+
const trace = await buildTraceView({
|
|
2509
|
+
session: selectedSession,
|
|
2510
|
+
sessions: ownedSessions,
|
|
2511
|
+
events: state.readModel.listAllEvents(selectedSession.id),
|
|
2512
|
+
status: indexedSession?.status,
|
|
2513
|
+
includeRawEvents,
|
|
2514
|
+
rawEventsLimit,
|
|
2515
|
+
latestStreamId,
|
|
2516
|
+
});
|
|
2517
|
+
setTraceCache(state.traceCache, cacheKey, trace);
|
|
2518
|
+
return responseJson(trace, { headers });
|
|
2519
|
+
}
|
|
2520
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/message` && request.method === "POST") {
|
|
2521
|
+
requireSameOriginJsonRequest(request);
|
|
2522
|
+
const webSession = await requireSession(request, context);
|
|
2523
|
+
const body = await readJsonBody(request);
|
|
2524
|
+
return sendChatMessage({ state, context, webSession, defaultProfile, body });
|
|
2525
|
+
}
|
|
2526
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/action` && request.method === "POST") {
|
|
2527
|
+
requireSameOriginJsonRequest(request);
|
|
2528
|
+
const webSession = await requireSession(request, context);
|
|
2529
|
+
const body = await readJsonBody(request);
|
|
2530
|
+
if (typeof body.action !== "string" || body.action.length === 0) {
|
|
2531
|
+
return responseJson({ error: "Action is required" }, { status: 400 });
|
|
2532
|
+
}
|
|
2533
|
+
if (body.params !== undefined && !isJsonValue(body.params)) {
|
|
2534
|
+
return responseJson({ error: "Params must be JSON serializable" }, { status: 400 });
|
|
2535
|
+
}
|
|
2536
|
+
const selectedSession = resolveRequestedSession(state, context, webSession, defaultProfile, typeof body.piboSessionId === "string" ? body.piboSessionId : undefined);
|
|
2537
|
+
const room = ensureSessionRoom(state, context, selectedSession, webSession);
|
|
2538
|
+
if (isPiboRoomArchived(room)) {
|
|
2539
|
+
throw new PiboWebHttpError("Archived rooms are read-only", 403);
|
|
2540
|
+
}
|
|
2541
|
+
state.readModel.upsertSession(selectedSession);
|
|
2542
|
+
const output = await context.channelContext.emit({
|
|
2543
|
+
type: "execution",
|
|
2544
|
+
piboSessionId: selectedSession.id,
|
|
2545
|
+
id: randomUUID(),
|
|
2546
|
+
action: body.action,
|
|
2547
|
+
...(body.params === undefined ? {} : { params: body.params }),
|
|
2548
|
+
});
|
|
2549
|
+
return responseJson(output);
|
|
2550
|
+
}
|
|
2551
|
+
if (url.pathname === `${CHAT_WEB_API_PREFIX}/events` && request.method === "GET") {
|
|
2552
|
+
const webSession = await requireSession(request, context);
|
|
2553
|
+
const requestedRoomId = url.searchParams.get("roomId") || undefined;
|
|
2554
|
+
const selectedSession = resolveRequestedSession(state, context, webSession, defaultProfile, url.searchParams.get("piboSessionId") || undefined, requestedRoomId);
|
|
2555
|
+
const roomId = requestedRoomId ?? selectedRoomIdForSession(state, context, selectedSession);
|
|
2556
|
+
requireRoom(state, roomId, webSession, "read");
|
|
2557
|
+
const cursor = parseSseCursor(url.searchParams.get("since")) ?? parseSseCursor(request.headers.get("last-event-id"));
|
|
2558
|
+
return createEventStream({
|
|
2559
|
+
roomId: url.searchParams.has("roomId") ? roomId : undefined,
|
|
2560
|
+
piboSessionId: url.searchParams.has("roomId") ? undefined : selectedSession.id,
|
|
2561
|
+
context,
|
|
2562
|
+
state,
|
|
2563
|
+
cursor,
|
|
2564
|
+
});
|
|
2565
|
+
}
|
|
2566
|
+
return undefined;
|
|
2567
|
+
},
|
|
2568
|
+
};
|
|
2569
|
+
}
|