@humain/humain-code 0.8.2 → 0.8.4
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/CHANGELOG.md +152 -0
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/anthropic-messages-42CGJCSR.js +82 -0
- package/dist/bundle/chunks/ask-VH7GNX75.js +97 -0
- package/dist/bundle/chunks/azure-openai-responses-DOKKMBUN.js +15 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +200 -179
- package/dist/bundle/chunks/bowser-UX7KDMIY.js +92 -0
- package/dist/bundle/chunks/{chunk-46C6D7UC.js → chunk-2CYGUEQO.js} +1 -1
- package/dist/bundle/chunks/chunk-3RXT35Y3.js +3 -0
- package/dist/bundle/chunks/chunk-4BNDLR6C.js +177 -0
- package/dist/bundle/chunks/{chunk-MPRAQ6ZI.js → chunk-4LGBXPUD.js} +1 -1
- package/dist/bundle/chunks/chunk-4SL6URR3.js +90 -0
- package/dist/bundle/chunks/{chunk-PJXBU6CR.js → chunk-52642TYH.js} +394 -204
- package/dist/bundle/chunks/{chunk-LSRXA7OS.js → chunk-5C5K4EVJ.js} +3 -3
- package/dist/bundle/chunks/{chunk-2JNJJ6SZ.js → chunk-5KUCY54O.js} +3 -3
- package/dist/bundle/chunks/{chunk-4TDNOR36.js → chunk-625QJSFJ.js} +1 -1
- package/dist/bundle/chunks/chunk-73YX5XGR.js +2461 -0
- package/dist/bundle/chunks/chunk-7DIRHF4H.js +17 -0
- package/dist/bundle/chunks/{chunk-QJB5YI3I.js → chunk-7PAXKU7M.js} +1 -1
- package/dist/bundle/chunks/{chunk-R2KD2HFT.js → chunk-7YB3HRRN.js} +83 -196
- package/dist/bundle/chunks/{chunk-DCXHRP6C.js → chunk-A2UZYK23.js} +13 -13
- package/dist/bundle/chunks/chunk-A5ZMBTTM.js +12 -0
- package/dist/bundle/chunks/{chunk-JKX5EGOT.js → chunk-AER66CNP.js} +13 -13
- package/dist/bundle/chunks/chunk-ARTF7ZMQ.js +5 -0
- package/dist/bundle/chunks/chunk-B3FT6L6S.js +131 -0
- package/dist/bundle/chunks/chunk-BIC5BSNX.js +13 -0
- package/dist/bundle/chunks/{chunk-JSHKS7VH.js → chunk-BNZZJ4LO.js} +1 -1
- package/dist/bundle/chunks/{chunk-4MKATHT2.js → chunk-CG43CMFH.js} +1 -1
- package/dist/bundle/chunks/{chunk-EFY2QPVP.js → chunk-CIAXW64K.js} +16 -16
- package/dist/bundle/chunks/{chunk-VFLVWPLZ.js → chunk-CKFLQGJN.js} +20 -16
- package/dist/bundle/chunks/chunk-D4UCXXDP.js +115 -0
- package/dist/bundle/chunks/{chunk-HQMUDHC3.js → chunk-D6ZWWDW5.js} +6 -5
- package/dist/bundle/chunks/{chunk-U4EAJPMO.js → chunk-EVDQRT3I.js} +252 -371
- package/dist/bundle/chunks/{chunk-FJIISX5W.js → chunk-F74XLJPC.js} +195 -192
- package/dist/bundle/chunks/chunk-FDRBTGFJ.js +4 -0
- package/dist/bundle/chunks/{chunk-E4VUW4RI.js → chunk-FLWO3H5J.js} +12 -12
- package/dist/bundle/chunks/{chunk-KLSRGGOH.js → chunk-G2PFPQX7.js} +2 -2
- package/dist/bundle/chunks/chunk-GMPJWLZS.js +57 -0
- package/dist/bundle/chunks/{chunk-M5TVWJ5T.js → chunk-H35P7ROY.js} +462 -441
- package/dist/bundle/chunks/chunk-HCHCYBNK.js +2 -0
- package/dist/bundle/chunks/{chunk-7WE77IE3.js → chunk-HRNYDRL7.js} +1 -1
- package/dist/bundle/chunks/chunk-HWFAAGYK.js +23 -0
- package/dist/bundle/chunks/{chunk-G2QMON4O.js → chunk-HWXQCJDP.js} +408 -392
- package/dist/bundle/chunks/{chunk-PVNXN2TC.js → chunk-II5C7G67.js} +1 -1
- package/dist/bundle/chunks/{chunk-F2H47FRF.js → chunk-IMRZP5SC.js} +182 -137
- package/dist/bundle/chunks/{chunk-H2B3WLIM.js → chunk-J5YFXMTM.js} +4 -4
- package/dist/bundle/chunks/chunk-J64VNQ6D.js +13 -0
- package/dist/bundle/chunks/{chunk-65FLSKDA.js → chunk-K5EFEIFP.js} +5 -4
- package/dist/bundle/chunks/{chunk-KI7CHPWC.js → chunk-KJ3QRSSY.js} +46 -43
- package/dist/bundle/chunks/{cli-6DJO467D.js → chunk-KSEO2LRK.js} +12 -10
- package/dist/bundle/chunks/{chunk-HHWVVNGG.js → chunk-MA2WCMSN.js} +2 -2
- package/dist/bundle/chunks/{chunk-L4J7SMJB.js → chunk-MAEKQSFU.js} +1 -1
- package/dist/bundle/chunks/chunk-MHQNLTZR.js +8 -0
- package/dist/bundle/chunks/chunk-MLOUZAVZ.js +122 -0
- package/dist/bundle/chunks/chunk-MQYR4Q6X.js +5 -0
- package/dist/bundle/chunks/chunk-MXF3KYLZ.js +4 -0
- package/dist/bundle/chunks/{chunk-GY663MNP.js → chunk-MZRTVX7F.js} +1 -1
- package/dist/bundle/chunks/chunk-MZYHSWHX.js +59 -0
- package/dist/bundle/chunks/{chunk-6HTHDVJC.js → chunk-NPVRWPGX.js} +1 -1
- package/dist/bundle/chunks/{chunk-BRSLXHED.js → chunk-O44A4E4K.js} +1 -1
- package/dist/bundle/chunks/{chunk-T2ZGMEMV.js → chunk-OADQOW67.js} +175 -260
- package/dist/bundle/chunks/chunk-OTVHRZ67.js +17 -0
- package/dist/bundle/chunks/{chunk-J4GII2EE.js → chunk-P7SLTLSZ.js} +51 -46
- package/dist/bundle/chunks/{chunk-7OZNMWAJ.js → chunk-PPGSQZZF.js} +1 -1
- package/dist/bundle/chunks/chunk-PYX6ZCC7.js +29 -0
- package/dist/bundle/chunks/chunk-PZ7NYBHJ.js +8 -0
- package/dist/bundle/chunks/{chunk-VCMXBP5S.js → chunk-QESIDBMW.js} +1 -7
- package/dist/bundle/chunks/chunk-QUWVILLB.js +3 -0
- package/dist/bundle/chunks/chunk-QZWUXGY7.js +99 -0
- package/dist/bundle/chunks/{chunk-MIAXMK5F.js → chunk-QZXLTW7V.js} +8 -7
- package/dist/bundle/chunks/chunk-RP6MWUAP.js +4 -0
- package/dist/bundle/chunks/chunk-S2US54IU.js +37 -0
- package/dist/bundle/chunks/{chunk-H7UPU2SH.js → chunk-SOE25WIS.js} +1218 -1239
- package/dist/bundle/chunks/{chunk-JSZBTGI6.js → chunk-SZZ5PNP6.js} +2 -2
- package/dist/bundle/chunks/chunk-T5WECB2D.js +7 -0
- package/dist/bundle/chunks/{chunk-2NVGOSBN.js → chunk-T7F2TEIS.js} +37 -13
- package/dist/bundle/chunks/{chunk-ZSWU5KKA.js → chunk-UOSJTMCL.js} +7 -3
- package/dist/bundle/chunks/{chunk-6P6MMQUH.js → chunk-UTRUALFN.js} +3 -3
- package/dist/bundle/chunks/{chunk-PWFM6AQQ.js → chunk-V2HTCZRF.js} +70 -67
- package/dist/bundle/chunks/{chunk-JX6YIPNK.js → chunk-WCKS2DPT.js} +1 -1
- package/dist/bundle/chunks/chunk-XGOJCV6Z.js +2 -0
- package/dist/bundle/chunks/chunk-XGSJX23G.js +1151 -0
- package/dist/bundle/chunks/{chunk-7WETECIB.js → chunk-Z7BWHPJ2.js} +1 -1
- package/dist/bundle/chunks/chunk-ZFFDBTG3.js +17 -0
- package/dist/bundle/chunks/cli-NJLV3XDZ.js +3 -0
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-JEZVYITT.js → cloudflare-workers-ai-system-one-ZAZW4M4B.js} +1 -1
- package/dist/bundle/chunks/{compat-ELBUCH6U.js → compat-7UJJAO4E.js} +12 -12
- package/dist/bundle/chunks/{curator-server-QB4GITGS.js → curator-server-MW645JI3.js} +2 -2
- package/dist/bundle/chunks/{dist-NERIS6SW.js → dist-7PCCEUQF.js} +2 -2
- package/dist/bundle/chunks/{dist-QSYDYE3Y.js → dist-I53JI67E.js} +9 -9
- package/dist/bundle/chunks/{dist-35STTNYA.js → dist-NI2PTSLH.js} +1 -1
- package/dist/bundle/chunks/{dist-CBODG4CA.js → dist-VXQT3DQY.js} +6 -6
- package/dist/bundle/chunks/{dist-cjs-EROMDUKS.js → dist-cjs-4JQA6W3S.js} +31 -31
- package/dist/bundle/chunks/doctor-KJVAYG3F.js +83 -0
- package/dist/bundle/chunks/{easter-egg-3d-VZC5WOYV.js → easter-egg-3d-Z24JLXD4.js} +1 -1
- package/dist/bundle/chunks/entry-3EL6GOWK.js +2 -0
- package/dist/bundle/chunks/{entry-SRYLSS5P.js → entry-4IMREZBD.js} +80 -79
- package/dist/bundle/chunks/{execute-6MEJJF2T.js → execute-C4BZQRPQ.js} +23 -22
- package/dist/bundle/chunks/{extract-L373D6O7.js → extract-XVQCIS7D.js} +5 -5
- package/dist/bundle/chunks/{flow-implementer-3P3BHQ7E.js → flow-implementer-GE2ARQKR.js} +5 -5
- package/dist/bundle/chunks/github-copilot.js +57 -56
- package/dist/bundle/chunks/google-generative-ai-P2P45MYP.js +22 -0
- package/dist/bundle/chunks/google-vertex-SHY4IS5F.js +26 -0
- package/dist/bundle/chunks/{host-WOLZCWQQ.js → host-YESS2VAB.js} +1 -1
- package/dist/bundle/chunks/{index.bundle-HONF3PUD.js → index.bundle-TZT64KLH.js} +102 -89
- package/dist/bundle/chunks/{inprocess-3PDJKE5F.js → inprocess-MGMVI6HN.js} +6 -6
- package/dist/bundle/chunks/interactive-mode-HHWOE4FD.js +5 -0
- package/dist/bundle/chunks/{llama-cpp-classify-KYZT532X.js → llama-cpp-classify-RSRH4KV2.js} +5 -5
- package/dist/bundle/chunks/mistral-conversations-YTMJKHHI.js +42 -0
- package/dist/bundle/chunks/{node-N7TPBUJB.js → node-FF6QQQLH.js} +1 -1
- package/dist/bundle/chunks/openai-codex-responses-NUCJOJSZ.js +97 -0
- package/dist/bundle/chunks/openai-completions-E5NRJUHA.js +91 -0
- package/dist/bundle/chunks/{openai-decisions-JMSDGR7K.js → openai-decisions-342J5ZYG.js} +1 -1
- package/dist/bundle/chunks/openai-responses-BN5Z4HFI.js +26 -0
- package/dist/bundle/chunks/openrouter-images-7RNG3JVF.js +12 -0
- package/dist/bundle/chunks/{pdfjs-FE3L72A6.js → pdfjs-LSTLRXQW.js} +1415 -1416
- package/dist/bundle/chunks/pi-messages-2L7FV5OK.js +22 -0
- package/dist/bundle/chunks/questionnaire-session-XEVAK7JS.js +123 -0
- package/dist/bundle/chunks/runtime-2FSZRUG5.js +2 -0
- package/dist/bundle/chunks/session-picker-666KJIVM.js +4 -0
- package/dist/bundle/chunks/startup-ui-INEVSNGK.js +3 -0
- package/dist/bundle/chunks/{trace-command-VM7FBWPE.js → trace-command-BCVMZ5ZD.js} +4 -4
- package/dist/bundle/chunks/typesafe-system-one-UJUNSZG4.js +3 -0
- package/dist/bundle/chunks/{undici-WVNE45GY.js → undici-7IGAYA4S.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-UXSSFNV5.js +29 -0
- package/dist/bundle/cli-runtime.js +5 -5
- package/dist/bundle/flow/package.json +3 -3
- package/dist/bundle/index.js +13 -13
- package/dist/bundle/orchestrate/package.json +1 -1
- package/dist/bundle/rpc-entry.js +5 -4
- package/dist/cli/agent-dir-arg.d.ts +12 -0
- package/dist/cli/agent-dir-arg.d.ts.map +1 -0
- package/dist/cli/agent-dir-arg.js +15 -0
- package/dist/cli/agent-dir-arg.js.map +1 -0
- package/dist/cli/args.d.ts +9 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +19 -5
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/auth-check.d.ts +1 -1
- package/dist/cli/auth-check.d.ts.map +1 -1
- package/dist/cli/auth-check.js +4 -2
- package/dist/cli/auth-check.js.map +1 -1
- package/dist/cli/doctor-config.d.ts +14 -0
- package/dist/cli/doctor-config.d.ts.map +1 -0
- package/dist/cli/doctor-config.js +92 -0
- package/dist/cli/doctor-config.js.map +1 -0
- package/dist/cli/doctor-system.d.ts +12 -0
- package/dist/cli/doctor-system.d.ts.map +1 -0
- package/dist/cli/doctor-system.js +109 -0
- package/dist/cli/doctor-system.js.map +1 -0
- package/dist/cli/doctor.d.ts +11 -0
- package/dist/cli/doctor.d.ts.map +1 -0
- package/dist/cli/doctor.js +323 -0
- package/dist/cli/doctor.js.map +1 -0
- package/dist/cli/doctor.lazy.d.ts +3 -0
- package/dist/cli/doctor.lazy.d.ts.map +1 -0
- package/dist/cli/doctor.lazy.js +3 -0
- package/dist/cli/doctor.lazy.js.map +1 -0
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +0 -4
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli/project-trust.d.ts.map +1 -1
- package/dist/cli/project-trust.js +6 -6
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/cli/startup-ui.d.ts +3 -2
- package/dist/cli/startup-ui.d.ts.map +1 -1
- package/dist/cli/startup-ui.js +23 -10
- package/dist/cli/startup-ui.js.map +1 -1
- package/dist/config.d.ts +5 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +13 -3
- package/dist/config.js.map +1 -1
- package/dist/coordination/adapter/delivery.d.ts +27 -0
- package/dist/coordination/adapter/delivery.d.ts.map +1 -1
- package/dist/coordination/adapter/delivery.js +164 -4
- package/dist/coordination/adapter/delivery.js.map +1 -1
- package/dist/coordination/adapter/index.d.ts.map +1 -1
- package/dist/coordination/adapter/index.js +31 -5
- package/dist/coordination/adapter/index.js.map +1 -1
- package/dist/coordination/adapter/presence.d.ts +5 -0
- package/dist/coordination/adapter/presence.d.ts.map +1 -1
- package/dist/coordination/adapter/presence.js +25 -3
- package/dist/coordination/adapter/presence.js.map +1 -1
- package/dist/coordination/adapter/question-routing.d.ts +7 -0
- package/dist/coordination/adapter/question-routing.d.ts.map +1 -0
- package/dist/coordination/adapter/question-routing.js +40 -0
- package/dist/coordination/adapter/question-routing.js.map +1 -0
- package/dist/coordination/adapter/receipts.d.ts +7 -0
- package/dist/coordination/adapter/receipts.d.ts.map +1 -1
- package/dist/coordination/adapter/receipts.js +25 -2
- package/dist/coordination/adapter/receipts.js.map +1 -1
- package/dist/coordination/adapter/tool.d.ts +19 -3
- package/dist/coordination/adapter/tool.d.ts.map +1 -1
- package/dist/coordination/adapter/tool.js +93 -19
- package/dist/coordination/adapter/tool.js.map +1 -1
- package/dist/coordination/broker/broker.d.ts +3 -3
- package/dist/coordination/broker/broker.d.ts.map +1 -1
- package/dist/coordination/broker/broker.js +15 -7
- package/dist/coordination/broker/broker.js.map +1 -1
- package/dist/coordination/client/client.d.ts +2 -2
- package/dist/coordination/client/client.d.ts.map +1 -1
- package/dist/coordination/client/client.js +4 -0
- package/dist/coordination/client/client.js.map +1 -1
- package/dist/coordination/transport/protocol.d.ts.map +1 -1
- package/dist/coordination/transport/protocol.js +23 -0
- package/dist/coordination/transport/protocol.js.map +1 -1
- package/dist/coordination/transport/types.d.ts +11 -1
- package/dist/coordination/transport/types.d.ts.map +1 -1
- package/dist/coordination/transport/types.js.map +1 -1
- package/dist/core/acceptance-command.d.ts +6 -3
- package/dist/core/acceptance-command.d.ts.map +1 -1
- package/dist/core/acceptance-command.js +43 -12
- package/dist/core/acceptance-command.js.map +1 -1
- package/dist/core/acceptance-ledger.d.ts +2 -0
- package/dist/core/acceptance-ledger.d.ts.map +1 -1
- package/dist/core/acceptance-ledger.js +14 -3
- package/dist/core/acceptance-ledger.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +11 -4
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +13 -4
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +6 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +19 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +131 -36
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +7 -1
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts +3 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +18 -8
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +2 -2
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +9 -15
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +3 -0
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/export-html/index.d.ts.map +1 -1
- package/dist/core/export-html/index.js +12 -10
- package/dist/core/export-html/index.js.map +1 -1
- package/dist/core/export-html/template.js +23 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +13 -2
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +2 -4
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +5 -2
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +6 -3
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/keybindings.d.ts +20 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +4 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +29 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +63 -17
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/messages.d.ts +4 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +10 -2
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-config.d.ts +36 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +20 -10
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/nested-tool-calls.d.ts +6 -5
- package/dist/core/nested-tool-calls.d.ts.map +1 -1
- package/dist/core/nested-tool-calls.js +1 -3
- package/dist/core/nested-tool-calls.js.map +1 -1
- package/dist/core/oauth-account-pool.d.ts +14 -0
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +166 -14
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/core/os-secret-store.js +1 -1
- package/dist/core/os-secret-store.js.map +1 -1
- package/dist/core/package-manager.d.ts +3 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +25 -4
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +4 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -1
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/provider-composer.d.ts +1 -0
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +1 -0
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/resolve-config-value.d.ts +4 -0
- package/dist/core/resolve-config-value.d.ts.map +1 -1
- package/dist/core/resolve-config-value.js +14 -3
- package/dist/core/resolve-config-value.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +40 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/run-outcome.d.ts +1 -1
- package/dist/core/run-outcome.d.ts.map +1 -1
- package/dist/core/run-outcome.js +2 -2
- package/dist/core/run-outcome.js.map +1 -1
- package/dist/core/run-preflight.d.ts.map +1 -1
- package/dist/core/run-preflight.js +15 -8
- package/dist/core/run-preflight.js.map +1 -1
- package/dist/core/runtime-credentials.d.ts.map +1 -1
- package/dist/core/runtime-credentials.js +11 -7
- package/dist/core/runtime-credentials.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +8 -4
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +22 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +227 -37
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +10 -1
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +7 -1
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +14 -4
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +48 -15
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +20 -2
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +27 -4
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +2 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tools/bash-jobs.js +2 -2
- package/dist/core/tools/bash-jobs.js.map +1 -1
- package/dist/core/tools/bash.d.ts +3 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +78 -46
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +7 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +139 -75
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +4 -1
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +21 -6
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +90 -76
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +7 -2
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +14 -1
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts.map +1 -1
- package/dist/core/tools/renderers/bash.js +9 -3
- package/dist/core/tools/renderers/bash.js.map +1 -1
- package/dist/core/tools/truncate.d.ts +1 -1
- package/dist/core/tools/truncate.d.ts.map +1 -1
- package/dist/core/tools/truncate.js +16 -7
- package/dist/core/tools/truncate.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +2 -0
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts +2 -0
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +5 -4
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +3 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +64 -20
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +8 -3
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +5 -0
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/client.d.ts.map +1 -1
- package/dist/extensions/llama/client.js +3 -13
- package/dist/extensions/llama/client.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +2 -1
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts +7 -0
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +35 -8
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +33 -0
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +11 -2
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +8 -0
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +16 -0
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/resources.d.ts +1 -1
- package/dist/extensions/mcp/resources.d.ts.map +1 -1
- package/dist/extensions/mcp/resources.js +4 -3
- package/dist/extensions/mcp/resources.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +15 -14
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +1 -24
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +10 -163
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/humain/ask-user-question/index.d.ts +4 -0
- package/dist/humain/ask-user-question/index.d.ts.map +1 -0
- package/dist/humain/ask-user-question/index.js +18 -0
- package/dist/humain/ask-user-question/index.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/answer-channel.d.ts +38 -0
- package/dist/humain/ask-user-question/vendor/ask/answer-channel.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/answer-channel.js +97 -0
- package/dist/humain/ask-user-question/vendor/ask/answer-channel.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/ask-user-question.d.ts +41 -0
- package/dist/humain/ask-user-question/vendor/ask/ask-user-question.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/ask-user-question.js +441 -0
- package/dist/humain/ask-user-question/vendor/ask/ask-user-question.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/config.d.ts +39 -0
- package/dist/humain/ask-user-question/vendor/ask/config.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/config.js +95 -0
- package/dist/humain/ask-user-question/vendor/ask/config.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/events.d.ts +132 -0
- package/dist/humain/ask-user-question/vendor/ask/events.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/events.js +50 -0
- package/dist/humain/ask-user-question/vendor/ask/events.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/index.d.ts +5 -0
- package/dist/humain/ask-user-question/vendor/ask/index.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/index.js +15 -0
- package/dist/humain/ask-user-question/vendor/ask/index.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/presentation.d.ts +81 -0
- package/dist/humain/ask-user-question/vendor/ask/presentation.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/presentation.js +105 -0
- package/dist/humain/ask-user-question/vendor/ask/presentation.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/reconcile.d.ts +28 -0
- package/dist/humain/ask-user-question/vendor/ask/reconcile.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/reconcile.js +45 -0
- package/dist/humain/ask-user-question/vendor/ask/reconcile.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.d.ts +41 -0
- package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.js +166 -0
- package/dist/humain/ask-user-question/vendor/ask/rpc-fallback.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.d.ts +46 -0
- package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.js +247 -0
- package/dist/humain/ask-user-question/vendor/ask/state/build-questionnaire.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/external-editor.d.ts +11 -0
- package/dist/humain/ask-user-question/vendor/ask/state/external-editor.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/external-editor.js +56 -0
- package/dist/humain/ask-user-question/vendor/ask/state/external-editor.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.d.ts +6 -0
- package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.js +10 -0
- package/dist/humain/ask-user-question/vendor/ask/state/i18n-bridge.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/key-router.d.ts +57 -0
- package/dist/humain/ask-user-question/vendor/ask/state/key-router.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/key-router.js +357 -0
- package/dist/humain/ask-user-question/vendor/ask/state/key-router.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.d.ts +112 -0
- package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.js +240 -0
- package/dist/humain/ask-user-question/vendor/ask/state/questionnaire-session.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/row-intent.d.ts +87 -0
- package/dist/humain/ask-user-question/vendor/ask/state/row-intent.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/row-intent.js +79 -0
- package/dist/humain/ask-user-question/vendor/ask/state/row-intent.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.d.ts +22 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.js +2 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/contract.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.d.ts +27 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.js +48 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/derivations.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.d.ts +13 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.js +15 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/focus.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.d.ts +14 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.js +96 -0
- package/dist/humain/ask-user-question/vendor/ask/state/selectors/projections.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.d.ts +58 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.js +310 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state-reducer.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state.d.ts +68 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state.js +2 -0
- package/dist/humain/ask-user-question/vendor/ask/state/state.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.d.ts +24 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.js +114 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/external-answer.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.d.ts +18 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.js +29 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/format-answer.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.d.ts +41 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.js +99 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/normalize-params.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.d.ts +37 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.js +70 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/response-envelope.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/types.d.ts +129 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/types.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/types.js +76 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/types.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.d.ts +21 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.js +49 -0
- package/dist/humain/ask-user-question/vendor/ask/tool/validate-questionnaire.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/component-binding.d.ts +23 -0
- package/dist/humain/ask-user-question/vendor/ask/view/component-binding.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/component-binding.js +16 -0
- package/dist/humain/ask-user-question/vendor/ask/view/component-binding.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.d.ts +21 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.js +49 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/inline-input.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.d.ts +43 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.js +130 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/multi-select-view.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.d.ts +45 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.js +39 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/option-list-view.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.d.ts +36 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.js +72 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/markdown-content-cache.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.d.ts +61 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.js +108 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-block-renderer.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.d.ts +39 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.js +76 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-box-renderer.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.d.ts +123 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.js +180 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-layout-decider.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.d.ts +108 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.js +235 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/preview/preview-pane.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.d.ts +37 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.js +47 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/submit-picker.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.d.ts +31 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.js +35 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/tab-bar.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.d.ts +124 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.js +205 -0
- package/dist/humain/ask-user-question/vendor/ask/view/components/wrapping-select.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.d.ts +83 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.js +186 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-builder.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.d.ts +47 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.js +48 -0
- package/dist/humain/ask-user-question/vendor/ask/view/dialog-copy.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.d.ts +58 -0
- package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.js +84 -0
- package/dist/humain/ask-user-question/vendor/ask/view/props-adapter.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.d.ts +20 -0
- package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.js +55 -0
- package/dist/humain/ask-user-question/vendor/ask/view/scroll-window.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.d.ts +23 -0
- package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.js +2 -0
- package/dist/humain/ask-user-question/vendor/ask/view/stateful-view.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-components.d.ts +15 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-components.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-components.js +2 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-components.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.d.ts +98 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.js +248 -0
- package/dist/humain/ask-user-question/vendor/ask/view/tab-content-strategy.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/transcript.d.ts +23 -0
- package/dist/humain/ask-user-question/vendor/ask/view/transcript.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/ask/view/transcript.js +131 -0
- package/dist/humain/ask-user-question/vendor/ask/view/transcript.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/config/config.d.ts +132 -0
- package/dist/humain/ask-user-question/vendor/config/config.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/config/config.js +286 -0
- package/dist/humain/ask-user-question/vendor/config/config.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/config/index.d.ts +2 -0
- package/dist/humain/ask-user-question/vendor/config/index.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/config/index.js +2 -0
- package/dist/humain/ask-user-question/vendor/config/index.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/i18n/i18n.d.ts +64 -0
- package/dist/humain/ask-user-question/vendor/i18n/i18n.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/i18n/i18n.js +185 -0
- package/dist/humain/ask-user-question/vendor/i18n/i18n.js.map +1 -0
- package/dist/humain/ask-user-question/vendor/i18n/loader.d.ts +44 -0
- package/dist/humain/ask-user-question/vendor/i18n/loader.d.ts.map +1 -0
- package/dist/humain/ask-user-question/vendor/i18n/loader.js +55 -0
- package/dist/humain/ask-user-question/vendor/i18n/loader.js.map +1 -0
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +26 -16
- package/dist/humain/brand-logo.d.ts +2 -0
- package/dist/humain/brand-logo.d.ts.map +1 -1
- package/dist/humain/brand-logo.js +4 -0
- package/dist/humain/brand-logo.js.map +1 -1
- package/dist/humain/bundled-extension-names.d.ts +1 -0
- package/dist/humain/bundled-extension-names.d.ts.map +1 -1
- package/dist/humain/bundled-extension-names.js +1 -0
- package/dist/humain/bundled-extension-names.js.map +1 -1
- package/dist/humain/checklist/footer-progress.d.ts +7 -0
- package/dist/humain/checklist/footer-progress.d.ts.map +1 -0
- package/dist/humain/checklist/footer-progress.js +15 -0
- package/dist/humain/checklist/footer-progress.js.map +1 -0
- package/dist/humain/checklist/glyphs.d.ts +7 -0
- package/dist/humain/checklist/glyphs.d.ts.map +1 -0
- package/dist/humain/checklist/glyphs.js +8 -0
- package/dist/humain/checklist/glyphs.js.map +1 -0
- package/dist/humain/checklist/index.d.ts +6 -0
- package/dist/humain/checklist/index.d.ts.map +1 -0
- package/dist/humain/checklist/index.js +37 -0
- package/dist/humain/checklist/index.js.map +1 -0
- package/dist/humain/checklist/progress.d.ts +37 -0
- package/dist/humain/checklist/progress.d.ts.map +1 -0
- package/dist/humain/checklist/progress.js +234 -0
- package/dist/humain/checklist/progress.js.map +1 -0
- package/dist/humain/checklist/projector.d.ts +53 -0
- package/dist/humain/checklist/projector.d.ts.map +1 -0
- package/dist/humain/checklist/projector.js +198 -0
- package/dist/humain/checklist/projector.js.map +1 -0
- package/dist/humain/checklist/sidebar.d.ts +18 -0
- package/dist/humain/checklist/sidebar.d.ts.map +1 -0
- package/dist/humain/checklist/sidebar.js +38 -0
- package/dist/humain/checklist/sidebar.js.map +1 -0
- package/dist/humain/checklist/status-segment.d.ts +19 -0
- package/dist/humain/checklist/status-segment.d.ts.map +1 -0
- package/dist/humain/checklist/status-segment.js +59 -0
- package/dist/humain/checklist/status-segment.js.map +1 -0
- package/dist/humain/checklist/vendor/add-task-dialog.d.ts +54 -0
- package/dist/humain/checklist/vendor/add-task-dialog.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/add-task-dialog.js +238 -0
- package/dist/humain/checklist/vendor/add-task-dialog.js.map +1 -0
- package/dist/humain/checklist/vendor/commands.d.ts +38 -0
- package/dist/humain/checklist/vendor/commands.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/commands.js +193 -0
- package/dist/humain/checklist/vendor/commands.js.map +1 -0
- package/dist/humain/checklist/vendor/index.d.ts +3 -0
- package/dist/humain/checklist/vendor/index.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/index.js +276 -0
- package/dist/humain/checklist/vendor/index.js.map +1 -0
- package/dist/humain/checklist/vendor/render.d.ts +97 -0
- package/dist/humain/checklist/vendor/render.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/render.js +354 -0
- package/dist/humain/checklist/vendor/render.js.map +1 -0
- package/dist/humain/checklist/vendor/settings.d.ts +11 -0
- package/dist/humain/checklist/vendor/settings.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/settings.js +8 -0
- package/dist/humain/checklist/vendor/settings.js.map +1 -0
- package/dist/humain/checklist/vendor/store.d.ts +120 -0
- package/dist/humain/checklist/vendor/store.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/store.js +990 -0
- package/dist/humain/checklist/vendor/store.js.map +1 -0
- package/dist/humain/checklist/vendor/tools.d.ts +21 -0
- package/dist/humain/checklist/vendor/tools.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/tools.js +162 -0
- package/dist/humain/checklist/vendor/tools.js.map +1 -0
- package/dist/humain/checklist/vendor/types.d.ts +188 -0
- package/dist/humain/checklist/vendor/types.d.ts.map +1 -0
- package/dist/humain/checklist/vendor/types.js +32 -0
- package/dist/humain/checklist/vendor/types.js.map +1 -0
- package/dist/humain/gateway/catalog.d.ts +1 -0
- package/dist/humain/gateway/catalog.d.ts.map +1 -1
- package/dist/humain/gateway/catalog.js +1 -0
- package/dist/humain/gateway/catalog.js.map +1 -1
- package/dist/humain/gateway/client.d.ts +1 -0
- package/dist/humain/gateway/client.d.ts.map +1 -1
- package/dist/humain/gateway/client.js +8 -1
- package/dist/humain/gateway/client.js.map +1 -1
- package/dist/humain/gateway/http.d.ts.map +1 -1
- package/dist/humain/gateway/http.js +11 -3
- package/dist/humain/gateway/http.js.map +1 -1
- package/dist/humain/gateway/images.d.ts +3 -0
- package/dist/humain/gateway/images.d.ts.map +1 -0
- package/dist/humain/gateway/images.js +73 -0
- package/dist/humain/gateway/images.js.map +1 -0
- package/dist/humain/gateway/provider.js +1 -1
- package/dist/humain/gateway/provider.js.map +1 -1
- package/dist/humain/hcode/account-store.d.ts.map +1 -1
- package/dist/humain/hcode/account-store.js +3 -1
- package/dist/humain/hcode/account-store.js.map +1 -1
- package/dist/humain/hcode/account.d.ts.map +1 -1
- package/dist/humain/hcode/account.js +23 -13
- package/dist/humain/hcode/account.js.map +1 -1
- package/dist/humain/hcode/images.d.ts.map +1 -1
- package/dist/humain/hcode/images.js +19 -13
- package/dist/humain/hcode/images.js.map +1 -1
- package/dist/humain/hcode/login-failure.d.ts +1 -0
- package/dist/humain/hcode/login-failure.d.ts.map +1 -1
- package/dist/humain/hcode/login-failure.js +1 -0
- package/dist/humain/hcode/login-failure.js.map +1 -1
- package/dist/humain/hcode/provider.d.ts.map +1 -1
- package/dist/humain/hcode/provider.js +2 -1
- package/dist/humain/hcode/provider.js.map +1 -1
- package/dist/humain/hcode/run-credential.d.ts +1 -0
- package/dist/humain/hcode/run-credential.d.ts.map +1 -1
- package/dist/humain/hcode/run-credential.js +12 -4
- package/dist/humain/hcode/run-credential.js.map +1 -1
- package/dist/humain/index.d.ts.map +1 -1
- package/dist/humain/index.js +4 -0
- package/dist/humain/index.js.map +1 -1
- package/dist/humain/node-provider.d.ts.map +1 -1
- package/dist/humain/node-provider.js +37 -8
- package/dist/humain/node-provider.js.map +1 -1
- package/dist/main.d.ts +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +38 -26
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/chat-viewport.js +1 -1
- package/dist/modes/interactive/chat-viewport.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +7 -4
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +1 -1
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +20 -1
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts +1 -1
- package/dist/modes/interactive/components/extension-editor.js +2 -2
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +7 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +74 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +11 -4
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +2 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +56 -8
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +13 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +10 -9
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +3 -3
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +4 -3
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +83 -37
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +3 -3
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/status-indicator.d.ts +18 -7
- package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-indicator.js +70 -24
- package/dist/modes/interactive/components/status-indicator.js.map +1 -1
- package/dist/modes/interactive/components/status-line.d.ts +16 -0
- package/dist/modes/interactive/components/status-line.d.ts.map +1 -0
- package/dist/modes/interactive/components/status-line.js +51 -0
- package/dist/modes/interactive/components/status-line.js.map +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts +5 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +8 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
- package/dist/modes/interactive/components/visual-truncate.js +11 -3
- package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +13 -3
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +17 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +232 -108
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/program-status-reporter.d.ts +2 -0
- package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -1
- package/dist/modes/interactive/program-status-reporter.js +4 -0
- package/dist/modes/interactive/program-status-reporter.js.map +1 -1
- package/dist/modes/interactive/session-share.d.ts.map +1 -1
- package/dist/modes/interactive/session-share.js +9 -1
- package/dist/modes/interactive/session-share.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +34 -7
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/jsonl.js +6 -5
- package/dist/modes/rpc/jsonl.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +2 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +9 -2
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +2 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +113 -13
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +22 -1
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/uncaught-errors.d.ts +20 -0
- package/dist/modes/uncaught-errors.d.ts.map +1 -0
- package/dist/modes/uncaught-errors.js +56 -0
- package/dist/modes/uncaught-errors.js.map +1 -0
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +10 -1
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/clipboard-image.js +1 -1
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.js +2 -2
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/image-process.d.ts +5 -0
- package/dist/utils/image-process.d.ts.map +1 -1
- package/dist/utils/image-process.js +22 -4
- package/dist/utils/image-process.js.map +1 -1
- package/dist/utils/output-files.d.ts +44 -7
- package/dist/utils/output-files.d.ts.map +1 -1
- package/dist/utils/output-files.js +206 -12
- package/dist/utils/output-files.js.map +1 -1
- package/dist/utils/piped-stdin.d.ts +21 -0
- package/dist/utils/piped-stdin.d.ts.map +1 -0
- package/dist/utils/piped-stdin.js +60 -0
- package/dist/utils/piped-stdin.js.map +1 -0
- package/dist/utils/shell.d.ts +5 -2
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +77 -8
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +33 -2
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +77 -10
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +1 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +9 -8
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/wsl.d.ts +8 -2
- package/dist/utils/wsl.d.ts.map +1 -1
- package/dist/utils/wsl.js +12 -3
- package/dist/utils/wsl.js.map +1 -1
- package/docs/cli.md +45 -3
- package/docs/codemode.md +7 -3
- package/docs/compaction.md +1 -1
- package/docs/coordination.md +16 -4
- package/docs/development.md +6 -0
- package/docs/environment-variables.md +5 -3
- package/docs/extensions.md +19 -5
- package/docs/keybindings.md +2 -0
- package/docs/llama-cpp.md +2 -2
- package/docs/message-types.md +1 -0
- package/docs/models-configuration.md +14 -3
- package/docs/models.md +29 -7
- package/docs/providers.md +25 -3
- package/docs/rpc-commands.md +25 -2
- package/docs/rpc.md +20 -0
- package/docs/run-preflight.md +2 -2
- package/docs/session-format.md +9 -0
- package/docs/settings.md +35 -5
- package/docs/shell-aliases.md +1 -1
- package/docs/slash-commands.md +3 -1
- package/docs/terminal-setup.md +25 -0
- package/docs/windows.md +2 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/rpc-extension-ui.ts +8 -7
- package/npm-shrinkwrap.json +209 -180
- package/package.json +26 -20
- package/schemas/keybindings.schema.json +12 -0
- package/schemas/models.schema.json +20 -7
- package/schemas/settings.schema.json +43 -5
- package/src/coordination/UPSTREAM.md +27 -1
- package/src/coordination/upstream.json +3 -3
- package/src/humain/ask-user-question/UPSTREAM.md +31 -0
- package/src/humain/ask-user-question/upstream.json +258 -0
- package/src/humain/ask-user-question/vendor/ask/LICENSE +21 -0
- package/src/humain/ask-user-question/vendor/ask/locales/de.json +38 -0
- package/src/humain/ask-user-question/vendor/ask/locales/en.json +41 -0
- package/src/humain/ask-user-question/vendor/ask/locales/es.json +38 -0
- package/src/humain/ask-user-question/vendor/ask/locales/fr.json +38 -0
- package/src/humain/ask-user-question/vendor/ask/locales/pt-BR.json +38 -0
- package/src/humain/ask-user-question/vendor/ask/locales/pt.json +38 -0
- package/src/humain/ask-user-question/vendor/ask/locales/ru.json +38 -0
- package/src/humain/ask-user-question/vendor/ask/locales/uk.json +38 -0
- package/src/humain/ask-user-question/vendor/ask/locales/zh.json +40 -0
- package/src/humain/ask-user-question/vendor/config/LICENSE +21 -0
- package/src/humain/ask-user-question/vendor/i18n/LICENSE +21 -0
- package/src/humain/caveman/UPSTREAM.md +44 -11
- package/src/humain/caveman/upstream.json +3 -3
- package/src/humain/caveman/vendor/NOTICE +4 -0
- package/dist/bundle/chunks/anthropic-messages-XFCDMGD6.js +0 -77
- package/dist/bundle/chunks/azure-openai-responses-F4KQM3NK.js +0 -15
- package/dist/bundle/chunks/bowser-DXKSTXFQ.js +0 -89
- package/dist/bundle/chunks/chunk-3E37CJCE.js +0 -34
- package/dist/bundle/chunks/chunk-3HVHETMU.js +0 -18
- package/dist/bundle/chunks/chunk-3PJ7NPWN.js +0 -80
- package/dist/bundle/chunks/chunk-6JTCRCNF.js +0 -74
- package/dist/bundle/chunks/chunk-F77J5EQZ.js +0 -3
- package/dist/bundle/chunks/chunk-GPLWWO5Q.js +0 -121
- package/dist/bundle/chunks/chunk-GV5OVRKK.js +0 -4
- package/dist/bundle/chunks/chunk-JBSWWCT5.js +0 -12
- package/dist/bundle/chunks/chunk-JQBZUFH7.js +0 -3580
- package/dist/bundle/chunks/chunk-JWOPWHVH.js +0 -51
- package/dist/bundle/chunks/chunk-KRBELWQH.js +0 -7
- package/dist/bundle/chunks/chunk-PFBAIRCY.js +0 -56
- package/dist/bundle/chunks/chunk-Q5RKNQ2T.js +0 -73
- package/dist/bundle/chunks/chunk-QFDZEUFU.js +0 -12
- package/dist/bundle/chunks/chunk-SKCJ25SX.js +0 -24
- package/dist/bundle/chunks/chunk-UEW6TUSP.js +0 -36
- package/dist/bundle/chunks/chunk-UZOIHLNU.js +0 -23
- package/dist/bundle/chunks/chunk-YSWDFV2L.js +0 -11
- package/dist/bundle/chunks/chunk-YZMQXAJM.js +0 -8
- package/dist/bundle/chunks/entry-2GZ3PTWQ.js +0 -2
- package/dist/bundle/chunks/google-generative-ai-WIASMWS3.js +0 -22
- package/dist/bundle/chunks/google-vertex-WSPHRZIZ.js +0 -25
- package/dist/bundle/chunks/interactive-mode-SDUO5OLD.js +0 -5
- package/dist/bundle/chunks/mistral-conversations-7JYDDRUT.js +0 -43
- package/dist/bundle/chunks/openai-codex-responses-7PAML4NF.js +0 -102
- package/dist/bundle/chunks/openai-completions-UJDAIGTK.js +0 -87
- package/dist/bundle/chunks/openai-responses-2WNCE6AY.js +0 -26
- package/dist/bundle/chunks/openrouter-images-V3UCCO6X.js +0 -8
- package/dist/bundle/chunks/pi-messages-TQ7LJUNQ.js +0 -28
- package/dist/bundle/chunks/runtime-H7LYNKCZ.js +0 -2
- package/dist/bundle/chunks/session-picker-EYKCMFQR.js +0 -4
- package/dist/bundle/chunks/startup-ui-7ODOR34R.js +0 -3
- package/dist/bundle/chunks/typesafe-system-one-YP7GGN4C.js +0 -3
- package/dist/bundle/chunks/virtual-modules-IU5KWB2C.js +0 -28
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isObject}from"./chunk-
|
|
3
|
-
import{APP_TITLE,ENV_MCP_CLIENT_METADATA_URL,VERSION,getAgentDir}from"./chunk-
|
|
2
|
+
import{oauthErrorHtml,oauthSuccessHtml}from"./chunk-7NKUVTBL.js";import{JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isObject}from"./chunk-QZWUXGY7.js";import{FileAuthStorageBackend,mcpNamespace,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-GMPJWLZS.js";import{sliceTail}from"./chunk-7DIRHF4H.js";import{require_proper_lockfile}from"./chunk-F6ZAYLU2.js";
|
|
3
|
+
import{APP_TITLE,ENV_MCP_CLIENT_METADATA_URL,VERSION,getAgentDir}from"./chunk-CKFLQGJN.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";import{pathToFileURL}from"node:url";import{createServer}from"node:http";var ALLOWED_ERROR_CODES=new Set(["invalid_request","invalid_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope","access_denied","unsupported_response_type","server_error","temporarily_unavailable","invalid_token","insufficient_scope","authorization_pending","slow_down","expired_token","invalid_redirect_uri","invalid_client_metadata","invalid_software_statement","unapproved_software_statement"]);function isAllowedOAuthErrorCode(value){return ALLOWED_ERROR_CODES.
|
|
4
4
|
has(value)}function sanitizeOAuthErrorCode(value,fallback="server_error"){return value&&ALLOWED_ERROR_CODES.has(value)?value:fallback}var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){let format=issuer=>issuer===void 0?"none":JSON.stringify(issuer);super(`OAuth issuer mismatch: expected ${format(
|
|
5
5
|
expected)}, received ${format(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRedirectError=class extends Error{constructor(){super("OAuth endpoint redirected; refusing to follow the redirect"),this.name="OAuthRedirectError"}},
|
|
6
6
|
OAuthRegistrationError=class extends Error{status;code;constructor(status,code){super(`OAuth dynamic client registration failed with status ${status}${code?`: ${code}`:""}`),this.name="OAuthRegistrationError",this.status=status,this.code=code}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}};function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
|
|
@@ -84,16 +84,16 @@ options.prompt,signal);await authorizeMcp(provider,{...flow,authorizationCode:co
|
|
|
84
84
|
ign-in. Run ${provider?`/login ${provider}`:"/mcp"} to sign in.`}function usesOAuth(entry){let{config}=entry;return!("url"in config)||config.auth?!1:!Object.keys(config.headers??{}).some(header=>header.toLowerCase()==="authorization")}function expandHome(value){return value==="~"?homedir():value.startsWith("~/")||process.platform==="win32"&&value.startsWith("~\\")?join2(homedir(),value.slice(2)):value}function createDefaultTransport(entry,cwd,authProvider){let{config,name}=entry;if("url"in config)
|
|
85
85
|
return new StreamableHttpTransport({url:config.url,headers:resolveHeadersOrThrow(config.headers,`MCP server "${name}"`),authProvider});let env={};for(let[key,value]of Object.entries(config.env??{}))env[key]=resolveConfigValueOrThrow(value,`MCP server "${name}" env "${key}"`);return new StdioTransport({command:expandHome(config.command),args:config.args?.map(expandHome),cwd:resolve(cwd,expandHome(config.cwd??".")),env,stderr:"pipe"})}async function withoutTemplates(list,empty){try{return await list()}catch(error){
|
|
86
86
|
if(error instanceof McpError&&error.code===JSON_RPC_ERROR_CODES.methodNotFound)return empty;throw error}}function listTemplates(client,options={}){return withoutTemplates(()=>client.listResourceTemplates(options),[])}var McpServerConnection=class{entry;state="connecting";error;tools=[];hasResources=!1;instructions;challenge;client;opening;shutdown=new AbortController;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(options){this.entry=options.entry,this.cwd=options.cwd,
|
|
87
|
-
this.createTransport=options.createTransport,this.onTools=options.onTools,this.onChange=options.onChange,this.log=options.log;let url=this.oauthUrl,provider="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=url?createMcpAuthProvider({serverUrl:url,store:options.credentials.forServer(this.entry.name,url),settings:()=>this.oauthSettings(),onChallenge:challenge=>{this.challenge=challenge}}):provider?{token:async()=>options.providerToken?.(provider),
|
|
88
|
-
void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??DEFAULT_TIMEOUT_SECONDS)*1e3}get oauthUrl(){return usesOAuth(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){let oauth="url"in this.entry.config?this.entry.config.oauth:void 0;return oauth?{clientId:oauth.clientId,clientSecret:oauth.clientSecret===void 0?void 0:resolveConfigValueOrThrow(oauth.clientSecret
|
|
89
|
-
entry.name}" oauth.clientSecret`),callbackPort:oauth.callbackPort,callbackUrl:oauth.callbackUrl,scope:oauth.scope,clientName:oauth.clientName,clientRegistration:oauth.clientRegistration,authServerMetadataUrl:oauth.authServerMetadataUrl?new URL(oauth.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.
|
|
90
|
-
this.opening=void 0}),this.opening)}callTool(name,args,options){return this.withClient(client=>client.callTool(name,args,options))}readResource(uri,options){return this.withClient(client=>client.readResource(uri,options),!0)}resourcesPage(cursor,options){return this.withClient(client=>client.listResourcesPage(cursor,options),!0)}resourceTemplatesPage(cursor,options){return this.withClient(client=>withoutTemplates(()=>client.listResourceTemplatesPage(cursor,options),{resourceTemplates:[]})
|
|
91
|
-
return this.withClient(client=>client.listResources(options),!0)}allResourceTemplates(options){return this.withClient(client=>listTemplates(client,options),!0)}async withClient(run,readOnly=!1){for(let attempt=1;;attempt++){let client=await this.getClient();try{return await run(client)}catch(error){if(readOnly&&attempt===1&&error instanceof McpHttpError&&isTransientError(error)){await new Promise(resolve2=>setTimeout(resolve2,CONNECT_RETRY_DELAYS_MS[0]));continue}if(error instanceof
|
|
92
|
-
attempt===1){this.client===client&&(this.client=void 0);continue}throw this.needsSignIn(error)?(await this.dropClient(client),this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):error}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(error){return error instanceof
|
|
93
|
-
this.authProvider!==void 0&&error instanceof McpAuthRequiredError}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(client){this.client===client&&(this.client=void 0),await client.close().catch(()=>{})}async open(){this.state="connecting",this.changed();let retries="url"in this.entry.config?CONNECT_RETRY_DELAYS_MS:[];for(let attempt=0;;attempt++){this.stderrTail=void 0;
|
|
94
|
-
if(this.closed||delay===void 0||!isTransientError(error))throw this.connectFailed(error);if(await sleep(delay,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(error)}}}async connectOnce(){let client=new McpClient({name:"pi",version:VERSION,requestTimeoutMs:this.timeoutMs,roots:[{uri:pathToFileURL(this.cwd).href,name:basename(this.cwd)}]}),log=this.log;log&&client.onNotification("
|
|
95
|
-
closeClient=()=>(closing??=client.close().catch(()=>{}),closing);this.shutdown.signal.addEventListener("abort",closeClient,{once:!0});let transport;try{transport=this.createTransport(this.entry,this.cwd,this.authProvider),await client.connect(transport),client.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(client)});let stdio=transport instanceof StdioTransport?transport:void 0;client.onClose(()=>this.
|
|
96
|
-
tools?await client.listTools():[];if(this.closed)throw new Error("shut down while connecting");if(client.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=client,this.tools=tools,this.hasResources=client.serverCapabilities?.resources!==void 0,this.instructions=client.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),client}catch(error){
|
|
97
|
-
(this.stderrTail=sliceTail(transport.stderr.trim(),STDERR_TAIL_CHARS)||void 0),error}finally{this.shutdown.signal.removeEventListener("abort",closeClient)}}connectFailed(error){return this.needsSignIn(error)&&!this.closed?(this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${errorMessage(error)}
|
|
87
|
+
this.createTransport=options.createTransport,this.onTools=options.onTools,this.onChange=options.onChange,this.log=options.log;let url=this.oauthUrl,provider="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=url&&options.credentials?createMcpAuthProvider({serverUrl:url,store:options.credentials.forServer(this.entry.name,url),settings:()=>this.oauthSettings(),onChallenge:challenge=>{this.challenge=challenge}}):provider?{token:async()=>options.providerToken?.(provider),
|
|
88
|
+
settled:async()=>{}}:void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??DEFAULT_TIMEOUT_SECONDS)*1e3}get oauthUrl(){return usesOAuth(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){let oauth="url"in this.entry.config?this.entry.config.oauth:void 0;return oauth?{clientId:oauth.clientId,clientSecret:oauth.clientSecret===void 0?void 0:resolveConfigValueOrThrow(oauth.clientSecret,
|
|
89
|
+
`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:oauth.callbackPort,callbackUrl:oauth.callbackUrl,scope:oauth.scope,clientName:oauth.clientName,clientRegistration:oauth.clientRegistration,authServerMetadataUrl:oauth.authServerMetadataUrl?new URL(oauth.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.
|
|
90
|
+
open().finally(()=>{this.opening=void 0}),this.opening)}callTool(name,args,options){return this.withClient(client=>client.callTool(name,args,options))}readResource(uri,options){return this.withClient(client=>client.readResource(uri,options),!0)}resourcesPage(cursor,options){return this.withClient(client=>client.listResourcesPage(cursor,options),!0)}resourceTemplatesPage(cursor,options){return this.withClient(client=>withoutTemplates(()=>client.listResourceTemplatesPage(cursor,options),{resourceTemplates:[]}),
|
|
91
|
+
!0)}allResources(options){return this.withClient(client=>client.listResources(options),!0)}allResourceTemplates(options){return this.withClient(client=>listTemplates(client,options),!0)}async withClient(run,readOnly=!1){for(let attempt=1;;attempt++){let client=await this.getClient();try{return await run(client)}catch(error){if(readOnly&&attempt===1&&error instanceof McpHttpError&&isTransientError(error)){await new Promise(resolve2=>setTimeout(resolve2,CONNECT_RETRY_DELAYS_MS[0]));continue}if(error instanceof
|
|
92
|
+
McpSessionExpiredError&&attempt===1){this.client===client&&(this.client=void 0);continue}throw this.needsSignIn(error)?(await this.dropClient(client),this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):error}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(error){return error instanceof
|
|
93
|
+
McpOAuthAuthorizationRequiredError||(this.authProvider!==void 0||this.oauthUrl!==void 0)&&error instanceof McpAuthRequiredError}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(client){this.client===client&&(this.client=void 0),await client.close().catch(()=>{})}async open(){this.state="connecting",this.changed();let retries="url"in this.entry.config?CONNECT_RETRY_DELAYS_MS:[];for(let attempt=0;;attempt++){this.stderrTail=void 0;
|
|
94
|
+
try{return await this.connectOnce()}catch(error){let delay=retries[attempt];if(this.closed||delay===void 0||!isTransientError(error))throw this.connectFailed(error);if(await sleep(delay,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(error)}}}async connectOnce(){let client=new McpClient({name:"pi",version:VERSION,requestTimeoutMs:this.timeoutMs,roots:[{uri:pathToFileURL(this.cwd).href,name:basename(this.cwd)}]}),log=this.log;log&&client.onNotification("no\
|
|
95
|
+
tifications/message",params=>log.write(this.entry.name,params));let closing,closeClient=()=>(closing??=client.close().catch(()=>{}),closing);this.shutdown.signal.addEventListener("abort",closeClient,{once:!0});let transport;try{transport=this.createTransport(this.entry,this.cwd,this.authProvider),await client.connect(transport),client.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(client)});let stdio=transport instanceof StdioTransport?transport:void 0;client.onClose(()=>this.
|
|
96
|
+
handleClientClose(client,stdio));let tools=client.serverCapabilities?.tools?await client.listTools():[];if(this.closed)throw new Error("shut down while connecting");if(client.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=client,this.tools=tools,this.hasResources=client.serverCapabilities?.resources!==void 0,this.instructions=client.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),client}catch(error){
|
|
97
|
+
throw await closeClient(),transport instanceof StdioTransport&&(this.stderrTail=sliceTail(transport.stderr.trim(),STDERR_TAIL_CHARS)||void 0),error}finally{this.shutdown.signal.removeEventListener("abort",closeClient)}}connectFailed(error){return this.needsSignIn(error)&&!this.closed?(this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${errorMessage(error)}
|
|
98
98
|
${this.stderrTail}`:errorMessage(error),this.changed(),new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`))}handleClientClose(client,stdio){if(this.client!==client||this.closed)return;this.client=void 0,this.state="disconnected";let stderr=stdio?sliceTail(stdio.stderr.trim(),STDERR_TAIL_CHARS):void 0;this.error=stderr?`Connection closed
|
|
99
99
|
${stderr}`:"Connection closed",this.changed()}async refreshTools(client){try{let tools=await client.listTools();if(this.client!==client||this.closed)return;this.tools=tools,this.onTools(this)}catch(error){this.error=`Failed to refresh tools: ${errorMessage(error)}`}this.changed()}async close(){this.shutdown.abort(),this.state="closed",this.changed();let client=this.client;this.client=void 0,await Promise.all([client?.close().catch(()=>{}),this.opening?.catch(()=>{})]),await this.authProvider?.settled()}};export{McpOAuthCredentialStore,McpSignInCancelledError,signInMcpServer,McpServerLog,createDefaultTransport,McpServerConnection};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{FirstTimeSetupComponent,getDefaultThemeName}from"./chunk-WCKS2DPT.js";import{ExtensionInputComponent,ExtensionSelectorComponent,dialogBlockedStatus,requestTerminalColors}from"./chunk-UOSJTMCL.js";import{KeybindingsManager,areExperimentalFeaturesEnabled,flushStdout}from"./chunk-HWFAAGYK.js";import{DEFAULT_THEME_NAME,getTerminalTheme,initTheme,loadThemeFromPath,markTerminalColorsPending,resolveThemeSetting,setRegisteredThemes,setTerminalColors,setTheme}from"./chunk-FLWO3H5J.js";
|
|
3
|
+
import{DefaultPackageManager,resolveHcodeEnvironment}from"./chunk-OADQOW67.js";import{SettingsManager}from"./chunk-4SL6URR3.js";import{ProcessTerminal,TuiMainScreen,setCapabilityOverrides,setKeybindings}from"./chunk-H35P7ROY.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,FIRST_TIME_SETUP_ENABLED,PACKAGE_NAME,getAgentDir,getSettingsPath,stripBom}from"./chunk-CKFLQGJN.js";import{existsSync,readFileSync}from"fs";var OFFICIAL_PACKAGE_NAME="@humain/humain-code",OFFICIAL_APP_NAME="humain-terminal",OFFICIAL_CONFIG_DIR_NAME=".humain-terminal";function isOfficialDistribution({packageName,appName,configDirName}){return packageName===OFFICIAL_PACKAGE_NAME&&appName===OFFICIAL_APP_NAME&&configDirName===OFFICIAL_CONFIG_DIR_NAME}function loadThemes(resources){let themes=[],seen=new Set;for(let resource of resources)if(resource.enabled)try{let loadedTheme=loadThemeFromPath(resource.path);if(loadedTheme.name){if(seen.
|
|
4
|
+
has(loadedTheme.name))continue;seen.add(loadedTheme.name)}themes.push(loadedTheme)}catch{}return themes}async function loadStartupThemes(settingsManager){let globalSettingsManager=SettingsManager.inMemory(settingsManager.getGlobalSettings(),{projectTrusted:!1}),resolvedPaths=await new DefaultPackageManager({cwd:process.cwd(),agentDir:getAgentDir(),settingsManager:globalSettingsManager}).resolve(async()=>"skip");return loadThemes(resolvedPaths.themes)}async function createStartupTui(settingsManager){
|
|
5
|
+
setCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides()),setRegisteredThemes(await loadStartupThemes(settingsManager)),markTerminalColorsPending(),initTheme(resolveThemeSetting(settingsManager.getThemeSetting(),getTerminalTheme())??DEFAULT_THEME_NAME),setKeybindings(KeybindingsManager.create());let ui=new TuiMainScreen(new ProcessTerminal,settingsManager.getShowHardwareCursor(),getAgentDir());return ui.setClearOnShrink(settingsManager.getClearOnShrink()),ui}function startStartupTui(ui,settingsManager){
|
|
6
|
+
ui.start();let themeSetting=settingsManager.getThemeSetting();queryStartupTerminalColors(ui,()=>{setTheme(resolveThemeSetting(themeSetting,getTerminalTheme())??DEFAULT_THEME_NAME)})}function queryStartupTerminalColors(ui,onColors){requestTerminalColors(ui,colors=>{setTerminalColors(colors),onColors(),ui.invalidate(),ui.requestRender()})}function showStartupDialog(ui,component,blocked,settingsManager){ui.addChild(component),ui.setFocus(component),ui.terminal.setProgramStatus({state:"blocked",app:APP_NAME,
|
|
7
|
+
...blocked}),startStartupTui(ui,settingsManager)}async function clearStartupTui(ui){ui.clear(),ui.requestRender(),await new Promise(resolve=>setTimeout(resolve,25))}function shouldRunFirstTimeSetupForDistribution(metadata){return FIRST_TIME_SETUP_ENABLED||isOfficialDistribution(metadata)&&areExperimentalFeaturesEnabled()}function shouldRunFirstTimeSetup(settingsPath=getSettingsPath()){if(!shouldRunFirstTimeSetupForDistribution({packageName:PACKAGE_NAME,appName:APP_NAME,configDirName:CONFIG_DIR_NAME})||
|
|
8
|
+
process.env[ENV_AGENT_DIR]||process.env.PI_CODING_AGENT_DIR)return!1;try{let settings=JSON.parse(stripBom(readFileSync(settingsPath,"utf-8")));return!(typeof settings=="object"&&settings!==null&&"hcodeMetadataDisclosureVersion"in settings&&settings.hcodeMetadataDisclosureVersion===1)}catch{return!0}}async function showStartupSelector(settingsManager,title,options,blockedKind="question"){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let settled=!1,finish=async result=>{
|
|
9
|
+
settled||(settled=!0,await clearStartupTui(ui),ui.stop(),await flushStdout(),resolve(result))},selector=new ExtensionSelectorComponent(title,options.map(option=>option.label),option=>{finish(options.find(entry=>entry.label===option)?.value)},()=>{finish(void 0)},{tui:ui});showStartupDialog(ui,selector,dialogBlockedStatus(blockedKind,title),settingsManager)})}async function showFirstTimeSetup(settingsManager,origin=resolveHcodeEnvironment().origin){let initialStep=existsSync(getSettingsPath())?"d\
|
|
10
|
+
isclosure":"theme",ui=await createStartupTui(settingsManager);return new Promise((resolve,reject)=>{let settled=!1,finish=async result=>{if(!settled){settled=!0;try{result&&await settingsManager.acknowledgeHcodeMetadataDisclosure(result.theme),await clearStartupTui(ui)}catch(error){ui.stop(),reject(error);return}ui.stop(),await flushStdout(),resolve()}},previewTheme=initialStep==="theme"?getDefaultThemeName():resolveThemeSetting(settingsManager.getThemeSetting(),getTerminalTheme())??DEFAULT_THEME_NAME;
|
|
11
|
+
setTheme(previewTheme);let component=new FirstTimeSetupComponent({origin,initialStep,tui:ui,onThemePreview:themeName=>{previewTheme=themeName,setTheme(themeName),ui.requestRender()},onSubmit:result=>{finish(result)},onCancel:()=>{finish(void 0)}});ui.addChild(component),ui.setFocus(component),ui.terminal.setProgramStatus({state:"blocked",app:APP_NAME,kind:"permission",message:"Metadata disclosure"}),ui.start(),ui.requestRender(),queryStartupTerminalColors(ui,()=>setTheme(previewTheme))})}async function showStartupInput(settingsManager,title,placeholder,blockedKind="\
|
|
12
|
+
question"){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let settled=!1,finish=async result=>{settled||(settled=!0,input.dispose(),await clearStartupTui(ui),ui.stop(),await flushStdout(),resolve(result))},input=new ExtensionInputComponent(title,placeholder,value=>{finish(value)},()=>{finish(void 0)},{tui:ui});showStartupDialog(ui,input,dialogBlockedStatus(blockedKind,title),settingsManager)})}export{createStartupTui,startStartupTui,shouldRunFirstTimeSetupForDistribution,shouldRunFirstTimeSetup,showStartupSelector,showFirstTimeSetup,showStartupInput};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{
|
|
2
|
+
import{KeybindingsManager}from"./chunk-HWFAAGYK.js";import{DynamicBorder}from"./chunk-XGOJCV6Z.js";import{keyHint,keyText}from"./chunk-MXF3KYLZ.js";import{theme}from"./chunk-FLWO3H5J.js";import{Container,Input,Spacer,Text,fuzzyMatch,getKeybindings,truncateToWidth,visibleWidth}from"./chunk-H35P7ROY.js";import{canonicalizePath,getPathComparisonKey,shortenHomePath}from"./chunk-CKFLQGJN.js";import{spawnSync}from"node:child_process";import{existsSync}from"node:fs";import{unlink}from"node:fs/promises";function normalizeWhitespaceLower(text){return text.toLowerCase().replace(/\s+/g," ").trim()}var TIER_NAME=0,TIER_TEXT=1,TIER_FUZZY=2,TIER_WEIGHT=1e6,messageTextCache=new WeakMap;function getMessageText(session){let cached=messageTextCache.get(session);return(!cached||cached.source!==session.allMessagesText)&&(cached={source:session.allMessagesText,lower:session.allMessagesText.toLowerCase()},messageTextCache.set(session,cached)),cached}function getNormalizedMessageText(session){let cached=getMessageText(
|
|
3
3
|
session);return cached.normalized??=cached.lower.replace(/\s+/g," ").trim(),cached.normalized}function tierScore(tier,score=0){return tier*TIER_WEIGHT+score}function matchLiteralToken(session,value){let name=session.name?.toLowerCase()??"";if(name.includes(value))return tierScore(TIER_NAME,fuzzyMatch(value,name).score);if(session.id.toLowerCase().includes(value)||getMessageText(session).lower.includes(value)||session.cwd.toLowerCase().includes(value))return tierScore(TIER_TEXT)}function matchFuzzyToken(session,value){
|
|
4
4
|
let literal=matchLiteralToken(session,value.toLowerCase());if(literal!==void 0)return literal;let best;for(let field of[session.name??"",session.cwd]){let m=fuzzyMatch(value,field);m.matches&&(best===void 0||m.score<best)&&(best=m.score)}return best===void 0?void 0:tierScore(TIER_FUZZY,best)}function matchPhraseToken(session,phrase){let name=normalizeWhitespaceLower(session.name??"");if(name.includes(phrase))return tierScore(TIER_NAME,fuzzyMatch(phrase,name).score);if(session.id.toLowerCase().includes(
|
|
5
5
|
phrase)||getNormalizedMessageText(session).includes(phrase)||normalizeWhitespaceLower(session.cwd).includes(phrase))return tierScore(TIER_TEXT)}function matchRegex(session,regex){if(session.name&®ex.test(session.name))return tierScore(TIER_NAME);if(regex.test(session.id)||regex.test(session.allMessagesText)||regex.test(session.cwd))return tierScore(TIER_TEXT)}function hasSessionName(session){return!!session.name?.trim()}function matchesNameFilter(session,filter){return filter==="all"?!0:hasSessionName(
|
|
@@ -23,17 +23,17 @@ let selected=this.filteredSessions[this.selectedIndex];this.onSelect&&this.onSel
|
|
|
23
23
|
if(this.allSessions=sessions,this.showCwd=showCwd,this.filterSessions(this.searchInput.getValue()),!this.selectionTouched)this.selectedIndex=0;else if(selectedPath){let selectedIndex=this.filteredSessions.findIndex(node=>node.session.path===selectedPath);selectedIndex>=0?(this.selectedIndex=selectedIndex,this.pendingSelectedPath=void 0):partial?this.pendingSelectedPath=selectedPath:this.pendingSelectedPath=void 0}}filterSessions(query){let trimmed=query.trim(),nameFiltered=this.nameFilter==="all"?
|
|
24
24
|
this.allSessions:this.allSessions.filter(session=>hasSessionName(session));if(this.sortMode==="threaded"&&!trimmed){let roots=buildSessionTree(nameFiltered);this.filteredSessions=flattenSessionTree(roots)}else{let filtered=filterAndSortSessions(nameFiltered,query,this.sortMode,"all");this.filteredSessions=filtered.map(session=>({session,depth:0,isLast:!0,ancestorContinues:[]}))}this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredSessions.length-1))}setConfirmingDeletePath(path){
|
|
25
25
|
this.confirmingDeletePath=path,this.onDeleteConfirmationChange?.(path)}startDeleteConfirmationForSelectedSession(){let selected=this.filteredSessions[this.selectedIndex];if(selected){if(this.isCurrentSessionPath(selected.session.path)){this.onError?.("Cannot delete the currently active session");return}this.setConfirmingDeletePath(selected.session.path)}}isCurrentSessionPath(path){return this.currentSessionPathKey?getSessionPathKey(path)===this.currentSessionPathKey:!1}invalidate(){}render(width){
|
|
26
|
-
let lines=[];if(lines.push(...this.searchInput.render(width)),lines.push(""),this.filteredSessions.length===0){let emptyMessage;if(this.nameFilter==="named"){let toggleKey=keyText("app.session.toggleNamedFilter");this.showCwd?emptyMessage=` No named sessions found. Press ${toggleKey} to show all.`:emptyMessage=` No named sessions in current folder. Press ${toggleKey} to show all, or
|
|
27
|
-
|
|
28
|
-
isCurrent=this.isCurrentSessionPath(session.path),prefix=this.buildTreePrefix(node),hasName=!!session.name,normalizedMessage=(session.name??session.firstMessage).replace(/[\x00-\x1f\x7f]/g," ").trim(),age=formatSessionDate(session.modified),rightPart=`${String(session.messageCount)} ${age}`;this.showCwd&&session.cwd&&(rightPart=`${shortenHomePath(session.cwd)} ${rightPart}`),this.showPath&&(rightPart=`${shortenHomePath(session.path)} ${rightPart}`);let cursor=isSelected?
|
|
29
|
-
" ",prefixWidth=visibleWidth(prefix),rightWidth=visibleWidth(rightPart)+2,availableForMsg=width-2-prefixWidth-rightWidth,truncatedMsg=truncateToWidth(normalizedMessage,Math.max(10,availableForMsg),"\u2026"),messageColor=null;isConfirmingDelete?messageColor="error":isCurrent?messageColor="accent":hasName&&(messageColor="warning");let styledMsg=messageColor?theme.fg(messageColor,truncatedMsg):truncatedMsg;isSelected&&(styledMsg=theme.bold(styledMsg));let leftPart=cursor+
|
|
30
|
-
leftWidth=visibleWidth(leftPart),spacing=Math.max(1,width-leftWidth-visibleWidth(rightPart)),styledRight=theme.fg(isConfirmingDelete?"error":"dim",rightPart),line=leftPart+" ".repeat(spacing)+styledRight;isSelected&&(line=theme.bg("selectedBg",line)),lines.push(truncateToWidth(line,width))}if(startIndex>0||endIndex<this.filteredSessions.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredSessions.length})`,scrollInfo=theme.fg("muted",truncateToWidth(
|
|
31
|
-
scrollInfo)}return lines}buildTreePrefix(node){if(node.depth===0)return"";let parts=node.ancestorContinues.map(continues=>continues?"\u2502 ":" "),branch=node.isLast?"\u2514\u2500 ":"\u251C\u2500 ";return parts.join("")+branch}handleInput(keyData){let kb=getKeybindings();if(this.confirmingDeletePath!==null){if(kb.matches(keyData,"tui.select.confirm")){let pathToDelete=this.confirmingDeletePath;this.setConfirmingDeletePath(null),this.onDeleteSession?.(pathToDelete);
|
|
32
|
-
"tui.select.cancel")){this.setConfirmingDeletePath(null);return}return}if(kb.matches(keyData,"tui.input.tab")){this.onToggleScope&&this.onToggleScope();return}if(kb.matches(keyData,"app.session.toggleSort")){this.onToggleSort?.();return}if(this.keybindings.matches(keyData,"app.session.toggleNamedFilter")){this.onToggleNameFilter?.();return}if(kb.matches(keyData,"app.session.togglePath")){this.showPath=!this.showPath,this.onTogglePath?.(this.showPath);return}if(kb.matches(
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
let selected=this.filteredSessions[this.selectedIndex];selected&&this.onSelect&&this.onSelect(selected.session.path)}else kb.matches(keyData,"tui.select.cancel")?this.onCancel&&this.onCancel():this.handleSearchInput(keyData)}handleSearchInput(keyData){let previousQuery=this.searchInput.getValue();this.searchInput.handleInput(keyData);let query=this.searchInput.getValue();query!==previousQuery&&(this.filterSessions(query),query.trim()&&(this.selectedIndex=0,this.selectionTouched
|
|
36
|
-
void 0))}};async function deleteSessionFile(sessionPath){let trashArgs=sessionPath.startsWith("-")?["--",sessionPath]:[sessionPath],trashResult=spawnSync("trash",trashArgs,{encoding:"utf-8"}),getTrashErrorHint=()=>{let parts=[];trashResult.error&&parts.push(trashResult.error.message);let stderr=trashResult.stderr?.trim();return stderr&&parts.push(stderr.split(`
|
|
26
|
+
let lines=[];if(lines.push(...this.searchInput.render(width)),lines.push(""),this.filteredSessions.length===0){let emptyMessage;if(this.nameFilter==="named"){let toggleKey=keyText("app.session.toggleNamedFilter");this.showCwd?emptyMessage=` No named sessions found. Press ${toggleKey} to show all.`:emptyMessage=` No named sessions in current folder. Press ${toggleKey} to show all, or ${keyText("tui.input.tab")} to view all.`}else this.showCwd?emptyMessage=" No sessions found":emptyMessage=` N\
|
|
27
|
+
o sessions in current folder. Press ${keyText("tui.input.tab")} to view all.`;return lines.push(theme.fg("muted",truncateToWidth(emptyMessage,width,"\u2026"))),lines}let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredSessions.length-this.maxVisible)),endIndex=Math.min(startIndex+this.maxVisible,this.filteredSessions.length);for(let i=startIndex;i<endIndex;i++){let node=this.filteredSessions[i],session=node.session,isSelected=i===this.selectedIndex,isConfirmingDelete=session.
|
|
28
|
+
path===this.confirmingDeletePath,isCurrent=this.isCurrentSessionPath(session.path),prefix=this.buildTreePrefix(node),hasName=!!session.name,normalizedMessage=(session.name??session.firstMessage).replace(/[\x00-\x1f\x7f]/g," ").trim(),age=formatSessionDate(session.modified),rightPart=`${String(session.messageCount)} ${age}`;this.showCwd&&session.cwd&&(rightPart=`${shortenHomePath(session.cwd)} ${rightPart}`),this.showPath&&(rightPart=`${shortenHomePath(session.path)} ${rightPart}`);let cursor=isSelected?
|
|
29
|
+
theme.fg("accent","\u203A "):" ",prefixWidth=visibleWidth(prefix),rightWidth=visibleWidth(rightPart)+2,availableForMsg=width-2-prefixWidth-rightWidth,truncatedMsg=truncateToWidth(normalizedMessage,Math.max(10,availableForMsg),"\u2026"),messageColor=null;isConfirmingDelete?messageColor="error":isCurrent?messageColor="accent":hasName&&(messageColor="warning");let styledMsg=messageColor?theme.fg(messageColor,truncatedMsg):truncatedMsg;isSelected&&(styledMsg=theme.bold(styledMsg));let leftPart=cursor+
|
|
30
|
+
theme.fg("dim",prefix)+styledMsg,leftWidth=visibleWidth(leftPart),spacing=Math.max(1,width-leftWidth-visibleWidth(rightPart)),styledRight=theme.fg(isConfirmingDelete?"error":"dim",rightPart),line=leftPart+" ".repeat(spacing)+styledRight;isSelected&&(line=theme.bg("selectedBg",line)),lines.push(truncateToWidth(line,width))}if(startIndex>0||endIndex<this.filteredSessions.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredSessions.length})`,scrollInfo=theme.fg("muted",truncateToWidth(
|
|
31
|
+
scrollText,width,""));lines.push(scrollInfo)}return lines}buildTreePrefix(node){if(node.depth===0)return"";let parts=node.ancestorContinues.map(continues=>continues?"\u2502 ":" "),branch=node.isLast?"\u2514\u2500 ":"\u251C\u2500 ";return parts.join("")+branch}handleInput(keyData){let kb=getKeybindings();if(this.confirmingDeletePath!==null){if(kb.matches(keyData,"tui.select.confirm")){let pathToDelete=this.confirmingDeletePath;this.setConfirmingDeletePath(null),this.onDeleteSession?.(pathToDelete);
|
|
32
|
+
return}if(kb.matches(keyData,"tui.select.cancel")){this.setConfirmingDeletePath(null);return}return}if(kb.matches(keyData,"tui.input.tab")){this.onToggleScope&&this.onToggleScope();return}if(kb.matches(keyData,"app.session.toggleSort")){this.onToggleSort?.();return}if(this.keybindings.matches(keyData,"app.session.toggleNamedFilter")){this.onToggleNameFilter?.();return}if(kb.matches(keyData,"app.session.togglePath")){this.showPath=!this.showPath,this.onTogglePath?.(this.showPath);return}if(kb.matches(
|
|
33
|
+
keyData,"app.session.delete")){this.startDeleteConfirmationForSelectedSession();return}if(kb.matches(keyData,"app.session.rename")){let selected=this.filteredSessions[this.selectedIndex];selected&&this.onRenameSession?.(selected.session.path);return}if(kb.matches(keyData,"app.session.deleteNoninvasive")){if(this.searchInput.getValue().length>0){this.handleSearchInput(keyData);return}this.startDeleteConfirmationForSelectedSession();return}if(this.selectionTouched=!0,this.pendingSelectedPath=void 0,
|
|
34
|
+
kb.matches(keyData,"tui.select.up"))this.selectedIndex=Math.max(0,this.selectedIndex-1);else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+1);else if(kb.matches(keyData,"tui.select.pageUp"))this.selectedIndex=Math.max(0,this.selectedIndex-this.maxVisible);else if(kb.matches(keyData,"tui.select.pageDown"))this.selectedIndex=Math.min(this.filteredSessions.length-1,this.selectedIndex+this.maxVisible);else if(kb.matches(keyData,
|
|
35
|
+
"tui.select.confirm")){let selected=this.filteredSessions[this.selectedIndex];selected&&this.onSelect&&this.onSelect(selected.session.path)}else kb.matches(keyData,"tui.select.cancel")?this.onCancel&&this.onCancel():this.handleSearchInput(keyData)}handleSearchInput(keyData){let previousQuery=this.searchInput.getValue();this.searchInput.handleInput(keyData);let query=this.searchInput.getValue();query!==previousQuery&&(this.filterSessions(query),query.trim()&&(this.selectedIndex=0,this.selectionTouched=
|
|
36
|
+
!1,this.pendingSelectedPath=void 0))}};async function deleteSessionFile(sessionPath){let trashArgs=sessionPath.startsWith("-")?["--",sessionPath]:[sessionPath],trashResult=spawnSync("trash",trashArgs,{encoding:"utf-8"}),getTrashErrorHint=()=>{let parts=[];trashResult.error&&parts.push(trashResult.error.message);let stderr=trashResult.stderr?.trim();return stderr&&parts.push(stderr.split(`
|
|
37
37
|
`)[0]??stderr),parts.length===0?null:`trash: ${parts.join(" \xB7 ").slice(0,200)}`};if(trashResult.status===0||!existsSync(sessionPath))return{ok:!0,method:"trash"};try{return await unlink(sessionPath),{ok:!0,method:"unlink"}}catch(err){let unlinkError=err instanceof Error?err.message:String(err),trashErrorHint=getTrashErrorHint();return{ok:!1,method:"unlink",error:trashErrorHint?`${unlinkError} (${trashErrorHint})`:unlinkError}}}var SessionSelectorComponent=class extends Container{get capturesViewportInput(){
|
|
38
38
|
return this.mode!=="rename"}handleInput(data){if(this.mode==="rename"){if(getKeybindings().matches(data,"tui.select.cancel")){this.exitRenameMode();return}this.renameInput.handleInput(data);return}this.sessionList.handleInput(data)}canRename=!0;sessionList;header;keybindings;scope="current";sortMode="threaded";nameFilter="all";currentSessions=null;allSessions=null;currentSessionsLoader;allSessionsLoader;requestRender;renameSession;currentLoad=null;allLoad=null;mode="list";renameInput=new Input;renameTargetPath=null;_focused=!1;get focused(){
|
|
39
39
|
return this._focused}set focused(value){this._focused=value,this.sessionList.focused=value,this.renameInput.focused=value,value&&this.mode==="rename"&&(this.renameInput.focused=!0)}buildBaseLayout(content,options){this.clear(),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder(s=>theme.fg("accent",s))),this.addChild(new Spacer(1)),(options?.showHeader??!0)&&(this.addChild(this.header),this.addChild(new Spacer(1))),this.addChild(content),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder(
|
|
@@ -43,7 +43,7 @@ onCancel=()=>{clearStatusMessage(),this.cancelLoads(),onCancel()},this.sessionLi
|
|
|
43
43
|
this.currentSessions??[]).find(s=>s.path===sessionPath);this.enterRenameMode(sessionPath,session?.name)},this.sessionList.onTogglePath=showPath=>{this.header.setShowPath(showPath),this.requestRender()},this.sessionList.onDeleteConfirmationChange=path=>{this.header.setConfirmingDeletePath(path),this.requestRender()},this.sessionList.onError=msg=>{this.header.setStatusMessage({type:"error",message:msg},3e3),this.requestRender()},this.sessionList.onDeleteSession=async sessionPath=>{let result=await deleteSessionFile(
|
|
44
44
|
sessionPath);if(result.ok){this.currentSessions&&(this.currentSessions=this.currentSessions.filter(s=>s.path!==sessionPath)),this.allSessions&&(this.allSessions=this.allSessions.filter(s=>s.path!==sessionPath));let sessions=this.scope==="all"?this.allSessions??[]:this.currentSessions??[],showCwd=this.scope==="all";this.sessionList.setSessions(sessions,showCwd);let msg=result.method==="trash"?"Session moved to trash":"Session deleted";this.header.setStatusMessage({type:"info",message:msg},2e3),await this.
|
|
45
45
|
refreshSessionsAfterMutation()}else{let errorMessage=result.error??"Unknown error";this.header.setStatusMessage({type:"error",message:`Failed to delete: ${errorMessage}`},3e3)}this.requestRender()},this.loadScope("current")}cancelLoads(){this.currentLoad&&(this.currentLoad.abort(),this.currentLoad=null,this.currentSessions=null),this.allLoad&&(this.allLoad.abort(),this.allLoad=null,this.allSessions=null)}enterRenameMode(sessionPath,currentName){this.mode="rename",this.renameTargetPath=sessionPath,
|
|
46
|
-
this.renameInput.setValue(currentName??""),this.renameInput.focused=!0;let panel=new Container;panel.addChild(new Text(theme.bold("Rename Session"),1,0)),panel.addChild(new Spacer(1)),panel.addChild(this.renameInput),panel.addChild(new Spacer(1)),panel.addChild(new Text(theme.fg("muted",`${keyText("tui.
|
|
46
|
+
this.renameInput.setValue(currentName??""),this.renameInput.focused=!0;let panel=new Container;panel.addChild(new Text(theme.bold("Rename Session"),1,0)),panel.addChild(new Spacer(1)),panel.addChild(this.renameInput),panel.addChild(new Spacer(1)),panel.addChild(new Text(theme.fg("muted",`${keyText("tui.input.submit")} to save \xB7 ${keyText("tui.select.cancel")} to cancel`),1,0)),this.buildBaseLayout(panel,{showHeader:!1}),this.requestRender()}exitRenameMode(){this.mode="list",this.renameTargetPath=
|
|
47
47
|
null,this.buildBaseLayout(this.sessionList),this.requestRender()}async confirmRename(value){let next=value.trim();if(!next)return;let target=this.renameTargetPath;if(!target){this.exitRenameMode();return}let renameSession=this.renameSession;if(!renameSession){this.exitRenameMode();return}try{await renameSession(target,next),await this.refreshSessionsAfterMutation()}finally{this.exitRenameMode()}}async loadScope(scope){if(scope==="current"?this.currentLoad:this.allLoad)return;let showCwd=scope===
|
|
48
48
|
"all",controller=new AbortController;scope==="current"?this.currentLoad=controller:this.allLoad=controller,this.header.setScope(scope),this.header.setLoading(!0),this.requestRender();let isActive=()=>(scope==="current"?this.currentLoad:this.allLoad)===controller,onProgress=(loaded,total,partialSessions)=>{if(isActive()){if(partialSessions){let sessions=[...partialSessions];scope==="current"?this.currentSessions=sessions:this.allSessions=sessions,scope===this.scope&&this.sessionList.setSessions(sessions,
|
|
49
49
|
showCwd,!0)}scope===this.scope&&(this.header.setProgress(loaded,total),this.requestRender())}};try{let sessions=await(scope==="current"?this.currentSessionsLoader(onProgress,controller.signal):this.allSessionsLoader(onProgress,controller.signal));if(!isActive()||(scope==="current"?(this.currentSessions=sessions,this.currentLoad=null):(this.allSessions=sessions,this.allLoad=null),scope!==this.scope))return;this.header.setLoading(!1),this.sessionList.setSessions(sessions,showCwd),this.requestRender()}catch(err){
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{AuthCommandError,getAuthCredential,validateAuthCommandArgs}from"./chunk-OTVHRZ67.js";import{InMemoryCodingAgentModelsStore,ModelRuntime,resolveCliModel}from"./chunk-XGSJX23G.js";import{join}from"node:path";async function checkProviderAuth(args,modelRuntime,options={refresh:!1}){let{provider:cliProvider,model:cliModel}=validateAuthCommandArgs(args,"check"),provider=cliProvider;if(cliModel){let resolved=resolveCliModel({cliProvider,cliModel,modelRuntime});if(resolved.error||!resolved.model)throw new AuthCommandError(resolved.error??`Unable to resolve model "${cliModel}"`);provider=resolved.model.provider}if(!provider)throw new AuthCommandError("Unable to resolve an auth provider");if(modelRuntime.getError())
|
|
3
|
+
return{status:"invalid",provider,reason:"invalid_state"};if(!modelRuntime.getProvider(provider))return{status:"not_ready",provider,reason:"provider_not_found"};try{let auth=await modelRuntime.checkAuth(provider);return auth?options.refresh&&!await modelRuntime.getAuth(provider)?{status:"not_ready",provider,reason:"credentials_not_configured"}:{status:"ready",provider,authType:auth.type}:{status:"not_ready",provider,reason:"credentials_not_configured"}}catch{return{status:"invalid",provider,reason:"\
|
|
4
|
+
invalid_state"}}}async function getProviderCredential(providerId,modelRuntime,options){let credential=await modelRuntime.readStoredCredential(providerId);return!options.refresh&&credential?.type==="oauth"?credential.access:getAuthCredential(await modelRuntime.getAuth(providerId))}async function createAuthCheckModelRuntime(credentials,environment,agentDir){return ModelRuntime.create({credentials,hcode:{environment,agentDir,...agentDir?{networkAllowed:()=>!1}:{}},...agentDir?{modelsPath:join(agentDir,
|
|
5
|
+
"models.json")}:{},modelsStore:new InMemoryCodingAgentModelsStore,allowModelNetwork:!1,refreshOnCreate:!1})}export{checkProviderAuth,getProviderCredential,createAuthCheckModelRuntime};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{getCurrentSystemMessage}from"./chunk-KJ3QRSSY.js";import{uuidv7}from"./chunk-K5EFEIFP.js";import{APP_TITLE,getAgentDir,getSessionsDir,normalizePath,pathsEqual,resolvePath}from"./chunk-CKFLQGJN.js";function readOrientationFromTiff(bytes,tiffStart){if(tiffStart+8>bytes.length)return 1;let le=(bytes[tiffStart]<<8|bytes[tiffStart+1])===18761,read16=pos=>le?bytes[pos]|bytes[pos+1]<<8:bytes[pos]<<8|bytes[pos+1],ifdOffset=(pos=>le?bytes[pos]|bytes[pos+1]<<8|bytes[pos+2]<<16|bytes[pos+3]<<24:(bytes[pos]<<24|bytes[pos+1]<<16|bytes[pos+2]<<8|bytes[pos+3])>>>0)(tiffStart+4),ifdStart=tiffStart+ifdOffset;if(ifdStart+2>bytes.length)return 1;let entryCount=read16(ifdStart);for(let i=0;i<entryCount;i++){
|
|
3
|
+
let entryPos=ifdStart+2+i*12;if(entryPos+12>bytes.length)return 1;if(read16(entryPos)===274){let value=read16(entryPos+8);return value>=1&&value<=8?value:1}}return 1}function findJpegTiffOffset(bytes){let offset=2;for(;offset<bytes.length-1;){if(bytes[offset]!==255)return-1;let marker=bytes[offset+1];if(marker===255){offset++;continue}if(marker===225){if(offset+4>=bytes.length)return-1;let segmentStart=offset+4;if(segmentStart+6>bytes.length)return-1;if(hasExifHeader(bytes,segmentStart))return segmentStart+
|
|
4
|
+
6}if(offset+4>bytes.length)return-1;let length=bytes[offset+2]<<8|bytes[offset+3];offset+=2+length}return-1}function findWebpTiffOffset(bytes){let offset=12;for(;offset+8<=bytes.length;){let chunkId=String.fromCharCode(bytes[offset],bytes[offset+1],bytes[offset+2],bytes[offset+3]),chunkSize=bytes[offset+4]|bytes[offset+5]<<8|bytes[offset+6]<<16|bytes[offset+7]<<24,dataStart=offset+8;if(chunkId==="EXIF")return dataStart+chunkSize>bytes.length?-1:chunkSize>=6&&hasExifHeader(bytes,dataStart)?dataStart+
|
|
5
|
+
6:dataStart;offset=dataStart+chunkSize+chunkSize%2}return-1}function hasExifHeader(bytes,offset){return bytes[offset]===69&&bytes[offset+1]===120&&bytes[offset+2]===105&&bytes[offset+3]===102&&bytes[offset+4]===0&&bytes[offset+5]===0}function getExifOrientation(bytes){let tiffOffset=-1;return bytes.length>=2&&bytes[0]===255&&bytes[1]===216?tiffOffset=findJpegTiffOffset(bytes):bytes.length>=12&&bytes[0]===82&&bytes[1]===73&&bytes[2]===70&&bytes[3]===70&&bytes[8]===87&&bytes[9]===69&&bytes[10]===66&&
|
|
6
|
+
bytes[11]===80&&(tiffOffset=findWebpTiffOffset(bytes)),tiffOffset===-1?1:readOrientationFromTiff(bytes,tiffOffset)}function rotate90(photon,image,dstIndex){let w=image.get_width(),h=image.get_height(),src=image.get_raw_pixels(),dst=new Uint8Array(src.length);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let srcIdx=(y*w+x)*4,dstIdx=dstIndex(x,y,w,h)*4;dst[dstIdx]=src[srcIdx],dst[dstIdx+1]=src[srcIdx+1],dst[dstIdx+2]=src[srcIdx+2],dst[dstIdx+3]=src[srcIdx+3]}return new photon.PhotonImage(dst,h,w)}function applyExifOrientation(photon,image,originalBytes){
|
|
7
|
+
let orientation=getExifOrientation(originalBytes);if(orientation===1)return image;switch(orientation){case 2:return photon.fliph(image),image;case 3:return photon.fliph(image),photon.flipv(image),image;case 4:return photon.flipv(image),image;case 5:{let rotated=rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));return photon.fliph(rotated),rotated}case 6:return rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));case 7:{let rotated=rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);return photon.fliph(rotated),
|
|
8
|
+
rotated}case 8:return rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);default:return image}}import{createRequire}from"module";import*as path from"path";import{fileURLToPath}from"url";var require2=createRequire(import.meta.url),fs=require2("fs"),WASM_FILENAME="photon_rs_bg.wasm",photonModule=null,loadPromise=null;function pathOrNull(file){return typeof file=="string"?file:file instanceof URL?fileURLToPath(file):null}function getFallbackWasmPaths(){let execDir=path.dirname(process.execPath);return[path.join(execDir,WASM_FILENAME),path.join(execDir,"photon",WASM_FILENAME),path.join(process.
|
|
9
|
+
cwd(),WASM_FILENAME)]}function patchPhotonWasmRead(){let originalReadFileSync=fs.readFileSync.bind(fs),fallbackPaths=getFallbackWasmPaths(),mutableFs=fs,patchedReadFileSync=((...args)=>{let[file,options]=args;if(pathOrNull(file)?.endsWith(WASM_FILENAME))try{return originalReadFileSync(...args)}catch(error){let err=error;if(err?.code&&err.code!=="ENOENT")throw error;for(let fallbackPath of fallbackPaths)if(fs.existsSync(fallbackPath))return options===void 0?originalReadFileSync(fallbackPath):originalReadFileSync(
|
|
10
|
+
fallbackPath,options);throw error}return originalReadFileSync(...args)});try{mutableFs.readFileSync=patchedReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:patchedReadFileSync,writable:!0,configurable:!0})}return()=>{try{mutableFs.readFileSync=originalReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:originalReadFileSync,writable:!0,configurable:!0})}}}async function loadPhoton(){return photonModule||loadPromise||(loadPromise=(async()=>{let restoreReadFileSync=patchPhotonWasmRead();
|
|
11
|
+
try{return photonModule=await import("@silvia-odwyer/photon-node"),photonModule}catch{return photonModule=null,photonModule}finally{restoreReadFileSync()}})(),loadPromise)}var IMAGE_RESIZE_WORKER_RESPONSE_TYPE="pi:image-resize-response",DEFAULT_MAX_BYTES=4.5*1024*1024,DEFAULT_OPTIONS={maxWidth:2e3,maxHeight:2e3,maxBytes:DEFAULT_MAX_BYTES,jpegQuality:80};function encodeCandidate(buffer,mimeType){let data=Buffer.from(buffer).toString("base64");return{data,encodedSize:Buffer.byteLength(data,"utf-8"),mimeType}}async function resizeImageInProcess(inputBytes,mimeType,options){let opts={...DEFAULT_OPTIONS,...options},inputBase64Size=Math.ceil(inputBytes.byteLength/3)*4,photon=await loadPhoton();
|
|
12
|
+
if(!photon)return null;let image;try{let tryEncodings=function(width,height,jpegQualities){let resized=photon.resize(image,width,height,photon.SamplingFilter.Lanczos3);try{let candidates=[encodeCandidate(resized.get_bytes(),"image/png")];for(let quality of jpegQualities)candidates.push(encodeCandidate(resized.get_bytes_jpeg(quality),"image/jpeg"));return candidates}finally{resized.free()}},rawImage=photon.PhotonImage.new_from_byteslice(inputBytes);image=applyExifOrientation(photon,rawImage,inputBytes),
|
|
13
|
+
image!==rawImage&&rawImage.free();let originalWidth=image.get_width(),originalHeight=image.get_height(),format=mimeType.split("/")[1]??"png";if(originalWidth<=opts.maxWidth&&originalHeight<=opts.maxHeight&&inputBase64Size<opts.maxBytes)return{data:Buffer.from(inputBytes).toString("base64"),mimeType:mimeType||`image/${format}`,originalWidth,originalHeight,width:originalWidth,height:originalHeight,wasResized:!1};let targetWidth=originalWidth,targetHeight=originalHeight;targetWidth>opts.maxWidth&&(targetHeight=
|
|
14
|
+
Math.max(1,Math.round(targetHeight*opts.maxWidth/targetWidth)),targetWidth=opts.maxWidth),targetHeight>opts.maxHeight&&(targetWidth=Math.max(1,Math.round(targetWidth*opts.maxHeight/targetHeight)),targetHeight=opts.maxHeight);let qualitySteps=Array.from(new Set([opts.jpegQuality,85,70,55,40])),currentWidth=targetWidth,currentHeight=targetHeight;for(;;){let[png,jpeg,...lowerQualityJpegs]=tryEncodings(currentWidth,currentHeight,qualitySteps),preferred=jpeg&&jpeg.encodedSize<png.encodedSize?[jpeg,png]:
|
|
15
|
+
[png,jpeg];for(let candidate of[...preferred,...lowerQualityJpegs])if(candidate&&candidate.encodedSize<opts.maxBytes)return{data:candidate.data,mimeType:candidate.mimeType,originalWidth,originalHeight,width:currentWidth,height:currentHeight,wasResized:!0};if(currentWidth===1&¤tHeight===1)break;let nextWidth=currentWidth===1?1:Math.max(1,Math.floor(currentWidth*.75)),nextHeight=currentHeight===1?1:Math.max(1,Math.floor(currentHeight*.75));if(nextWidth===currentWidth&&nextHeight===currentHeight)
|
|
16
|
+
break;currentWidth=nextWidth,currentHeight=nextHeight}return null}catch{return null}finally{image&&image.free()}}function toTransferableBytes(input){return new Uint8Array(input)}function isResizeImageWorkerResponse(value){return value!==null&&typeof value=="object"&&"type"in value&&value.type===IMAGE_RESIZE_WORKER_RESPONSE_TYPE}function createResizeWorker(workerSpecifier){return new(process.getBuiltinModule("node:worker_threads")).Worker(workerSpecifier)}async function resizeImageInWorker(workerSpecifier,inputBytes,mimeType,options){let worker=createResizeWorker(workerSpecifier);try{let inputBytesForWorker=toTransferableBytes(
|
|
17
|
+
inputBytes);return await new Promise((resolve2,reject)=>{let settled=!1,settle=result=>{settled||(settled=!0,resolve2(result))},fail=error=>{settled||(settled=!0,reject(error))};worker.on("message",message=>{isResizeImageWorkerResponse(message)&&("error"in message?fail(new Error(message.error)):settle(message.result))}),worker.once("error",fail),worker.once("exit",code=>{settled||fail(new Error(`Image resize worker exited with code ${code}`))}),worker.postMessage({inputBytes:inputBytesForWorker,
|
|
18
|
+
mimeType,options},[inputBytesForWorker.buffer])})}finally{await worker.terminate().catch(()=>{})}}async function resizeImage(inputBytes,mimeType,options){let isTypeScriptRuntime=import.meta.url.endsWith(".ts"),workerUrl=new URL(isTypeScriptRuntime?"./image-resize-worker.ts":"./image-resize-worker.js",import.meta.url);if(typeof process.versions.bun=="string")try{return await resizeImageInWorker("./src/utils/image-resize-worker.ts",inputBytes,mimeType,options)}catch{}try{return await resizeImageInWorker(
|
|
19
|
+
workerUrl,inputBytes,mimeType,options)}catch{return resizeImageInProcess(inputBytes,mimeType,options)}}function formatDimensionNote(result){if(!result.wasResized)return;let scale=result.originalWidth/result.width;return`[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
|
|
20
|
+
|
|
21
|
+
<summary>
|
|
22
|
+
`,COMPACTION_SUMMARY_SUFFIX=`
|
|
23
|
+
</summary>`,BRANCH_SUMMARY_PREFIX=`The following is a summary of a branch that this conversation came back from:
|
|
24
|
+
|
|
25
|
+
<summary>
|
|
26
|
+
`,BRANCH_SUMMARY_SUFFIX="</summary>";function bashExecutionToText(msg){let text=`Ran \`${msg.command}\`
|
|
27
|
+
`;return msg.output?text+=`\`\`\`
|
|
28
|
+
${msg.output}
|
|
29
|
+
\`\`\``:text+="(no output)",msg.cancelled?text+=`
|
|
30
|
+
|
|
31
|
+
(command cancelled)`:msg.exitCode!==null&&msg.exitCode!==void 0&&msg.exitCode!==0&&(text+=`
|
|
32
|
+
|
|
33
|
+
Command exited with code ${msg.exitCode}`),msg.truncated&&(text+=`
|
|
34
|
+
|
|
35
|
+
[${bashTruncationNote(msg)}]`),text}function bashTruncationNote(msg){return msg.fullOutputPath?`Output truncated. Full output: ${msg.fullOutputPath}`:msg.fullOutputError?`Output truncated. Could not save the full output: ${msg.fullOutputError}`:"Output truncated"}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp){return{role:"compa\
|
|
36
|
+
ctionSummary",summary,tokensBefore,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){return messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp};case"custom":return{role:"user",content:typeof m.
|
|
37
|
+
content=="string"?[{type:"text",text:m.content}]:m.content,timestamp:m.timestamp};case"branchSummary":return{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp};case"compactionSummary":return{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp};case"system":case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==
|
|
38
|
+
void 0)}import{randomUUID}from"crypto";import{closeSync,existsSync,fchmodSync,fstatSync,fsyncSync,mkdirSync,openSync,readdirSync,readSync,renameSync,statSync,writeFileSync,writeSync}from"fs";import{open,readdir,stat}from"fs/promises";import{basename,join as join2,resolve}from"path";import{StringDecoder}from"string_decoder";var CURRENT_SESSION_VERSION=3;function includeSummaryUsageEntries(branch,getEntry){let included=new Set(branch.map(entry=>entry.id));return branch.flatMap(entry=>{let owners=[];if(entry.type==="compaction"||entry.type==="branch_summary")for(let id of entry.usageEntryIds??[]){if(included.has(id))continue;let owner=getEntry(id);owner?.type==="usage"&&(included.add(id),owners.push(owner))}return[...owners,entry]})}function createSessionId(){return uuidv7()}function assertValidSessionId(id){if(!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.
|
|
39
|
+
test(id))throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character")}function generateId(byId){for(let i=0;i<100;i++){let id=randomUUID().slice(0,8);if(!byId.has(id))return id}return randomUUID()}function migrateV1ToV2(entries){let ids=new Set,prevId=null;for(let entry of entries){if(entry.type==="session"){entry.version=2;continue}if(entry.id=generateId(ids),entry.parentId=prevId,prevId=entry.id,entry.
|
|
40
|
+
type==="compaction"){let comp=entry;if(typeof comp.firstKeptEntryIndex=="number"){let targetEntry=entries[comp.firstKeptEntryIndex];targetEntry&&targetEntry.type!=="session"&&(comp.firstKeptEntryId=targetEntry.id),delete comp.firstKeptEntryIndex}}}}function migrateV2ToV3(entries){for(let entry of entries){if(entry.type==="session"){entry.version=3;continue}if(entry.type==="message"){let msgEntry=entry;msgEntry.message&&msgEntry.message.role==="hookMessage"&&(msgEntry.message.role="custom")}}}function migrateToCurrentVersion(entries){
|
|
41
|
+
let version=entries.find(e=>e.type==="session")?.version??1;return version>=CURRENT_SESSION_VERSION?!1:(version<2&&migrateV1ToV2(entries),version<3&&migrateV2ToV3(entries),!0)}function migrateSessionEntries(entries){migrateToCurrentVersion(entries)}function parseSessionEntries(content){let entries=[],lines=content.trim().split(`
|
|
42
|
+
`);for(let line of lines)if(line.trim())try{let entry=JSON.parse(line);entries.push(entry)}catch{}return entries}function relinkOrphanedEntries(entries,byId){let earlier=new Set;for(let entry of entries)if(entry.type!=="session"){if(entry.parentId&&byId.has(entry.parentId)&&!earlier.has(entry.parentId))return 0;earlier.add(entry.id)}let previousId,relinked=0;for(let entry of entries)entry.type!=="session"&&(entry.parentId&&previousId!==void 0&&!byId.has(entry.parentId)&&(entry.parentId=previousId,
|
|
43
|
+
relinked++),previousId=entry.id);return relinked}function getLatestCompactionEntry(entries){for(let i=entries.length-1;i>=0;i--)if(entries[i].type==="compaction")return entries[i];return null}function buildEntryIndex(entries,byId){if(byId)return byId;let index=new Map;for(let entry of entries)index.set(entry.id,entry);return index}function buildSessionPath(entries,leafId,byId){let index=buildEntryIndex(entries,byId),leaf;return leafId===null?[]:(leafId&&(leaf=index.get(leafId)),leaf??=entries[entries.
|
|
44
|
+
length-1],leaf?walkToRoot(leaf,index):[])}function walkToRoot(leaf,byId){let path2=[],current=leaf;for(;current;){if(path2.length>byId.size)return walkToRootCuttingCycle(leaf,byId);path2.push(current),current=current.parentId?byId.get(current.parentId):void 0}return path2.reverse()}function walkToRootCuttingCycle(leaf,byId){let path2=[],seen=new Set,current=leaf;for(;current&&!seen.has(current.id);)seen.add(current.id),path2.push(current),current=current.parentId?byId.get(current.parentId):void 0;
|
|
45
|
+
return path2.reverse()}function getSessionContextSettings(path2){let settings={thinkingLevel:"off",model:null};for(let entry of path2)applySessionContextSetting(settings,entry);return settings}function applySessionContextSetting(settings,entry){entry.type==="thinking_level_change"?settings.thinkingLevel=entry.thinkingLevel:entry.type==="model_change"?settings.model={provider:entry.provider,modelId:entry.modelId}:entry.type==="message"&&entry.message.role==="assistant"&&(settings.model={provider:entry.
|
|
46
|
+
message.provider,modelId:entry.message.model})}function sessionEntryToContextMessages(entry){if(entry.type==="message"){let message=entry.message;return message.role==="system"&&message.content==null?[{...message,content:""}]:(message.role==="user"||message.role==="assistant"||message.role==="toolResult")&&message.content==null?[{...message,content:[]}]:[message]}if(entry.type==="custom_message")return[createCustomMessage(entry.customType,entry.content??[],entry.display,entry.details,entry.timestamp)];
|
|
47
|
+
if(entry.type==="branch_summary"&&entry.summary)return[createBranchSummaryMessage(entry.summary,entry.fromId,entry.timestamp)];if(entry.type==="compaction"){let summary=createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp);return entry.systemMessage?[entry.systemMessage,summary]:[summary]}return[]}function buildContextEntries(entries,leafId,byId){let denied=getControlDeniedEntryIds(entries),path2=buildSessionPath(entries,leafId,byId).map(entry=>omitControlDeniedContent(
|
|
48
|
+
entry,denied)),compaction=null;for(let entry of path2)entry.type==="compaction"&&(compaction=entry);if(!compaction)return path2;let compactionIdx=path2.findIndex(entry=>entry.id===compaction.id);if(compactionIdx<0)return path2;let contextEntries=[compaction],foundFirstKept=!1;for(let i=0;i<compactionIdx;i++){let entry=path2[i];entry.id===compaction.firstKeptEntryId&&(foundFirstKept=!0),foundFirstKept&&!(entry.type==="message"&&entry.message.role==="system")&&contextEntries.push(entry)}for(let i=compactionIdx+
|
|
49
|
+
1;i<path2.length;i++)contextEntries.push(path2[i]);return contextEntries}function projectContextEntry(entry,edit){if(entry.type==="message"&&entry.controlDenied)return[];let messages=sessionEntryToContextMessages(entry);if(!edit)return messages;let replacement=edit.replacement;return replacement===null?[]:messages.map(message=>{if(message.role!=="user"&&message.role!=="assistant"&&message.role!=="toolResult"&&message.role!=="custom")return message;let content=(message.role==="assistant"||message.
|
|
50
|
+
role==="toolResult")&&typeof replacement.content=="string"?[{type:"text",text:replacement.content}]:replacement.content;return{...message,content}})}function getControlDeniedEntryIds(entries){let denied=new Set;for(let entry of entries)entry.type==="context_edit"&&entry.reason==="control-denied"&&entry.replacement===null&&denied.add(entry.targetId),entry.type==="message"&&entry.controlDenied&&denied.add(entry.id);return denied}function omitControlDeniedContent(entry,denied){return entry.type==="\
|
|
51
|
+
context_edit"&&denied.has(entry.targetId)&&entry.replacement!==null?{...entry,replacement:null}:entry.type!=="message"||!denied.has(entry.id)?entry:{...entry,controlDenied:!0,message:{...entry.message,content:[]}}}function projectContextEntries(contextEntries){let edits=new Map;for(let entry of contextEntries)entry.type==="context_edit"&&edits.set(entry.targetId,entry);return contextEntries.map((sourceEntry,index)=>({sourceEntry,messages:sourceEntry.type==="compaction"&&index>0?[]:projectContextEntry(
|
|
52
|
+
sourceEntry,edits.get(sourceEntry.id))}))}function buildSessionProjection(entries,leafId,byId){let path2=buildSessionPath(entries,leafId,byId),{thinkingLevel,model}=getSessionContextSettings(path2),projectedEntries=projectContextEntries(buildContextEntries(entries,leafId,byId));return{entries:projectedEntries,messages:projectedEntries.flatMap(entry=>entry.messages),thinkingLevel,model}}function buildSessionContext(entries,leafId,byId){let{messages,thinkingLevel,model}=buildSessionProjection(entries,
|
|
53
|
+
leafId,byId);return{messages,thinkingLevel,model}}function openSessionFile(path2,flags){let fd=openSync(path2,flags,384);try{if(process.platform!=="win32"&&flags!=="wx"){let mode=fstatSync(fd).mode;(mode&63)!==0&&fchmodSync(fd,mode&448)}return fd}catch(error){throw closeSync(fd),error}}function getDefaultSessionDirPath(cwd,agentDir=getAgentDir()){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),safePath=`--${resolvedCwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return join2(
|
|
54
|
+
resolvedAgentDir,"sessions",safePath)}function getDefaultSessionDir(cwd,agentDir=getAgentDir()){let sessionDir=getDefaultSessionDirPath(cwd,agentDir);return existsSync(sessionDir)||mkdirSync(sessionDir,{recursive:!0,mode:448}),sessionDir}var SESSION_READ_BUFFER_SIZE=1024*1024,SESSION_HEADER_READ_BUFFER_SIZE=4096,MAX_SESSION_HEADER_SCAN_BYTES=1024*1024,SessionHeaderScanLimitError=class extends Error{constructor(filePath){super(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan lim\
|
|
55
|
+
it: ${filePath}`),this.name="SessionHeaderScanLimitError"}};function parseSessionEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function isSessionRecord(parsed,needsId){let value=parsed;return typeof value!="object"||value===null||typeof value.type!="string"?!1:!needsId||parsed.type==="session"||typeof parsed.id=="string"}function headerRequiresEntryIds(first){return first.type==="session"&&(first.version??1)>=2}function loadEntriesFromFile(filePath){let resolvedFilePath=normalizePath(
|
|
56
|
+
filePath);if(!existsSync(resolvedFilePath))return[];let entries=[],entriesHaveIds=!1,consume=line=>{let entry=parseSessionEntryLine(line);entry&&(entries.length===0?(entriesHaveIds=headerRequiresEntryIds(entry),entries.push(entry)):isSessionRecord(entry,entriesHaveIds)&&entries.push(entry))},pending="",fd=openSync(resolvedFilePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE),lineChunks=[];for(;;){let bytesRead=readSync(fd,buffer,0,buffer.length,
|
|
57
|
+
null);if(bytesRead===0)break;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
|
|
58
|
+
`,lineStart);for(;newlineIndex!==-1;)lineChunks.push(chunk.slice(lineStart,newlineIndex)),consume(lineChunks.join("")),lineChunks.length=0,lineStart=newlineIndex+1,newlineIndex=chunk.indexOf(`
|
|
59
|
+
`,lineStart);lineStart<chunk.length&&lineChunks.push(chunk.slice(lineStart))}lineChunks.push(decoder.end()),pending=lineChunks.join(""),consume(pending)}finally{closeSync(fd)}if(entries.length===0)return entries;let header=entries[0];if(header.type!=="session"||typeof header.id!="string")return[];if(pending){let fd2=openSessionFile(resolvedFilePath,"a");try{writeFileSync(fd2,`
|
|
60
|
+
`)}finally{closeSync(fd2)}}return entries}function parseSessionHeaderCandidate(line){if(!line.trim())return;let entry=parseSessionEntryLine(line);if(entry)return entry.type!=="session"||typeof entry.id!="string"?null:entry}function readSessionHeader(filePath){let fd=openSync(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE),lineChunks=[],scannedBytes=0;for(;scannedBytes<MAX_SESSION_HEADER_SCAN_BYTES;){let readLength=Math.min(buffer.
|
|
61
|
+
length,MAX_SESSION_HEADER_SCAN_BYTES-scannedBytes),bytesRead=readSync(fd,buffer,0,readLength,null);if(bytesRead===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;scannedBytes+=bytesRead;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
|
|
62
|
+
`,lineStart);for(;newlineIndex!==-1;){lineChunks.push(chunk.slice(lineStart,newlineIndex));let header=parseSessionHeaderCandidate(lineChunks.join(""));if(header!==void 0)return header;lineChunks.length=0,lineStart=newlineIndex+1,newlineIndex=chunk.indexOf(`
|
|
63
|
+
`,lineStart)}lineChunks.push(chunk.slice(lineStart))}let probe=Buffer.allocUnsafe(1);if(readSync(fd,probe,0,probe.length,null)===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;throw new SessionHeaderScanLimitError(filePath)}finally{closeSync(fd)}}function readSessionHeaderForDiscovery(filePath){try{return readSessionHeader(filePath)}catch{return null}}function getSessionHeaderCwd(header){let cwd=header.cwd;return typeof cwd=="string"?cwd:void 0}function sessionCwdMatches(cwd,resolvedCwd){
|
|
64
|
+
return cwd!==void 0&&cwd!==""&&pathsEqual(resolvePath(cwd),resolvedCwd)}function findMostRecentSession(sessionDir,cwd){let resolvedSessionDir=normalizePath(sessionDir),resolvedCwd=cwd?resolvePath(cwd):void 0;try{let files=readdirSync(resolvedSessionDir).filter(file=>file.endsWith(".jsonl")).map(file=>join2(resolvedSessionDir,file)).flatMap(path2=>{try{return[{path:path2,mtime:statSync(path2).mtimeMs}]}catch{return[]}}).sort((a,b)=>b.mtime-a.mtime);for(let{path:path2}of files){let header=readSessionHeaderForDiscovery(
|
|
65
|
+
path2);if(header&&(!resolvedCwd||sessionCwdMatches(getSessionHeaderCwd(header),resolvedCwd)))return path2}return null}catch{return null}}function isMessageWithContent(message){return typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function getMessageActivityTime(entry){let message=entry.message;if(!isMessageWithContent(
|
|
66
|
+
message)||message.role!=="user"&&message.role!=="assistant")return;let msgTimestamp=message.timestamp;if(typeof msgTimestamp=="number")return msgTimestamp;let t=new Date(entry.timestamp).getTime();return Number.isNaN(t)?void 0:t}var LINE_HEAD_BYTES=256,MESSAGE_LINE_HEAD=/^\{"type":"message","id":"[^"\\]*","parentId":(?:null|"[^"\\]*"),"timestamp":"[^"\\]*","message":\{"role":"([^"\\]*)"/;function classifySessionLine(buffer,start,end){let head=buffer.toString("latin1",start,Math.min(end,start+LINE_HEAD_BYTES));
|
|
67
|
+
if(!head.startsWith('{"type":"'))return"parse";let typeEnd=head.indexOf('"',9);if(typeEnd===-1)return"parse";let type=head.slice(9,typeEnd);if(type==="session_info"||type==="context_edit"||type.includes("\\"))return"parse";if(type!=="message")return"skip";let role=MESSAGE_LINE_HEAD.exec(head)?.[1];return role===void 0||role==="user"||role==="assistant"?"parse":end-start>=2&&buffer[end-1]===125&&buffer[end-2]===125?"count":"parse"}async function forEachLineOfFile(filePath,signal,onLine){signal?.throwIfAborted();
|
|
68
|
+
let file=await open(filePath,"r");try{let chunk=Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE),carry=[],skipLineFeed=!1,emit=(buffer,start,end)=>{if(carry.length===0)return onLine(buffer,start,end);let line=Buffer.concat([...carry,buffer.subarray(start,end)]);return carry=[],onLine(line,0,line.length)};for(;;){signal?.throwIfAborted();let{bytesRead}=await file.read(chunk,0,chunk.length,null);if(bytesRead===0)break;let buffer=chunk.subarray(0,bytesRead),pos=0;skipLineFeed&&(skipLineFeed=!1,buffer[0]===
|
|
69
|
+
10&&(pos=1));let nextLineFeed=buffer.indexOf(10,pos),nextCarriageReturn=buffer.indexOf(13,pos);for(;;){nextLineFeed!==-1&&nextLineFeed<pos&&(nextLineFeed=buffer.indexOf(10,pos)),nextCarriageReturn!==-1&&nextCarriageReturn<pos&&(nextCarriageReturn=buffer.indexOf(13,pos));let lineEnd=nextCarriageReturn===-1?nextLineFeed:nextLineFeed===-1?nextCarriageReturn:Math.min(nextLineFeed,nextCarriageReturn);if(lineEnd===-1)break;if(!emit(buffer,pos,lineEnd))return;pos=lineEnd+1,lineEnd===nextCarriageReturn&&
|
|
70
|
+
(pos===bytesRead?skipLineFeed=!0:buffer[pos]===10&&pos++)}pos<bytesRead&&carry.push(Buffer.from(buffer.subarray(pos)))}if(carry.length>0){let line=Buffer.concat(carry);carry=[],onLine(line,0,line.length)}}finally{await file.close()}}async function buildSessionInfo(filePath,signal,fileStats){try{let stats=fileStats??await stat(filePath),header=null,messageCount=0,allMessages=[],denialEntries=[],name,lastActivityTime,entriesHaveIds=!1;await forEachLineOfFile(filePath,signal,(buffer,start,end)=>{if(header){
|
|
71
|
+
let kind=classifySessionLine(buffer,start,end);if(kind==="skip")return!0;if(kind==="count")return messageCount++,!0}let entry=parseSessionEntryLine(buffer.toString("utf8",start,end));if(!entry)return!0;if(!header)return entry.type!=="session"?!1:(header=entry,entriesHaveIds=headerRequiresEntryIds(entry),!0);if(!isSessionRecord(entry,entriesHaveIds)||((entry.type==="context_edit"&&entry.reason==="control-denied"&&entry.replacement===null||entry.type==="message"&&entry.controlDenied)&&denialEntries.
|
|
72
|
+
push(entry),entry.type==="session_info"&&(name=entry.name?.trim()||void 0),entry.type!=="message"))return!0;messageCount++;let activityTime=getMessageActivityTime(entry);typeof activityTime=="number"&&(lastActivityTime=Math.max(lastActivityTime??0,activityTime));let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return!0;let textContent=extractTextContent(message);return textContent&&allMessages.push({id:entry.id,role:message.role,text:textContent}),
|
|
73
|
+
!0});let sessionHeader=header;if(!sessionHeader)return null;let denied=getControlDeniedEntryIds(denialEntries),visibleMessages=allMessages.filter(message=>!denied.has(message.id)),firstMessage=visibleMessages.find(message=>message.role==="user")?.text,cwd=typeof sessionHeader.cwd=="string"?sessionHeader.cwd:"",parentSessionPath=sessionHeader.parentSession,headerTime=typeof sessionHeader.timestamp=="string"?new Date(sessionHeader.timestamp).getTime():NaN,modified=typeof lastActivityTime=="number"&&
|
|
74
|
+
lastActivityTime>0?new Date(lastActivityTime):Number.isNaN(headerTime)?stats.mtime:new Date(headerTime);return{path:filePath,id:sessionHeader.id,cwd,name,parentSessionPath,created:new Date(sessionHeader.timestamp),modified,messageCount,firstMessage:firstMessage||"(no messages)",allMessagesText:visibleMessages.map(message=>message.text).join(" ")}}catch{return signal?.throwIfAborted(),null}}var MAX_CONCURRENT_SESSION_INFO_LOADS=10,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS=64,CURRENT_SESSION_LIST_PUBLISH_INTERVAL=10,
|
|
75
|
+
ALL_SESSION_LIST_PUBLISH_INTERVAL=100;async function mapWithConcurrency(items,limit,map,signal){let results=new Array(items.length),nextIndex=0,worker=async()=>{for(;nextIndex<items.length;){signal?.throwIfAborted();let index=nextIndex++;results[index]=await map(items[index],index)}};return await Promise.all(Array.from({length:Math.min(limit,items.length)},()=>worker())),results}function sortSessionInfos(sessions){return sessions.sort((a,b)=>b.modified.getTime()-a.modified.getTime())}async function buildSessionInfosWithConcurrency(files,onLoaded,signal){
|
|
76
|
+
let results=await mapWithConcurrency(files,MAX_CONCURRENT_SESSION_INFO_LOADS,async(file,index)=>{let info=await buildSessionInfo(file.path,signal,file.stats);return onLoaded(info,index),info},signal);return signal?.throwIfAborted(),results}async function listSessionsFromDir(dir,onProgress,signal){if(signal?.throwIfAborted(),!existsSync(dir))return[];try{let files=(await readdir(dir)).filter(file=>file.endsWith(".jsonl")).sort((a,b)=>b.localeCompare(a)).map(file=>({path:join2(dir,file)})),total=files.
|
|
77
|
+
length,partialSessions=[],loaded=0;return(await buildSessionInfosWithConcurrency(files,info=>{loaded++,info&&partialSessions.push(info);let publishPartial=loaded===1||loaded%CURRENT_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===files.length;onProgress?.(loaded,total,publishPartial?sortSessionInfos([...partialSessions]):void 0)},signal)).filter(info=>info!==null)}catch{return signal?.throwIfAborted(),[]}}var APPEND_FILE_IDLE_MS=1e3;function endPartialLine(fd,size){if(size===0)return;let last=Buffer.
|
|
78
|
+
alloc(1);readSync(fd,last,0,1,size-1)===1&&last[0]!==10&&writeLine(fd,`
|
|
79
|
+
`)}function writeLine(fd,line){let bytes=Buffer.from(line);for(let offset=0;offset<bytes.length;){let written=writeSync(fd,bytes,offset,bytes.length-offset);if(written===0)throw new Error("Session file write made no progress");offset+=written}}var SessionAppendFile=class{path;fd;dev;ino;lastAppend=0;timer;closed=!1;constructor(path2){this.path=path2,this.fd=openSessionFile(path2,"a+");try{let stats=fstatSync(this.fd);endPartialLine(this.fd,stats.size),this.dev=stats.dev,this.ino=stats.ino}catch(error){
|
|
80
|
+
throw closeSync(this.fd),error}}isFor(path2){if(this.closed||path2!==this.path)return!1;let stats=statSync(path2,{throwIfNoEntry:!1});return stats!==void 0&&stats.ino===this.ino&&stats.dev===this.dev}append(line){writeLine(this.fd,line),this.lastAppend=performance.now(),this.timer||this.scheduleClose(APPEND_FILE_IDLE_MS)}close(){if(!this.closed){this.closed=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0;try{closeSync(this.fd)}catch{}}}scheduleClose(delay){this.timer=setTimeout(()=>{this.
|
|
81
|
+
timer=void 0;let idle=performance.now()-this.lastAppend;idle>=APPEND_FILE_IDLE_MS?this.close():this.scheduleClose(APPEND_FILE_IDLE_MS-idle)},delay),this.timer.unref()}},SessionManager=class _SessionManager{sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;fileEntries=[];byId=new Map;controlDeniedEntryIds=new Set;labelsById=new Map;labelTimestampsById=new Map;leafId=null;linksMayCycle=!1;leafPath;projection;projectionRevision=0;latestSessionInfo;appendFile;constructor(cwd,sessionDir,sessionFile,persist,newSessionOptions,preloadedFileEntries){
|
|
82
|
+
this.cwd=resolvePath(cwd),this.sessionDir=normalizePath(sessionDir),this.persist=persist,persist&&this.sessionDir&&!existsSync(this.sessionDir)&&mkdirSync(this.sessionDir,{recursive:!0,mode:448}),sessionFile?this._setSessionFile(sessionFile,preloadedFileEntries):preloadedFileEntries?.length?this._loadEntries(preloadedFileEntries,newSessionOptions):this.newSession(newSessionOptions)}setSessionFile(sessionFile){this._setSessionFile(sessionFile)}_setSessionFile(sessionFile,preloadedFileEntries){if(this.
|
|
83
|
+
_closeAppendFile(),this.sessionFile=resolvePath(sessionFile),existsSync(this.sessionFile)){let entries=preloadedFileEntries??loadEntriesFromFile(this.sessionFile);if(entries.length===0){let explicitPath=this.sessionFile;if(statSync(explicitPath).size>0)throw new Error(`Session file is not a valid ${APP_TITLE} session: ${explicitPath}`);this.newSession(),this.sessionFile=explicitPath,this._rewriteFile(),this.flushed=!0;return}let relinked=this._loadEntries(entries)?relinkOrphanedEntries(this.fileEntries,
|
|
84
|
+
this.byId):0;relinked>0&&console.warn(`Warning: session file ${this.sessionFile} has damaged lines; relinked ${relinked} ${relinked===1?"entry":"entries"} whose parent was lost.`),this.flushed=!0}else{let explicitPath=this.sessionFile;this.newSession(),this.sessionFile=explicitPath}}newSession(options){options?.id!==void 0&&assertValidSessionId(options.id),this.sessionId=options?.id??createSessionId();let timestamp=new Date().toISOString(),header={type:"session",version:CURRENT_SESSION_VERSION,id:this.
|
|
85
|
+
sessionId,timestamp,cwd:this.cwd,parentSession:options?.parentSession};if(this._closeAppendFile(),this.fileEntries=[header],this.leafPath=void 0,this.projection=void 0,this.latestSessionInfo=void 0,this.byId.clear(),this.controlDeniedEntryIds.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.linksMayCycle=!1,this.flushed=!1,this.persist){let fileTimestamp=timestamp.replace(/[:.]/g,"-");this.sessionFile=join2(this.getSessionDir(),`${fileTimestamp}_${this.sessionId}\
|
|
86
|
+
.jsonl`)}return this.sessionFile}_loadEntries(entries,options){let header=entries.find(e=>e.type==="session");return header?(this.fileEntries=entries,this.sessionId=header.id,migrateToCurrentVersion(this.fileEntries)&&this._rewriteFile()):(this.newSession(options),this.fileEntries=this.fileEntries.concat(entries)),this._buildIndex()}_buildIndex(){this.leafPath=void 0,this.projection=void 0,this.latestSessionInfo=void 0,this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.
|
|
87
|
+
leafId=null,this.controlDeniedEntryIds=getControlDeniedEntryIds(this.fileEntries.filter(entry=>entry.type!=="session"));let unlinked=!1;for(let entry of this.fileEntries){if(entry.type==="session")continue;let parentId=entry.parentId;parentId&&parentId!==this.leafId&&!this.byId.has(parentId)&&(unlinked=!0),this.byId.set(entry.id,entry),this.leafId=entry.id,entry.type==="session_info"&&(this.latestSessionInfo=entry),entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),
|
|
88
|
+
this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId)))}return this.linksMayCycle=unlinked||this.byId.size+1!==this.fileEntries.length,unlinked}_rewriteFile(){if(!this.persist||!this.sessionFile)return;let tmpPath=`${this.sessionFile}.${process.pid}.tmp`,fd=openSessionFile(tmpPath,"w");try{for(let entry of this.fileEntries)writeFileSync(fd,`${JSON.stringify(entry)}
|
|
89
|
+
`);fsyncSync(fd)}finally{closeSync(fd)}renameSync(tmpPath,this.sessionFile)}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return pathsEqual(this.sessionDir,getDefaultSessionDirPath(this.cwd))}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_hasConversation(){return this.fileEntries.some(e=>e.type==="message"||e.type==="usage")}_persist(entry){if(!(!this.persist||!this.sessionFile))if(this.flushed)
|
|
90
|
+
this._appendLine(this.sessionFile,`${JSON.stringify(entry)}
|
|
91
|
+
`);else{if(!this._hasConversation())return;this._flushAll()}}_appendLine(path2,line){if(process.platform==="win32"){let fd=openSessionFile(path2,"a+");try{endPartialLine(fd,fstatSync(fd).size),writeLine(fd,line)}finally{closeSync(fd)}return}this.appendFile?.isFor(path2)||(this._closeAppendFile(),this.appendFile=new SessionAppendFile(path2));try{this.appendFile.append(line)}catch(error){throw this._closeAppendFile(),error}}_closeAppendFile(){this.appendFile?.close(),this.appendFile=void 0}_flushAll(){
|
|
92
|
+
if(!this.persist||!this.sessionFile)return;let fd=openSessionFile(this.sessionFile,"wx");try{for(let e of this.fileEntries)writeFileSync(fd,`${JSON.stringify(e)}
|
|
93
|
+
`)}finally{closeSync(fd)}this.flushed=!0}flush(){this._closeAppendFile(),!(!this.persist||!this.sessionFile||this.flushed)&&this.fileEntries.some(e=>e.type!=="session")&&this._flushAll()}_appendEntry(entry){let previousLeafId=this.leafId;this.fileEntries.push(entry),this.byId.set(entry.id,entry),entry.type==="context_edit"&&entry.reason==="control-denied"&&entry.replacement===null&&(this.controlDeniedEntryIds.add(entry.targetId),this.projection=void 0),entry.type==="message"&&entry.controlDenied&&
|
|
94
|
+
this.controlDeniedEntryIds.add(entry.id),this.leafId=entry.id;try{this._persist(entry)}catch(error){throw this.fileEntries.pop(),this.byId.delete(entry.id),this.leafId=previousLeafId,error}entry.type==="session_info"&&(this.latestSessionInfo=entry)}appendMessage(message){let entry={type:"message",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),message};return this._appendEntry(entry),entry.id}appendThinkingLevelChange(thinkingLevel){let entry={type:"thinking_leve\
|
|
95
|
+
l_change",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel};return this._appendEntry(entry),entry.id}appendModelChange(provider,modelId){let entry={type:"model_change",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),provider,modelId};return this._appendEntry(entry),entry.id}appendUsage(kind,provider,model,usage,note){let entry={type:"usage",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),
|
|
96
|
+
kind,provider,model,usage,...note?{note}:{}};return this._appendEntry(entry),entry}appendCompaction(summary,firstKeptEntryId,tokensBefore,details,fromHook,usage,usageEntryIds){let timestamp=new Date().toISOString(),systemMessage=getCurrentSystemMessage(this.buildSessionProjection().messages),id=generateId(this.byId),entry={type:"compaction",id,parentId:this.leafId,timestamp,summary,firstKeptEntryId:firstKeptEntryId??id,tokensBefore,details,usage,...usageEntryIds?.length?{usageEntryIds:[...usageEntryIds]}:
|
|
97
|
+
{},fromHook,...systemMessage?{systemMessage:{...systemMessage,timestamp:new Date(timestamp).getTime()}}:{}};return this._appendEntry(entry),entry.id}appendCustomEntry(customType,data){let entry={type:"custom",customType,data,id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendSessionInfo(name){let sanitizedName=name.replace(/[\r\n]+/g," ").trim(),entry={type:"session_info",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().
|
|
98
|
+
toISOString(),name:sanitizedName};return this._appendEntry(entry),entry.id}getSessionName(){return this.latestSessionInfo?.name?.trim()||void 0}appendCustomMessageEntry(customType,content,display,details){let entry={type:"custom_message",customType,content,display,details,id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendContextEdit(targetId,replacement,reason){if(reason!==void 0&&(reason!=="control-denied"||replacement!==
|
|
99
|
+
null))throw new Error("Control denial must omit its target");if(replacement!==null&&(typeof replacement!="object"||!("content"in replacement)||typeof replacement.content!="string"&&!Array.isArray(replacement.content)))throw new Error("Context edit replacement must be null or contain string/array content");let target=this.byId.get(targetId);if(!target)throw new Error(`Entry ${targetId} not found`);if(!this.getBranch().some(entry2=>entry2.id===targetId))throw new Error(`Entry ${targetId} is not on\
|
|
100
|
+
the active branch`);if(!(target.type==="custom_message"||target.type==="message"&&(target.message.role==="user"||target.message.role==="assistant"||target.message.role==="toolResult")))throw new Error(`Entry ${targetId} does not contribute editable model content`);if(reason==="control-denied"&&(target.type!=="message"||target.message.role!=="user"))throw new Error("Control denial requires a user message");let targetRole=target.type==="message"?target.message.role:"custom",normalizedReplacement=replacement!==
|
|
101
|
+
null&&(targetRole==="assistant"||targetRole==="toolResult")&&typeof replacement.content=="string"?{content:[{type:"text",text:replacement.content}]}:replacement,entry={type:"context_edit",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,replacement:normalizedReplacement,...reason?{reason}:{}};return this._appendEntry(entry),entry.id}getLeafId(){return this.leafId}getLeafEntry(){return this.leafId?this.getEntry(this.leafId):void 0}getEntry(id){let entry=this.
|
|
102
|
+
byId.get(id);return entry&&omitControlDeniedContent(entry,this.controlDeniedEntryIds)}getChildren(parentId){let children=[];for(let entry of this.byId.values())entry.parentId===parentId&&children.push(omitControlDeniedContent(entry,this.controlDeniedEntryIds));return children}getLabel(id){return this.labelsById.get(id)}appendLabelChange(targetId,label){if(!this.byId.has(targetId))throw new Error(`Entry ${targetId} not found`);let entry={type:"label",id:generateId(this.byId),parentId:this.leafId,
|
|
103
|
+
timestamp:new Date().toISOString(),targetId,label};return this._appendEntry(entry),label?(this.labelsById.set(targetId,label),this.labelTimestampsById.set(targetId,entry.timestamp)):(this.labelsById.delete(targetId),this.labelTimestampsById.delete(targetId)),entry.id}getBranch(fromId){return(fromId===void 0||fromId===this.leafId?this._leafPath():this._walkBranch(fromId)).map(entry=>omitControlDeniedContent(entry,this.controlDeniedEntryIds))}getContextUsageEntries(){let entries=[],current=this.leafId?
|
|
104
|
+
this.byId.get(this.leafId):void 0;for(;current;){if(entries.length>this.byId.size)return this._contextUsageEntriesFromLeafPath();if(entries.push(omitControlDeniedContent(current,this.controlDeniedEntryIds)),current.type==="compaction")break;current=current.parentId?this.byId.get(current.parentId):void 0}return entries.reverse()}_contextUsageEntriesFromLeafPath(){let path2=this._leafPath(),start=path2.length-1;for(;start>0&&path2[start].type!=="compaction";)start--;return path2.slice(start).map(entry=>omitControlDeniedContent(
|
|
105
|
+
entry,this.controlDeniedEntryIds))}_walkBranch(startId){return walkToRoot(startId?this.byId.get(startId):void 0,this.byId)}_leafPath(){let leafId=this.leafId;if(leafId===null)return[];let cached=this.leafPath;if(cached?.leafId===leafId)return cached.path;let appended=cached&&this._appendedSince(cached.leafId,leafId),path2;if(cached&&appended){path2=cached.path;for(let entry of appended)path2.push(entry)}else path2=this._walkBranch(leafId);return this.leafPath={leafId,path:path2},path2}_appendedSince(fromId,leafId){
|
|
106
|
+
let appended=[],current=this.byId.get(leafId);for(;current&&appended.length<64;){if(appended.push(current),current.parentId===fromId)return appended.reverse();current=current.parentId?this.byId.get(current.parentId):void 0}}_projection(){let leafId=this.leafId,cached=this.projection;if(cached&&cached.leafId===leafId)return cached;let appended=leafId!==null&&cached?.leafId!=null?this._appendedSince(cached.leafId,leafId):void 0,projection;if(cached&&appended?.every(entry=>entry.type!=="compaction"&&
|
|
107
|
+
entry.type!=="context_edit")){projection=cached.projection;for(let entry of appended){applySessionContextSetting(projection,entry);let sourceEntry=omitControlDeniedContent(entry,this.controlDeniedEntryIds),messages=projectContextEntry(sourceEntry,void 0);projection.entries.push({sourceEntry,messages});for(let message of messages)projection.messages.push(message)}}else projection=buildSessionProjection(this.getEntries(),leafId,this.byId);return this.projection={leafId,projection,revision:++this.projectionRevision},
|
|
108
|
+
this.projection}buildContextEntries(){return buildContextEntries(this.getEntries(),this.leafId,this.byId)}buildSessionProjection(){let{projection}=this._projection(),entries=projectContextEntries(projection.entries.map(({sourceEntry})=>this.getEntry(sourceEntry.id)));return{entries,messages:entries.flatMap(entry=>entry.messages),thinkingLevel:projection.thinkingLevel,model:projection.model&&{...projection.model}}}getProjectionRevision(){return this._projection().revision}peekSessionProjection(){
|
|
109
|
+
return this._projection().projection}buildSessionContext(){let{messages,thinkingLevel,model}=this.buildSessionProjection();return{messages,thinkingLevel,model}}getHeader(){let h=this.fileEntries.find(e=>e.type==="session");return h||null}getEntryCount(){return this.byId.size}getEntries(){return this.fileEntries.filter(e=>e.type!=="session").map(entry=>omitControlDeniedContent(entry,this.controlDeniedEntryIds))}getTree(){let entries=this.getEntries(),nodeMap=new Map,roots=[],cuts=this.linksMayCycle?
|
|
110
|
+
this._cycleCuts():void 0,lastIndexById=this.byId.size!==entries.length?new Map:void 0;for(let i=0;i<entries.length;i++){let entry=entries[i],label=this.labelsById.get(entry.id),labelTimestamp=this.labelTimestampsById.get(entry.id),nodeEntry=cuts?.has(entry.id)?{...entry,parentId:null}:entry;nodeMap.set(entry.id,{entry:nodeEntry,children:[],label,labelTimestamp}),lastIndexById?.set(entry.id,i)}for(let i=0;i<entries.length;i++){let entry=entries[i];if(lastIndexById&&lastIndexById.get(entry.id)!==i)
|
|
111
|
+
continue;let node=nodeMap.get(entry.id);if(entry.parentId===null||entry.parentId===entry.id||cuts?.has(entry.id))roots.push(node);else{let parent=nodeMap.get(entry.parentId);parent?parent.children.push(node):roots.push(node)}}let stack=[...roots];for(;stack.length>0;){let node=stack.pop();node.children.sort((a,b)=>new Date(a.entry.timestamp).getTime()-new Date(b.entry.timestamp).getTime()),stack.push(...node.children)}return roots}_cycleCuts(){let cuts=new Set,done=new Set;for(let i=this.fileEntries.
|
|
112
|
+
length-1;i>=0;i--){let entry=this.fileEntries[i];if(entry.type==="session")continue;let onPath=new Set,current=this.byId.get(entry.id),last;for(;current&&!done.has(current.id);){if(onPath.has(current.id)){last&&cuts.add(last.id);break}onPath.add(current.id),last=current,current=current.parentId?this.byId.get(current.parentId):void 0}for(let id of onPath)done.add(id)}return cuts}branch(branchFromId){if(!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);this.leafId=branchFromId}resetLeaf(){
|
|
113
|
+
this.leafId=null}branchWithSummary(branchFromId,summary,details,fromHook,usage,usageEntryIds){if(branchFromId!==null&&!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);let fromId=this.leafId??"root";this.leafId=branchFromId;let entry={type:"branch_summary",id:generateId(this.byId),parentId:branchFromId,timestamp:new Date().toISOString(),fromId,summary,details,usage,...usageEntryIds?.length?{usageEntryIds:[...usageEntryIds]}:{},fromHook};return this._appendEntry(entry),
|
|
114
|
+
entry.id}createBranchedSession(leafId){let previousSessionFile=this.sessionFile,path2=includeSummaryUsageEntries(this.getBranch(leafId),id=>this.getEntry(id));if(path2.length===0)throw new Error(`Entry ${leafId} not found`);let pathWithoutLabels=[],replacementByLabelId=new Map,pendingLabelIds=[],pathParentId=null;for(let entry of path2){if(entry.type==="label"){pendingLabelIds.push(entry.id);continue}for(let labelId of pendingLabelIds)replacementByLabelId.set(labelId,entry.id);pendingLabelIds.length=
|
|
115
|
+
0,pathWithoutLabels.push(entry.type==="compaction"?{...entry,parentId:pathParentId,firstKeptEntryId:entry.firstKeptEntryId===entry.id?entry.id:replacementByLabelId.get(entry.firstKeptEntryId)??entry.firstKeptEntryId}:{...entry,parentId:pathParentId}),pathParentId=entry.id}let newSessionId=createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join2(this.getSessionDir(),`${fileTimestamp}_${newSessionId}.jsonl`),header={type:"session",version:CURRENT_SESSION_VERSION,
|
|
116
|
+
id:newSessionId,timestamp,cwd:this.cwd,parentSession:this.persist?previousSessionFile:void 0},pathEntryIds=new Set(pathWithoutLabels.map(e=>e.id)),labelsToWrite=[];for(let[targetId,label]of this.labelsById)pathEntryIds.has(targetId)&&labelsToWrite.push({targetId,label,timestamp:this.labelTimestampsById.get(targetId)});if(this.persist){let parentId2=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null,labelEntries2=[];for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={
|
|
117
|
+
type:"label",id:generateId(new Set(pathEntryIds)),parentId:parentId2,timestamp:labelTimestamp,targetId,label};pathEntryIds.add(labelEntry.id),labelEntries2.push(labelEntry),parentId2=labelEntry.id}return this.fileEntries=[header,...pathWithoutLabels,...labelEntries2],this.sessionId=newSessionId,this.sessionFile=newSessionFile,this._buildIndex(),this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,newSessionFile}let labelEntries=[],parentId=pathWithoutLabels[pathWithoutLabels.
|
|
118
|
+
length-1]?.id||null;for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set([...pathEntryIds,...labelEntries.map(e=>e.id)])),parentId,timestamp:labelTimestamp,targetId,label};labelEntries.push(labelEntry),parentId=labelEntry.id}this.fileEntries=[header,...pathWithoutLabels,...labelEntries],this.sessionId=newSessionId,this._buildIndex()}static create(cwd,sessionDir,options){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(
|
|
119
|
+
cwd);return new _SessionManager(cwd,dir,void 0,!0,options)}static open(path2,sessionDir,cwdOverride){let resolvedPath=resolvePath(path2),header=null,preloadedFileEntries;if(cwdOverride===void 0&&existsSync(resolvedPath))try{header=readSessionHeader(resolvedPath)}catch(error){if(!(error instanceof SessionHeaderScanLimitError))throw error;preloadedFileEntries=loadEntriesFromFile(resolvedPath);let firstEntry=preloadedFileEntries[0];header=firstEntry?.type==="session"?firstEntry:null}let cwd=cwdOverride??
|
|
120
|
+
(header?getSessionHeaderCwd(header):void 0)??process.cwd(),dir=sessionDir?normalizePath(sessionDir):resolve(resolvedPath,"..");return new _SessionManager(cwd,dir,resolvedPath,!0,void 0,preloadedFileEntries)}static continueRecent(cwd,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),mostRecent=findMostRecentSession(dir,cwd);return mostRecent?new _SessionManager(cwd,dir,mostRecent,!0):new _SessionManager(cwd,dir,void 0,!0)}static inMemory(cwd=process.cwd(),options,entries){
|
|
121
|
+
return new _SessionManager(cwd,"",void 0,!1,options,entries)}static forkFrom(sourcePath,targetCwd,sessionDir,options){let resolvedSourcePath=resolvePath(sourcePath),resolvedTargetCwd=resolvePath(targetCwd),sourceEntries=loadEntriesFromFile(resolvedSourcePath);if(sourceEntries.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);if(!sourceEntries.find(e=>e.type==="session"))throw new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);
|
|
122
|
+
migrateToCurrentVersion(sourceEntries);let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(resolvedTargetCwd);existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448}),options?.id!==void 0&&assertValidSessionId(options.id);let newSessionId=options?.id??createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join2(dir,`${fileTimestamp}_${newSessionId}.jsonl`),newHeader={type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,
|
|
123
|
+
timestamp,cwd:resolvedTargetCwd,parentSession:resolvedSourcePath},fd=openSessionFile(newSessionFile,"wx");try{writeFileSync(fd,`${JSON.stringify(newHeader)}
|
|
124
|
+
`);for(let entry of sourceEntries)entry.type!=="session"&&writeFileSync(fd,`${JSON.stringify(entry)}
|
|
125
|
+
`)}finally{closeSync(fd)}return new _SessionManager(resolvedTargetCwd,dir,newSessionFile,!0)}static findById(cwd,id,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),resolvedCwd=resolvePath(cwd);try{for(let file of readdirSync(dir)){if(!file.endsWith(".jsonl"))continue;let path2=join2(dir,file),header=readSessionHeaderForDiscovery(path2);if(header?.id===id&&sessionCwdMatches(getSessionHeaderCwd(header),resolvedCwd))return path2}}catch{}}static async list(cwd,sessionDir,onProgress,signal){
|
|
126
|
+
let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),resolvedCwd=resolvePath(cwd),includeSession=session=>sessionCwdMatches(session.cwd,resolvedCwd),sessions=(await listSessionsFromDir(dir,onProgress?(loaded,total,partialSessions)=>onProgress(loaded,total,partialSessions?.filter(includeSession)):void 0,signal)).filter(includeSession);return sortSessionInfos(sessions)}static async listAll(sessionDirOrOnProgress,onProgressOrSignal,signal){let customSessionDir=typeof sessionDirOrOnProgress==
|
|
127
|
+
"string"?normalizePath(sessionDirOrOnProgress):void 0,progress=typeof sessionDirOrOnProgress=="function"?sessionDirOrOnProgress:typeof onProgressOrSignal=="function"?onProgressOrSignal:void 0,abortSignal=typeof sessionDirOrOnProgress=="string"||typeof onProgressOrSignal=="function"?signal:onProgressOrSignal??signal;if(abortSignal?.throwIfAborted(),customSessionDir)return sortSessionInfos(await listSessionsFromDir(customSessionDir,progress,abortSignal));let sessionsDir=getSessionsDir();try{if(!existsSync(
|
|
128
|
+
sessionsDir))return[];let dirs=(await readdir(sessionsDir,{withFileTypes:!0})).filter(entry=>entry.isDirectory()||entry.isSymbolicLink()).map(entry=>join2(sessionsDir,entry.name)),allFiles=(await mapWithConcurrency(dirs,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS,async dir=>{try{return(await readdir(dir)).filter(file=>file.endsWith(".jsonl")).map(file=>join2(dir,file))}catch{return[]}},abortSignal)).flat(),candidates=await mapWithConcurrency(allFiles,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS,async path2=>{
|
|
129
|
+
try{return{path:path2,stats:await stat(path2)}}catch{return{path:path2}}},abortSignal);candidates.sort((a,b)=>(b.stats?.mtimeMs??Number.NEGATIVE_INFINITY)-(a.stats?.mtimeMs??Number.NEGATIVE_INFINITY)||basename(b.path).localeCompare(basename(a.path)));let totalFiles=candidates.length,loaded=0,firstCandidateLoaded=!1,partialSessions=[],results=await buildSessionInfosWithConcurrency(candidates,(info,index)=>{loaded++,index===0&&(firstCandidateLoaded=!0),info&&partialSessions.push(info);let publishPartial=firstCandidateLoaded&&
|
|
130
|
+
(index===0||loaded%ALL_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===totalFiles);progress?.(loaded,totalFiles,publishPartial?sortSessionInfos([...partialSessions]):void 0)},abortSignal);return sortSessionInfos(results.filter(info=>info!==null))}catch{return abortSignal?.throwIfAborted(),[]}}};export{applyExifOrientation,loadPhoton,resizeImage,formatDimensionNote,bashTruncationNote,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,CURRENT_SESSION_VERSION,includeSummaryUsageEntries,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,projectContextEntry,getControlDeniedEntryIds,buildSessionProjection,buildSessionContext,getDefaultSessionDirPath,getDefaultSessionDir,
|
|
131
|
+
SessionManager};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
function buildProviderErrorPattern(patterns){return new RegExp(patterns.join("|"),"i")}var NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN=buildProviderErrorPattern(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded","subscription_sharing_workplace_individual_usage_limit_exceeded",'"code"\\s*:\\s*"?1308(?![0-9])']),RETRYABLE_PROVIDER_ERROR_PATTERN=buildProviderErrorPattern(
|
|
3
|
+
["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","admission ceiling","rate.?limit","too many requests","^Throttling error:","rate increased too quickly","(?<![a-z0-9])(?:429|500|502|503|504|520|524|525)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","provider.?(?:is.?)?temporarily.?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error",'"type"\\s*:\\s*"api_error"',"exceeded request bu\
|
|
4
|
+
ffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream.?sse.?stream.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","connection.?closed","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","(?<![a-z0-9_])(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|ETIMEDOUT|EPIPE)(?![a-z0-9_])","connection reset by peer","E\
|
|
5
|
+
NOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","model provider stopped sending output for \\d+(?:\\.\\d+)? s \\(no progress\\)","terminated","websocket.?closed","websocket.?error","websocket.?connection.?limit.?reached","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","provider finish_reason: error","provider stopped wit\
|
|
6
|
+
h: error","provider stopped with: malformed_(?:response|function_call)","returned an empty response","stopped before completing the response","stream disconnected before completion","cut short after the reply had begun","ended the response before it was complete","connection to the provider was reset","reported a failure while generating the response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","repeat the req\
|
|
7
|
+
uest later","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),DASHSCOPE_THROTTLE_ERROR_PATTERN=/"code"\s*:\s*"Throttling\.AllocationQuota"/,DEFAULT_MAX_AGENT_RETRY_DELAY_MS=6e4;function retryDelayMs(policy,attempt,serverDelayMs){let delay=Math.max(policy.baseDelayMs*2**Math.max(0,attempt-1),Math.ceil(serverDelayMs??0)),safeDelay=Number.isSafeInteger(delay)?delay:Number.MAX_SAFE_INTEGER;return Math.min(safeDelay,policy.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS)}
|
|
8
|
+
var RetrySleepAbortError=class extends Error{constructor(){super("Aborted")}};function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new RetrySleepAbortError);return}let onAbort=()=>{clearTimeout(timeout),reject(new RetrySleepAbortError)},timeout=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms);signal?.addEventListener("abort",onAbort,{once:!0})})}async function retryAssistantCall(produce,policy,signal,callbacks){let maxAttempts=policy?.
|
|
9
|
+
enabled?policy.maxRetries:0,attempt=0,lastRetry;for(;;){let response=await produce();if(response.stopReason==="aborted")return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt),response;if(response.stopReason!=="error")return lastRetry&&await callbacks?.onRetryFinished?.(!0,lastRetry.attempt),response;if(attempt>=maxAttempts||!isRetryableAssistantError(response))return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,response.errorMessage),response;let delayMs=getAssistantRetryDelayMs(
|
|
10
|
+
response,retryDelayMs(policy,attempt+1,response.retryAfterMs));if(delayMs>(policy.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS))return lastRetry&&await callbacks?.onRetryFinished?.(!1,lastRetry.attempt,response.errorMessage),response;attempt++,lastRetry={attempt,errorMessage:response.errorMessage||"Unknown error"},await callbacks?.onRetryScheduled?.(attempt,maxAttempts,delayMs,lastRetry.errorMessage);try{await sleep(delayMs,signal)}catch(error){if(await callbacks?.onRetryFinished?.(!1,attempt,
|
|
11
|
+
lastRetry.errorMessage),error instanceof RetrySleepAbortError){let{errorMessage:_errorMessage,...rest}=response;return{...rest,stopReason:"aborted"}}throw error}await callbacks?.onRetryAttemptStart?.()}}function isRetryableAssistantError(message){if(message.stopReason!=="error"||!message.errorMessage)return!1;if(message.diagnostics?.some(entry=>entry.type==="provider_no_progress_timeout"))return!0;let httpError=message.diagnostics?.findLast(entry=>entry.type==="provider_http_error");if(typeof httpError?.
|
|
12
|
+
details?.retryable=="boolean")return httpError.details.retryable;let errorMessage=message.errorMessage;return DASHSCOPE_THROTTLE_ERROR_PATTERN.test(errorMessage)?!0:NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage)?!1:RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage)}function getAssistantRetryDelayMs(message,baseDelayMs){let retryAt=message.diagnostics?.findLast(entry=>entry.type==="provider_http_error")?.details?.retryAt;return typeof retryAt=="number"&&Number.isFinite(retryAt)?Math.
|
|
13
|
+
max(baseDelayMs,retryAt-Date.now()):baseDelayMs}export{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,retryDelayMs,retryAssistantCall,isRetryableAssistantError,getAssistantRetryDelayMs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{resolveSchemaRef}from"./chunk-
|
|
2
|
+
import{resolveSchemaRef}from"./chunk-MLOUZAVZ.js";import{typebox_exports}from"./chunk-VEGJT52D.js";var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,wordSegmenter=new Intl.Segmenter(void 0,{granularity:"word"}),STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}
|
|
3
3
|
function tokenize(text){let normalized=text.normalize("NFC").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ");return(/^[a-z0-9 ]*$/.test(normalized)?normalized.split(" "):Array.from(wordSegmenter.segment(normalized),segment=>segment.isWordLike?segment.segment:"")).filter(word=>word.length>0&&!STOP_WORDS.has(word)).map(word=>/^[a-z0-9]+$/.test(word)?stem(word):word)}function isObject(value){return typeof value=="obje\
|
|
4
4
|
ct"&&value!==null&&!Array.isArray(value)}function schemaText(schema,root,parts,seen){if(isObject(schema)){if(typeof schema.$ref=="string"){let target=resolveSchemaRef(schema.$ref,root);isObject(target)&&!seen.has(target)&&(seen.add(target),schemaText(target,root,parts,seen))}if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,root,parts,seen);schemaText(schema.
|
|
5
5
|
items,root,parts,seen);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,root,parts,seen)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.description];schemaText(tool.parameters,tool.parameters,parts,new Set([tool.parameters]));let namespaceText=namespace?[namespace.name,namespace.description??"",namespace.instructions??""].join(" "):"";return{name:tool.name,text:parts.filter(part=>part.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{appendAssistantMessageDiagnostic,findSubmissionAdmissionError,ownedSlice}from"./chunk-
|
|
2
|
+
import{appendAssistantMessageDiagnostic,findSubmissionAdmissionError,ownedSlice}from"./chunk-K5EFEIFP.js";var MAX_PROVIDER_ERROR_BODY_CHARS=4e3,MAX_PROVIDER_ERROR_INPUT_CHARS=64*1024,OVERSIZED_ERROR_TEXT="Provider error text exceeded 65536 characters",UNPARSEABLE_ERROR_TEXT="Unparseable structured provider error";function normalizeProviderError(error){let refusal=findSubmissionAdmissionError(error);if(refusal)return{message:refusal.message,messageCarriesBody:!0,admissionRefused:!0};if(!(error instanceof Error))return{message:truncateErrorText(safeJsonStringify(error),MAX_PROVIDER_ERROR_BODY_CHARS),messageCarriesBody:!1};
|
|
3
3
|
let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),message=body==="[REDACTED]"?body:truncateErrorText(error.message,MAX_PROVIDER_ERROR_BODY_CHARS),transport=transportEvidence(error);transport.transportCode&&TRANSPORT_CODES.has(transport.transportCode)&&!message.includes(transport.transportCode)&&(message=truncateErrorText(`${message} (${transport.transportCode})`,MAX_PROVIDER_ERROR_BODY_CHARS));let messageCarriesBody=body===void 0||message!=="[REDACTED]"&&message.includes(
|
|
4
4
|
body);return{status,body,message,messageCarriesBody,...transport}}function transportEvidence(error){let candidate=error,transportCode,transportName;for(let depth=0;depth<8&&candidate&&typeof candidate=="object";depth++){let nested=candidate,status=extractStatus(nested);if(status!==void 0&&status>=400||nested.name==="AbortError"||nested.constructor?.name==="APIUserAbortError")return{};typeof nested.code=="string"&&TRANSPORT_CODES.has(nested.code)&&(transportCode??=nested.code);for(let name of[nested.
|
|
5
5
|
name,nested.constructor?.name])["TimeoutError","APIConnectionTimeoutError","APIConnectionError"].includes(name)&&(transportName??=name);candidate=nested.cause}return transportCode??=transportName,transportCode?{transportCode}:{}}function appendProviderTransportDiagnostic(message,error){if(error.admissionRefused){appendAssistantMessageDiagnostic(message,{type:"provider_http_error",timestamp:Date.now(),details:{retryable:!1}});return}message.stopReason!=="error"||!error.transportCode||appendAssistantMessageDiagnostic(
|