@pixelzx/genesis 2026.6.4 ā 2026.6.5
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 +18 -0
- package/dist/.buildstamp +1 -1
- package/dist/abort-CcNxEsSq.js +201 -0
- package/dist/abort.runtime-DZJDSf0d.js +2 -0
- package/dist/abort.runtime.js +1 -1
- package/dist/accounts-B7M6y8l8.js +107 -0
- package/dist/accounts-DddcYo7u.js +2 -0
- package/dist/accounts-v0Cqfnse.js +104 -0
- package/dist/acp-cli-D_2_Nim8.js +2193 -0
- package/dist/acp-spawn-BZPupfsZ.js +2 -0
- package/dist/acp-spawn-CWfIrbK7.js +1093 -0
- package/dist/acp-stateful-target-driver-DpCTjH5T.js +89 -0
- package/dist/action-agents-fjIM4rpc.js +67 -0
- package/dist/action-focus-cx1pm1ym.js +132 -0
- package/dist/action-help-DtyAnULB.js +7 -0
- package/dist/action-info-DF30-xZl.js +101 -0
- package/dist/action-kill-rsSdXzvX.js +33 -0
- package/dist/action-list-4VN835m2.js +21 -0
- package/dist/action-log-L032mq5B.js +30 -0
- package/dist/action-send-Dm62UP-n.js +39 -0
- package/dist/action-spawn-BuZHKlpL.js +47 -0
- package/dist/action-unfocus-CTIWf8WX.js +29 -0
- package/dist/actions.runtime-0ezEcm7K.js +18 -0
- package/dist/actions.runtime-DKsCTTnH.js +5 -0
- package/dist/actions.runtime.js +1 -1
- package/dist/agent-BTOBOCIw.js +2 -0
- package/dist/agent-command-C-_EFUUu.js +874 -0
- package/dist/agent-harness-runtime-Bye6j3EL.js +144 -0
- package/dist/agent-runner-utils-CX2vCMkx.js +239 -0
- package/dist/agent-runner.runtime-BBqrjZv4.js +3455 -0
- package/dist/agent-runner.runtime.js +1 -1
- package/dist/agent-runtime-D1LIGcNj.js +18 -0
- package/dist/agents-CME2O1l9.js +5 -0
- package/dist/agents-DsDQvAPy.js +954 -0
- package/dist/aliases-C807OidC.js +2 -0
- package/dist/aliases-jq1ap6Dz.js +96 -0
- package/dist/api-BbxKoRkD.js +3 -0
- package/dist/api-CwJPCW9U.js +139 -0
- package/dist/api-N5Kaaq64.js +5 -0
- package/dist/approval-gateway-resolver-DIPFgTnx.js +29 -0
- package/dist/approval-gateway-runtime-i0yziXk2.js +2 -0
- package/dist/approval-handler-runtime-Cdm-10f9.js +439 -0
- package/dist/approval-native-runtime-BRjeBoqL.js +729 -0
- package/dist/attempt-execution.runtime-NFTF7Cbt.js +509 -0
- package/dist/attempt-execution.runtime.js +1 -1
- package/dist/attempt.prompt-helpers-DuBXv46v.js +221 -0
- package/dist/attempt.tool-run-context-Qf-tbC-C.js +933 -0
- package/dist/audit-DsDfRhB8.js +939 -0
- package/dist/audit.runtime-ComjcUGJ.js +7 -0
- package/dist/audit.runtime.js +1 -1
- package/dist/auth-BT_gqC-D.js +2 -0
- package/dist/auth-DeUz_8w8.js +383 -0
- package/dist/auth-order-DM7UkPDa.js +96 -0
- package/dist/auth-order-yS8hXrXh.js +2 -0
- package/dist/bash-tools-D0M9gBDu.js +3 -0
- package/dist/bash-tools-tnj1gSbO.js +2824 -0
- package/dist/binding-routing-C7atXiTD.js +85 -0
- package/dist/binding-targets-CCv7agx9.js +121 -0
- package/dist/bridge-server-C5O9rTJg.js +113 -0
- package/dist/browser-control-auth-GGN_kbqE.js +2 -0
- package/dist/browser-node-runtime-B-uTSVqP.js +12 -0
- package/dist/browser-profiles-Dex2eaLH.js +2 -0
- package/dist/browser-runtime-BPocB6yO.js +387 -0
- package/dist/browser-setup-tools-gHfYeDWA.js +13 -0
- package/dist/build-BqG7RkBz.js +550 -0
- package/dist/build-info.json +3 -3
- package/dist/bundled/boot-md/handler.js +2 -2
- package/dist/bundled/session-memory/handler.js +1 -1
- package/dist/call-BI4JvjcR.js +3 -0
- package/dist/call-wY43fzOF.js +331 -0
- package/dist/call.runtime-Dh61oVeL.js +2 -0
- package/dist/call.runtime.js +1 -1
- package/dist/capability-cli-BHz-2Stx.js +1401 -0
- package/dist/catchup-Be7tHJwK.js +300 -0
- package/dist/channel-B-6VmF4-.js +840 -0
- package/dist/channel-BCJccV-O.js +226 -0
- package/dist/channel-BDZqLbod.js +1100 -0
- package/dist/channel-BQDNgTea.js +1174 -0
- package/dist/channel-BwjThGwK.js +453 -0
- package/dist/channel-CPoThmda.js +595 -0
- package/dist/channel-CUT8NJ-B.js +350 -0
- package/dist/channel-C_Y7lv8v.js +491 -0
- package/dist/channel-Ck7-C-lB.js +297 -0
- package/dist/channel-DOpVjq4i.js +1802 -0
- package/dist/channel-core-QV9-eAtb.js +5 -0
- package/dist/channel-inbound-D_tebgdx.js +31 -0
- package/dist/channel-plugin-runtime-DXcBwNNM.js +771 -0
- package/dist/channel-runtime-D4ci0o4V.js +425 -0
- package/dist/channel-sAdF_zH-.js +1320 -0
- package/dist/channel.runtime-1swLIpNV.js +89 -0
- package/dist/channel.runtime-B9hljdNF.js +4 -0
- package/dist/channel.runtime-CSbR2pni.js +430 -0
- package/dist/channel.runtime-CdpqhnLO.js +2364 -0
- package/dist/channel.runtime-DOx6WROg.js +40130 -0
- package/dist/channel.runtime-H5Kb2LbC.js +109 -0
- package/dist/channel.runtime-V7boBc_e.js +576 -0
- package/dist/channel.runtime.js +1 -1
- package/dist/channel.setup-BXyeNJ2_.js +10 -0
- package/dist/channels-KU7bwUUs.js +733 -0
- package/dist/channels-cli-CTX6_5z3.js +268 -0
- package/dist/chat-C_i6Wp50.js +2830 -0
- package/dist/clawbot-cli-CLGPtbt-.js +9 -0
- package/dist/cli/daemon-cli.js +3 -3
- package/dist/cli-BhwHu1dK.js +72 -0
- package/dist/cli-CFsq8f2H.js +2 -0
- package/dist/cli-CNVlwurq.js +219 -0
- package/dist/cli-DLP8hKbi.js +2 -0
- package/dist/cli-runner-BbNBHV6v.js +286 -0
- package/dist/cli-runner.runtime-CfPaauuM.js +4 -0
- package/dist/cli-runner.runtime-MxBlCOO2.js +3 -0
- package/dist/cli-runner.runtime.js +1 -1
- package/dist/cli-startup-metadata.json +2 -2
- package/dist/cli.runtime-3cD-pSyn.js +1261 -0
- package/dist/cli.runtime.js +1 -1
- package/dist/client-Bl0d_7ak.js +138 -0
- package/dist/client-ClJyHgmq.js +713 -0
- package/dist/command-auth-DO32coey.js +76 -0
- package/dist/command-config-resolution-CAsa4fGg.js +2 -0
- package/dist/command-config-resolution-D6YcwuRh.js +23 -0
- package/dist/command-config-resolution.runtime-CSHDu35A.js +2 -0
- package/dist/command-config-resolution.runtime.js +1 -1
- package/dist/command-registry-BJEQrMqR.js +4 -0
- package/dist/command-registry-DI9i95nj.js +9 -0
- package/dist/command-registry-core-BpF1mggD.js +106 -0
- package/dist/command-secret-gateway-DDNHxysD.js +528 -0
- package/dist/command-status.runtime-DqYUCcEA.js +87 -0
- package/dist/command-status.runtime.js +1 -1
- package/dist/commands-acp-C_zCJPvL.js +77 -0
- package/dist/commands-compact.runtime-B6e3kwMS.js +10 -0
- package/dist/commands-compact.runtime.js +1 -1
- package/dist/commands-handlers.runtime-B0gTkAC0.js +4599 -0
- package/dist/commands-handlers.runtime.js +1 -1
- package/dist/commands-status-BgZ64sA8.js +16 -0
- package/dist/commands-status.runtime-JI89gIEU.js +3 -0
- package/dist/commands-status.runtime.js +1 -1
- package/dist/commands-subagents-control.runtime-B0hdcBxr.js +2 -0
- package/dist/commands-subagents-control.runtime-DUeSQ5j4.js +3 -0
- package/dist/commands-subagents-control.runtime.js +1 -1
- package/dist/commands-system-prompt-B7moUaCI.js +158 -0
- package/dist/commands-system-prompt-DTUkp9TH.js +2 -0
- package/dist/commands.runtime-BjCVVqol.js +167 -0
- package/dist/commands.runtime.js +1 -1
- package/dist/compact-BNJH56SX.js +1118 -0
- package/dist/compact.runtime-CYI8Yi9d.js +12 -0
- package/dist/compact.runtime.js +1 -1
- package/dist/completion-cli-Bb1Tk-vM.js +328 -0
- package/dist/config-DxkleHmo.js +252 -0
- package/dist/config-cli-CtaRB_f8.js +1078 -0
- package/dist/configure-Bp8WFryM.js +1252 -0
- package/dist/configure-DQ_X5zyT.js +2 -0
- package/dist/connect-options-BkWD0Wvv.js +699 -0
- package/dist/control-auth-Iqyldslx.js +125 -0
- package/dist/control-service-xIhkqyZE.js +156 -0
- package/dist/control-ui/assets/agents-Dh_TAFxm.js +1052 -0
- package/dist/control-ui/assets/canvas-BBkF0c_Z.js +269 -0
- package/dist/control-ui/assets/channel-config-extras-CNdHdere.js +2 -0
- package/dist/control-ui/assets/channels-DxBxgFLI.js +463 -0
- package/dist/control-ui/assets/cron-DI85RTUE.js +933 -0
- package/dist/control-ui/assets/de-ona0Q7Bc.js +2 -0
- package/dist/control-ui/assets/debug-DnDu2pj9.js +94 -0
- package/dist/control-ui/assets/es-Dn-oNRUH.js +2 -0
- package/dist/control-ui/assets/format-BvrOTETl.js +9 -0
- package/dist/control-ui/assets/fr-DXJ2RnNl.js +2 -0
- package/dist/control-ui/assets/i18n-BiXTtoQW.js +3 -0
- package/dist/control-ui/assets/id-BWsRmAR3.js +2 -0
- package/dist/control-ui/assets/index-YAwpI05T.js +6366 -0
- package/dist/control-ui/assets/instances-CRNiJVGJ.js +57 -0
- package/dist/control-ui/assets/ja-JP-BUkQN13S.js +2 -0
- package/dist/control-ui/assets/ko-Q_K13wyH.js +2 -0
- package/dist/control-ui/assets/logs-CzRlG5kP.js +74 -0
- package/dist/control-ui/assets/mcp-CAYQSRMs.js +373 -0
- package/dist/control-ui/assets/nodes-92SUclba.js +618 -0
- package/dist/control-ui/assets/pl-WlhlBCqd.js +2 -0
- package/dist/control-ui/assets/plugins-TwSBb6p5.js +273 -0
- package/dist/control-ui/assets/pt-BR-CVchspYo.js +2 -0
- package/dist/control-ui/assets/sessions-CHmx5D2H.js +306 -0
- package/dist/control-ui/assets/skills-C-34EOwN.js +323 -0
- package/dist/control-ui/assets/skills-shared-BbxW-wNm.js +11 -0
- package/dist/control-ui/assets/th-C4FUN3Mq.js +2 -0
- package/dist/control-ui/assets/tr-CoySBXqw.js +2 -0
- package/dist/control-ui/assets/uk-C-mkZs9j.js +2 -0
- package/dist/control-ui/assets/wallet-DjjoYuDY.js +285 -0
- package/dist/control-ui/assets/zh-CN-B7HXiLrY.js +2 -0
- package/dist/control-ui/assets/zh-TW-CKLRstBM.js +2 -0
- package/dist/control-ui/index.html +3 -3
- package/dist/conversation-id-BZtOqHIz.js +38 -0
- package/dist/conversation-id-D1Q9qPFH.js +235 -0
- package/dist/conversation-runtime-B1QZ-DEM.js +31 -0
- package/dist/core-BdVAy0Wv.js +275 -0
- package/dist/cron-cli-BWM2kRKU.js +713 -0
- package/dist/daemon-cli-MRl5nyuF.js +12 -0
- package/dist/dashboard-BkdlJrnf.js +2 -0
- package/dist/dashboard-C9m86rHv.js +81 -0
- package/dist/delegate-BjUvKQlo.js +64 -0
- package/dist/detached-task-runtime-BAEzkNB8.js +73 -0
- package/dist/devices-cli-B1n6tl9f.js +498 -0
- package/dist/diagnostics-DZxWkW3i.js +154 -0
- package/dist/direct-dm-qw-uk31C.js +64 -0
- package/dist/dispatch-D0xiJ6Up.js +1131 -0
- package/dist/dispatch-acp-DVN58m9G.js +981 -0
- package/dist/dispatch-acp-manager.runtime-C8t1i5Wt.js +3 -0
- package/dist/dispatch-acp-manager.runtime.js +1 -1
- package/dist/dispatch-acp.runtime-FR0DUPpn.js +19 -0
- package/dist/dispatch-acp.runtime.js +1 -1
- package/dist/doctor-device-pairing-DIbiBPlL.js +307 -0
- package/dist/doctor-gateway-daemon-flow-BFjRlXvA.js +250 -0
- package/dist/doctor-gateway-health-uZrukX3c.js +63 -0
- package/dist/doctor-health-DKpg1bxM.js +59 -0
- package/dist/doctor-health-contributions-BoXX8ubw.js +493 -0
- package/dist/doctor-prompter-CLf5Uf10.js +56 -0
- package/dist/doctor-workspace-status-Cw61BbGy.js +75 -0
- package/dist/dreaming-Bk8dVfGi.js +1574 -0
- package/dist/dreaming-narrative-DGSQa-0N.js +595 -0
- package/dist/embedded-gateway-stub.runtime-sokWrs6B.js +9 -0
- package/dist/embedded-gateway-stub.runtime.js +1 -1
- package/dist/entry.js +2 -2
- package/dist/exec-approvals-cli-CnNETs_u.js +498 -0
- package/dist/extensionAPI.js +1 -1
- package/dist/extensions/active-memory/index.js +1 -1
- package/dist/extensions/bluebubbles/api.js +3 -3
- package/dist/extensions/bluebubbles/channel-plugin-api.js +1 -1
- package/dist/extensions/browser/browser-bridge.js +1 -1
- package/dist/extensions/browser/browser-config.js +4 -4
- package/dist/extensions/browser/browser-control-auth.js +2 -2
- package/dist/extensions/browser/browser-doctor.js +2 -2
- package/dist/extensions/browser/browser-maintenance.js +2 -2
- package/dist/extensions/browser/browser-profiles.js +2 -2
- package/dist/extensions/browser/browser-runtime-api.js +10 -10
- package/dist/extensions/browser/index.js +1 -1
- package/dist/extensions/browser/plugin-registration.js +1 -1
- package/dist/extensions/browser/register.runtime.js +3 -3
- package/dist/extensions/browser/runtime-api.js +11 -11
- package/dist/extensions/browser/test-support.js +1 -1
- package/dist/extensions/device-pair/api.js +1 -1
- package/dist/extensions/device-pair/index.js +3 -3
- package/dist/extensions/device-pair/notify.js +1 -1
- package/dist/extensions/device-pair/pair-command-approve.js +1 -1
- package/dist/extensions/google-meet/index.js +2 -2
- package/dist/extensions/imessage/api.js +3 -3
- package/dist/extensions/imessage/channel-plugin-api.js +1 -1
- package/dist/extensions/imessage/runtime-api.js +3 -3
- package/dist/extensions/irc/api.js +2 -2
- package/dist/extensions/irc/channel-plugin-api.js +1 -1
- package/dist/extensions/line/api.js +2 -2
- package/dist/extensions/line/channel-plugin-api.js +1 -1
- package/dist/extensions/line/contract-api.js +1 -1
- package/dist/extensions/line/runtime-api.js +4 -4
- package/dist/extensions/line/setup-api.js +1 -1
- package/dist/extensions/llm-task/index.js +2 -2
- package/dist/extensions/lobster/index.js +3 -3
- package/dist/extensions/lobster/runtime-api.js +1 -1
- package/dist/extensions/mattermost/api.js +1 -1
- package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
- package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
- package/dist/extensions/mattermost/policy-api.js +1 -1
- package/dist/extensions/mattermost/runtime-api.js +4 -4
- package/dist/extensions/mattermost/slash-route-api.js +1 -1
- package/dist/extensions/memory-core/api.js +1 -1
- package/dist/extensions/memory-core/cli-metadata.js +2 -2
- package/dist/extensions/memory-core/index.js +3 -3
- package/dist/extensions/memory-lancedb/cli-metadata.js +1 -1
- package/dist/extensions/msteams/api.js +1 -1
- package/dist/extensions/msteams/channel-plugin-api.js +1 -1
- package/dist/extensions/msteams/runtime-api.js +3 -3
- package/dist/extensions/msteams/test-api.js +1 -1
- package/dist/extensions/nextcloud-talk/api.js +1 -1
- package/dist/extensions/nextcloud-talk/channel-plugin-api.js +1 -1
- package/dist/extensions/nextcloud-talk/runtime-api.js +2 -2
- package/dist/extensions/openshell/index.js +2 -2
- package/dist/extensions/signal/api.js +6 -6
- package/dist/extensions/signal/channel-plugin-api.js +1 -1
- package/dist/extensions/signal/reaction-runtime-api.js +1 -1
- package/dist/extensions/signal/runtime-api.js +7 -7
- package/dist/extensions/skill-workshop/api.js +1 -1
- package/dist/extensions/skill-workshop/index.js +1 -1
- package/dist/extensions/synology-chat/api.js +1 -1
- package/dist/extensions/synology-chat/channel-plugin-api.js +1 -1
- package/dist/extensions/tlon/api.js +2 -2
- package/dist/extensions/tlon/channel-plugin-api.js +1 -1
- package/dist/extensions/tlon/runtime-api.js +1 -1
- package/dist/extensions/tlon/test-api.js +1 -1
- package/dist/extensions/twitch/api.js +1 -1
- package/dist/extensions/twitch/channel-plugin-api.js +1 -1
- package/dist/extensions/twitch/setup-plugin-api.js +1 -1
- package/dist/extensions/zalo/api.js +3 -3
- package/dist/extensions/zalo/channel-plugin-api.js +1 -1
- package/dist/extensions/zalo/runtime-api.js +2 -2
- package/dist/extensions/zalo/setup-api.js +2 -2
- package/dist/extensions/zalouser/api.js +3 -3
- package/dist/extensions/zalouser/channel-plugin-api.js +1 -1
- package/dist/extensions/zalouser/runtime-api.js +6 -6
- package/dist/extensions/zalouser/setup-plugin-api.js +1 -1
- package/dist/extensions/zalouser/test-api.js +1 -1
- package/dist/fallbacks-BwNexEVP.js +31 -0
- package/dist/fallbacks-GwVAaFt5.js +2 -0
- package/dist/fallbacks-shared-DmepG9Mq.js +111 -0
- package/dist/gateway-BB4hdlYm.js +115 -0
- package/dist/gateway-cli-Bzz62NC8.js +1283 -0
- package/dist/gateway-rpc-dyJV2osv.js +14 -0
- package/dist/gateway-rpc.runtime-DYVOEv4W.js +23 -0
- package/dist/gateway-rpc.runtime.js +1 -1
- package/dist/gateway-runtime-CqSQCYo0.js +15 -0
- package/dist/gateway-status-DdCiwrPt.js +584 -0
- package/dist/genesis-tools-Bh6dAUhK.js +9166 -0
- package/dist/genesis-tools.runtime-CiIUponP.js +2 -0
- package/dist/genesis-tools.runtime.js +1 -1
- package/dist/get-reply-from-config.runtime-Cu2DcwOW.js +2 -0
- package/dist/get-reply-from-config.runtime.js +1 -1
- package/dist/get-reply-qVmTjhwr.js +3897 -0
- package/dist/graph-users-kkSJYBNX.js +1337 -0
- package/dist/health-CFyVDYng.js +469 -0
- package/dist/health-Cl371mu8.js +3 -0
- package/dist/health-route-D0IspgUK.js +41 -0
- package/dist/health-route-D2tFKCLv.js +2 -0
- package/dist/heartbeat-runner-Bmi8YsXz.js +5 -0
- package/dist/heartbeat-runner-FSCWra2R.js +1292 -0
- package/dist/heartbeat-runner.runtime-QF8dg4j-.js +4 -0
- package/dist/heartbeat-runner.runtime.js +1 -1
- package/dist/hooks-cli-DYoG7Dz1.js +433 -0
- package/dist/image-fallbacks-5ckuJ46I.js +31 -0
- package/dist/image-fallbacks-DYnqzK01.js +2 -0
- package/dist/inbound-reply-dispatch-D5pqDZRa.js +73 -0
- package/dist/index.js +2 -2
- package/dist/infra-runtime-D08WIqN2.js +39 -0
- package/dist/init-BCgwiSZj.js +59 -0
- package/dist/library-CP9n_7AP.js +45 -0
- package/dist/lifecycle-BYam90xH.js +229 -0
- package/dist/lifecycle-DS58sNmu.js +571 -0
- package/dist/lifecycle.runtime-DMwss7xM.js +2 -0
- package/dist/lifecycle.runtime.js +1 -1
- package/dist/list-CASc4IWz.js +131 -0
- package/dist/list-CBPrBS2u.js +1212 -0
- package/dist/list-Cf7fcqQd.js +2 -0
- package/dist/list-Dqd2QyTH.js +2 -0
- package/dist/list.probe-BWcMSWDF.js +419 -0
- package/dist/llm-slug-generator-4LADFhXT.js +79 -0
- package/dist/llm-slug-generator.js +1 -1
- package/dist/load-config-DI-LDL6p.js +35 -0
- package/dist/local-dispatch.runtime-WDgraH3j.js +8 -0
- package/dist/local-dispatch.runtime.js +1 -1
- package/dist/logs-cli-zoBIelUH.js +265 -0
- package/dist/logs-cli.runtime-DxKNxXAz.js +2 -0
- package/dist/logs-cli.runtime.js +1 -1
- package/dist/main-session-restart-recovery-DWZfkOzH.js +206 -0
- package/dist/managed-image-attachments-DLDa1aE2.js +2 -0
- package/dist/managed-image-attachments-a4v60Bk3.js +635 -0
- package/dist/manager-CfUcsSI9.js +2057 -0
- package/dist/manager-DmBBLCOg.js +2 -0
- package/dist/markdown-to-line-B0mPruD_.js +790 -0
- package/dist/mcp/plugin-tools-serve.js +1 -1
- package/dist/mcp-cli-CLL9nfvE.js +725 -0
- package/dist/mcp-http-p7GbtbMx.js +529 -0
- package/dist/memory-core-host-runtime-cli-CZNYkDoE.js +9 -0
- package/dist/message-CRyNLXch.js +232 -0
- package/dist/message-action-runner-5Y4EFpWh.js +1407 -0
- package/dist/message-action-runner-Dxv-GXkn.js +2 -0
- package/dist/message-actions-DtoR6Mr2.js +143 -0
- package/dist/message.gateway.runtime-RI4cvk_E.js +2 -0
- package/dist/message.gateway.runtime.js +1 -1
- package/dist/models-auth-status-DsheCXaS.js +201 -0
- package/dist/models-cli-CQQG1U-p.js +219 -0
- package/dist/monitor-BRRSjPQY.js +1459 -0
- package/dist/monitor-Ch-cG7Si.js +1661 -0
- package/dist/monitor-ChBhfnC-.js +788 -0
- package/dist/monitor-CsvCTpjq.js +671 -0
- package/dist/monitor-DjemBuVh.js +1237 -0
- package/dist/monitor-LyGEO-KI.js +2 -0
- package/dist/monitor-auth-DVCdDwlp.js +207 -0
- package/dist/monitor-processing-Cib3ZjUe.js +1974 -0
- package/dist/monitor.runtime-DLBFALbV.js +2 -0
- package/dist/monitor.runtime.js +1 -1
- package/dist/monitor.webhook-Dktr8JA-.js +180 -0
- package/dist/msteams-G5I2CO13.js +35 -0
- package/dist/native-hook-relay-B1ArNeG5.js +519 -0
- package/dist/nextcloud-talk-DimOAfaR.js +17 -0
- package/dist/node-cli-RIjV0id4.js +2276 -0
- package/dist/nodes-cli-Cke-B80I.js +1046 -0
- package/dist/nodes-utils-CsTqKwN9.js +84 -0
- package/dist/nodes.helpers-DYpGCFer.js +34 -0
- package/dist/notify-zBChwf0-.js +315 -0
- package/dist/onboard-D6UawRld.js +2 -0
- package/dist/onboard-DfoCtk3_.js +70 -0
- package/dist/onboard-helpers-BKQMe3RX.js +6 -0
- package/dist/onboard-helpers-BLBJlQ50.js +204 -0
- package/dist/onboard-interactive-GAbQD437.js +24 -0
- package/dist/onboard-non-interactive-Bqi-JXh3.js +635 -0
- package/dist/onboard-remote-CNpTyVws.js +193 -0
- package/dist/onboard-remote-GFp2lT6Y.js +2 -0
- package/dist/onboard-skills-BQneolfo.js +2 -0
- package/dist/onboard-skills-BipqJ48b.js +134 -0
- package/dist/openai-http-CLDWjSKC.js +500 -0
- package/dist/openresponses-http-DNvXNiw_.js +1128 -0
- package/dist/operator-approvals-client-gaflvETF.js +68 -0
- package/dist/outbound.runtime-ByVsvEri.js +2 -0
- package/dist/outbound.runtime.js +1 -1
- package/dist/pair-command-approve-Dzkubc-8.js +44 -0
- package/dist/persistent-bindings.lifecycle-BhdRK7Lp.js +2 -0
- package/dist/persistent-bindings.lifecycle-DQ0AiHuy.js +85 -0
- package/dist/pi-embedded-C789hs31.js +4 -0
- package/dist/pi-embedded-CXLkrOwv.js +2905 -0
- package/dist/pi-embedded.runtime-BaHYLgKa.js +4 -0
- package/dist/pi-embedded.runtime.js +1 -1
- package/dist/pi-tool-definition-adapter-DFutc0D4.js +229 -0
- package/dist/pi-tools-k60jrAVq.js +1057 -0
- package/dist/pi-tools.before-tool-call-CFy20GCz.js +2 -0
- package/dist/pi-tools.before-tool-call-DJmPOVfQ.js +433 -0
- package/dist/plugin-BfFuIgXQ.js +12195 -0
- package/dist/plugin-enabled-dXOUnZwX.js +140 -0
- package/dist/plugin-registration-CEAozQhV.js +23 -0
- package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
- package/dist/plugin-sdk/acp-binding-runtime.js +1 -1
- package/dist/plugin-sdk/acp-runtime.js +2 -2
- package/dist/plugin-sdk/agent-harness-runtime.js +5 -5
- package/dist/plugin-sdk/agent-harness.js +6 -6
- package/dist/plugin-sdk/agent-runtime.js +2 -2
- package/dist/plugin-sdk/approval-gateway-runtime.js +2 -2
- package/dist/plugin-sdk/approval-handler-runtime.js +3 -3
- package/dist/plugin-sdk/approval-runtime.js +1 -1
- package/dist/plugin-sdk/browser-node-runtime.js +4 -4
- package/dist/plugin-sdk/browser-setup-tools.js +3 -3
- package/dist/plugin-sdk/browser-support.js +7 -7
- package/dist/plugin-sdk/channel-core.js +2 -2
- package/dist/plugin-sdk/channel-inbound.js +2 -2
- package/dist/plugin-sdk/command-auth.js +1 -1
- package/dist/plugin-sdk/command-status-runtime.js +1 -1
- package/dist/plugin-sdk/compat.js +1 -1
- package/dist/plugin-sdk/conversation-binding-runtime.js +1 -1
- package/dist/plugin-sdk/conversation-runtime.js +3 -3
- package/dist/plugin-sdk/core.js +2 -2
- package/dist/plugin-sdk/direct-dm.js +1 -1
- package/dist/plugin-sdk/gateway-runtime.js +3 -3
- package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
- package/dist/plugin-sdk/index.js +1 -1
- package/dist/plugin-sdk/infra-runtime.js +2 -2
- package/dist/plugin-sdk/irc.js +2 -2
- package/dist/plugin-sdk/matrix.js +1 -1
- package/dist/plugin-sdk/memory-core-host-runtime-cli.js +2 -2
- package/dist/plugin-sdk/memory-core.js +2 -2
- package/dist/plugin-sdk/msteams.js +2 -2
- package/dist/plugin-sdk/nextcloud-talk.js +2 -2
- package/dist/plugin-sdk/nostr.js +1 -1
- package/dist/plugin-sdk/reply-dispatch-runtime.js +1 -1
- package/dist/plugin-sdk/reply-runtime.js +4 -4
- package/dist/plugin-sdk/runtime-secret-resolution.js +1 -1
- package/dist/plugin-sdk/runtime.js +2 -2
- package/dist/plugin-sdk/session-visibility.js +1 -1
- package/dist/plugin-sdk/testing.js +4 -4
- package/dist/plugin-sdk/tlon.js +1 -1
- package/dist/plugin-sdk/zalo.js +1 -1
- package/dist/plugin-sdk/zalouser.js +1 -1
- package/dist/plugin-service-BOpLQ8BU.js +2892 -0
- package/dist/plugins/runtime/index.js +1 -1
- package/dist/policy-DiIlt2yW.js +328 -0
- package/dist/postinstall-inventory.json +445 -445
- package/dist/prepare.runtime-Bd8adOy3.js +815 -0
- package/dist/prepare.runtime.js +1 -1
- package/dist/probe-BOlTfbzG.js +2 -0
- package/dist/probe-BSRvsN95.js +2205 -0
- package/dist/probe-CDfjQSnz.js +74 -0
- package/dist/probe-D7gHyiZV.js +241 -0
- package/dist/probe-DTNKTWSs.js +2 -0
- package/dist/probe-DcryDdZh.js +45 -0
- package/dist/probe-nyesoHxj.js +1443 -0
- package/dist/program-BFGavenz.js +111 -0
- package/dist/prompt-select-styled-BhY1zahx.js +20 -0
- package/dist/protocol-DxLbSF2J.js +2477 -0
- package/dist/provider-dispatcher-C-yy1D7r.js +22 -0
- package/dist/provider-dispatcher-ErSjESTP.js +2 -0
- package/dist/qr-cli-C1-oy_ho.js +349 -0
- package/dist/qr-cli-DmEs63Sb.js +2 -0
- package/dist/reaction-runtime-api-gua650a7.js +116 -0
- package/dist/reactions-R-rA7cXz.js +998 -0
- package/dist/register-service-commands-DkbqNKVB.js +71 -0
- package/dist/register.agent-C3nW9wDn.js +248 -0
- package/dist/register.configure-BzLHCu95.js +15 -0
- package/dist/register.maintenance-BHFQo4gr.js +363 -0
- package/dist/register.message-CsYRdfKi.js +329 -0
- package/dist/register.onboard-DltySQ6C.js +88 -0
- package/dist/register.runtime-6Sk1Njnp.js +81 -0
- package/dist/register.runtime.js +1 -1
- package/dist/register.setup-CDvVQJuj.js +150 -0
- package/dist/register.status-health-sessions-B8lorJ2x.js +1215 -0
- package/dist/register.subclis-BD4fuAci.js +3 -0
- package/dist/register.subclis-CbRd3F_m.js +29 -0
- package/dist/register.subclis-core-Dtq9dAjI.js +249 -0
- package/dist/reply-dispatch-runtime-DldslKSK.js +13 -0
- package/dist/reply-runtime-2EGTfk-1.js +11 -0
- package/dist/reply.runtime-OaHntzIS.js +2 -0
- package/dist/reply.runtime.js +1 -1
- package/dist/restart-health-BjmfJCUM.js +202 -0
- package/dist/restart-health-hw909zlD.js +2 -0
- package/dist/root-help-_hHiERsR.js +44 -0
- package/dist/routes-BxCk7Pue.js +3341 -0
- package/dist/routes-C1_6oFmZ.js +2 -0
- package/dist/rpc-zRbkEo6W.js +61 -0
- package/dist/rpc.runtime-BZSYNDPa.js +21 -0
- package/dist/rpc.runtime.js +1 -1
- package/dist/run-delivery.runtime-D6YDo67d.js +530 -0
- package/dist/run-delivery.runtime.js +1 -1
- package/dist/run-embedded.runtime-BsgPrPDa.js +4 -0
- package/dist/run-embedded.runtime.js +1 -1
- package/dist/run-execution-cli.runtime-CggaHhrJ.js +4 -0
- package/dist/run-execution-cli.runtime.js +1 -1
- package/dist/run-executor.runtime-CKkLEr_T.js +277 -0
- package/dist/run-executor.runtime.js +1 -1
- package/dist/run-main-CJYYkV6H.js +567 -0
- package/dist/run-subagent-registry.runtime-B0sgf_oy.js +2 -0
- package/dist/run-subagent-registry.runtime.js +1 -1
- package/dist/run-wait-DHizeptL.js +135 -0
- package/dist/runtime-EtV_ChXX.js +9 -0
- package/dist/runtime-api-6H864Pmt.js +9 -0
- package/dist/runtime-api-CbZqRBZQ.js +14 -0
- package/dist/runtime-api-ZxEgu8cW.js +4 -0
- package/dist/runtime-api-j9A6jYUr.js +9 -0
- package/dist/runtime-embedded-pi.runtime-BHjCPnxo.js +2 -0
- package/dist/runtime-embedded-pi.runtime.js +1 -1
- package/dist/runtime-hvRzTSAZ.js +973 -0
- package/dist/runtime-internal-C_KZYzFK.js +2 -0
- package/dist/runtime-options-BZEOCnMg.js +275 -0
- package/dist/runtime-schema-R7LWe58K.js +28576 -0
- package/dist/scan-BNDE3dSE.js +523 -0
- package/dist/scan-TG6lVEQ2.js +2 -0
- package/dist/secrets-cli-twD2FWoZ.js +2101 -0
- package/dist/security-cli-Cd1A5yhL.js +486 -0
- package/dist/selection-CqqmU0Hi.js +7764 -0
- package/dist/selection-CsM62vcz.js +2 -0
- package/dist/send-D-EgB64m.js +156 -0
- package/dist/send-DPk5hW1W.js +102 -0
- package/dist/send.runtime-3QDkKN71.js +2 -0
- package/dist/send.runtime.js +1 -1
- package/dist/server-C94r_Qff.js +77 -0
- package/dist/server-Ceiopn_v.js +13 -0
- package/dist/server-context-BFJlu5HY.js +2 -0
- package/dist/server-context-PNEqhnTM.js +847 -0
- package/dist/server-node-events-QOAWLsDC.js +481 -0
- package/dist/server-plugin-bootstrap-CgsjzB17.js +2 -0
- package/dist/server-plugin-bootstrap-Dfuf75EN.js +12728 -0
- package/dist/server-restart-sentinel-BMPqZ7Jw.js +697 -0
- package/dist/server.impl-CCoQpvB7.js +12864 -0
- package/dist/session-kill-http-oPi3ajEp.js +110 -0
- package/dist/session-reset-service-CzDd6PBK.js +497 -0
- package/dist/session-route-DUOQE8-f.js +93 -0
- package/dist/session-status.runtime-W5tlGbXw.js +2 -0
- package/dist/session-status.runtime.js +1 -1
- package/dist/session-subagent-reactivation.runtime-yoYn1awK.js +2 -0
- package/dist/session-subagent-reactivation.runtime.js +1 -1
- package/dist/session-tab-registry-DkeCaT-2.js +581 -0
- package/dist/session-visibility-B4CFjv43.js +147 -0
- package/dist/sessions-helpers-CDfOVWe3.js +305 -0
- package/dist/sessions-history-http-QXeTdxXM.js +383 -0
- package/dist/sessions-patch-xb4bXPwh.js +309 -0
- package/dist/sessions-resolve-BPlrW8C3.js +174 -0
- package/dist/sessions.runtime-yYJXudA9.js +2 -0
- package/dist/sessions.runtime.js +1 -1
- package/dist/setup-0Im0LL1d.js +636 -0
- package/dist/setup-api-BxwfqXN-.js +29 -0
- package/dist/setup-core-BWwXgEuM.js +171 -0
- package/dist/setup-core-DzHNbQLG.js +176 -0
- package/dist/setup-surface-BVnqDsfU.js +286 -0
- package/dist/setup-surface-BajZWmKz2.js +403 -0
- package/dist/setup-surface-rDO3YjSb.js +219 -0
- package/dist/setup.finalize-BsnPbdwc.js +547 -0
- package/dist/setup.gateway-config-BFawSWHL.js +250 -0
- package/dist/shared-52tFSlVk.js +121 -0
- package/dist/shared-C8ENgtxM.js +198 -0
- package/dist/shared-DbXvU7JV.js +76 -0
- package/dist/slash-state-CMuPwgKt.js +1911 -0
- package/dist/src-IzaHgU6a.js +3974 -0
- package/dist/startup-context-xJS8ckSG.js +312 -0
- package/dist/status-BO4LMTER.js +2 -0
- package/dist/status-BwY1tASe.js +3 -0
- package/dist/status-BxG6n-ko.js +397 -0
- package/dist/status-Co_cq2vy.js +2 -0
- package/dist/status-DKNeRGzW.js +190 -0
- package/dist/status-DzlIHiTS.js +209 -0
- package/dist/status-all-DF7qaWjo.js +498 -0
- package/dist/status-json-CgCilobT.js +14 -0
- package/dist/status-json-command-DAa78z3e.js +84 -0
- package/dist/status-runtime-shared-CRCuxXn_.js +257 -0
- package/dist/status-subagents.runtime-hUsBd4C5.js +18 -0
- package/dist/status-subagents.runtime.js +1 -1
- package/dist/status-text-BdbRrl1G.js +237 -0
- package/dist/status.gateway-connection.runtime-BmSTYFFO.js +2 -0
- package/dist/status.gateway-connection.runtime.js +1 -1
- package/dist/status.gather-CItmFIHS.js +292 -0
- package/dist/status.gather-qB6WOoH7.js +2 -0
- package/dist/status.runtime-ClZCgYx1.js +2 -0
- package/dist/status.runtime.js +1 -1
- package/dist/status.scan-overview-B0b0Mvng.js +379 -0
- package/dist/status.scan-xY7nUi9N.js +65 -0
- package/dist/status.scan.fast-json-BANGHOys.js +132 -0
- package/dist/status.scan.fast-json-M-DmMy2l.js +2 -0
- package/dist/status.summary-B3PlFnWw.js +2 -0
- package/dist/status.summary-adB75FOM.js +214 -0
- package/dist/subagent-announce-B4w7Mcpr.js +351 -0
- package/dist/subagent-announce-delivery-Dma0A4gL.js +726 -0
- package/dist/subagent-announce-output-sUPLcge-.js +364 -0
- package/dist/subagent-control-CxR0WRrx.js +506 -0
- package/dist/subagent-followup.runtime-XeFe_LA0.js +68 -0
- package/dist/subagent-followup.runtime.js +1 -1
- package/dist/subagent-orphan-recovery-CJPHy8JV.js +305 -0
- package/dist/subagent-registry-CjMWjRCE.js +1753 -0
- package/dist/subagent-registry-H20VxEu0.js +3 -0
- package/dist/subagent-registry.runtime.js +1 -1
- package/dist/subagent-spawn-CRM5x6cV.js +1005 -0
- package/dist/system-cli-BJ5mMirj.js +59 -0
- package/dist/targets-CUnlEj96.js +67 -0
- package/dist/task-executor-DKnEwQ6v.js +360 -0
- package/dist/task-owner-access-CfypP1Yc.js +74 -0
- package/dist/task-registry-delivery-runtime-BB6ZzpqH.js +2 -0
- package/dist/task-registry-delivery-runtime-CvHa0gv-.js +3 -0
- package/dist/task-registry-pQuAfAL9.js +2366 -0
- package/dist/task-registry.maintenance-Bfd87wEV.js +416 -0
- package/dist/task-registry.maintenance-VgfbW0yt.js +2 -0
- package/dist/telegram/token.js +1 -1
- package/dist/testing-C_mngO0u.js +575 -0
- package/dist/text-report-Ct6t3he6.js +587 -0
- package/dist/tool-resolution-C4KGgPH-.js +90 -0
- package/dist/tools-effective-inventory-Bo2QC-m8.js +152 -0
- package/dist/tools-invoke-http-CBZPFh5L.js +206 -0
- package/dist/trash-DhZow3jd.js +24 -0
- package/dist/tui-cli-BPdQPozP.js +4575 -0
- package/dist/update-cli-BRi3mVAU.js +1759 -0
- package/dist/upgrade-D9zejtCk.js +1226 -0
- package/dist/video-generation-task-status-BSBQ0_FO.js +163 -0
- package/dist/wait-for-idle-before-flush-D1dTT9th.js +5986 -0
- package/dist/wizard-models-ysyV_WWR.js +334 -0
- package/package.json +1 -1
- package/dist/abort-DaihtnYj.js +0 -201
- package/dist/abort.runtime-BUT9L_5l.js +0 -2
- package/dist/accounts-BY5wsBnV.js +0 -104
- package/dist/accounts-DGth1vsM.js +0 -107
- package/dist/accounts-Do6Ir-q3.js +0 -2
- package/dist/acp-cli-BHgjn8rh.js +0 -2193
- package/dist/acp-spawn-BAM_Jrft.js +0 -2
- package/dist/acp-spawn-DyBD_Y_t.js +0 -1093
- package/dist/acp-stateful-target-driver-DKGnfjWu.js +0 -89
- package/dist/action-agents-CzMSNQdc.js +0 -67
- package/dist/action-focus-CpjIrZFe.js +0 -132
- package/dist/action-help-BhE9UosK.js +0 -7
- package/dist/action-info-CH2j6dKT.js +0 -101
- package/dist/action-kill-CB4AnLIf.js +0 -33
- package/dist/action-list-CQ8LbzvR.js +0 -21
- package/dist/action-log-DZblh247.js +0 -30
- package/dist/action-send-DMe0B4FG.js +0 -39
- package/dist/action-spawn-CkKMESb5.js +0 -47
- package/dist/action-unfocus-DjQzPZwU.js +0 -29
- package/dist/actions.runtime-CUdRdpLB.js +0 -5
- package/dist/actions.runtime-CxRstWdN.js +0 -18
- package/dist/agent-command-Nh_kPL3z.js +0 -874
- package/dist/agent-harness-runtime-BEb7Wk1m.js +0 -144
- package/dist/agent-q6U-cKJn.js +0 -2
- package/dist/agent-runner-utils-x_qJ6xYC.js +0 -239
- package/dist/agent-runner.runtime-DRvTfUPd.js +0 -3455
- package/dist/agent-runtime-jSYYQd6f.js +0 -18
- package/dist/agents-BKOpsZXw.js +0 -5
- package/dist/agents-BY34ViPX.js +0 -954
- package/dist/aliases-CD5YlX7d.js +0 -2
- package/dist/aliases-Dq31zANx.js +0 -96
- package/dist/api-BhxN9fxJ.js +0 -139
- package/dist/api-DjL_3olO.js +0 -5
- package/dist/api-jIYND-S5.js +0 -3
- package/dist/approval-gateway-resolver-BfvdJW5s.js +0 -29
- package/dist/approval-gateway-runtime-BBf976nt.js +0 -2
- package/dist/approval-handler-runtime-Bq4p5wvg.js +0 -439
- package/dist/approval-native-runtime-IrisOZrU.js +0 -729
- package/dist/attempt-execution.runtime-BXGalt-_.js +0 -509
- package/dist/attempt.prompt-helpers-A-pc2LfL.js +0 -221
- package/dist/attempt.tool-run-context-Ukna4ck-.js +0 -933
- package/dist/audit-CVUpfDvE.js +0 -939
- package/dist/audit.runtime-CsuGXvud.js +0 -7
- package/dist/auth-CjcZyRUW.js +0 -383
- package/dist/auth-order-DIkyTpW4.js +0 -2
- package/dist/auth-order-Dpt1K1rT.js +0 -96
- package/dist/auth-sVuL2xeZ.js +0 -2
- package/dist/bash-tools-DDv0zQh9.js +0 -2824
- package/dist/bash-tools-s-QSvRmt.js +0 -3
- package/dist/binding-routing-Cz5R2kFK.js +0 -85
- package/dist/binding-targets-D4j2hdQh.js +0 -121
- package/dist/bridge-server-X8SdeAI3.js +0 -113
- package/dist/browser-control-auth-BrF3DZxC.js +0 -2
- package/dist/browser-node-runtime-BecPmKOx.js +0 -12
- package/dist/browser-profiles-BxAKEG3x.js +0 -2
- package/dist/browser-runtime-D9fTDscJ.js +0 -387
- package/dist/browser-setup-tools--AQGWGvl.js +0 -13
- package/dist/build-B0nbyXrw.js +0 -550
- package/dist/call-BvqN9kay.js +0 -3
- package/dist/call-Dk5rTl-p.js +0 -331
- package/dist/call.runtime-Bx1hKDwO.js +0 -2
- package/dist/capability-cli-286Z3Bq3.js +0 -1401
- package/dist/catchup-DyeQ6GNj.js +0 -300
- package/dist/channel-B5m01jSZ.js +0 -1802
- package/dist/channel-BE26v3WU.js +0 -840
- package/dist/channel-BS7r_Zt1.js +0 -226
- package/dist/channel-BUWCqkGh.js +0 -1320
- package/dist/channel-BhgKqvZn.js +0 -453
- package/dist/channel-Bx703sxQ.js +0 -297
- package/dist/channel-CDjlEQAM.js +0 -491
- package/dist/channel-ChrqAgRS.js +0 -595
- package/dist/channel-Crmp3BHh.js +0 -1100
- package/dist/channel-D7GdDfBl.js +0 -1174
- package/dist/channel-DqSzRIul.js +0 -350
- package/dist/channel-core-DIwclC34.js +0 -5
- package/dist/channel-inbound-DPW1gRUU.js +0 -31
- package/dist/channel-plugin-runtime-BJhRSlBI.js +0 -771
- package/dist/channel-runtime-sV_Sg0EO.js +0 -425
- package/dist/channel.runtime-4BaNapRW.js +0 -89
- package/dist/channel.runtime-Bk2w0Yzd.js +0 -2364
- package/dist/channel.runtime-Bo5_2imz.js +0 -109
- package/dist/channel.runtime-CdYWlMyL.js +0 -40130
- package/dist/channel.runtime-CrYmCmSw.js +0 -4
- package/dist/channel.runtime-D3APPhVs.js +0 -430
- package/dist/channel.runtime-DjF1Gg6N.js +0 -576
- package/dist/channel.setup-BxXrmAYb.js +0 -10
- package/dist/channels-DHcJgMnw.js +0 -733
- package/dist/channels-cli-Dnq08u4r.js +0 -268
- package/dist/chat-BGU3UVKD.js +0 -2830
- package/dist/clawbot-cli-C-rqJUW-.js +0 -9
- package/dist/cli-BlnGJbLJ.js +0 -219
- package/dist/cli-D0RU1q0-.js +0 -2
- package/dist/cli-DBw79G2t.js +0 -72
- package/dist/cli-Dul37_xp.js +0 -2
- package/dist/cli-runner-DY8BKEmu.js +0 -286
- package/dist/cli-runner.runtime-5JMuegF9.js +0 -3
- package/dist/cli-runner.runtime-DQROn9Ve.js +0 -4
- package/dist/cli.runtime-CGOUREQg.js +0 -1261
- package/dist/client-CCBN1ydB.js +0 -138
- package/dist/client-PHLyQ8il.js +0 -713
- package/dist/command-auth-79QKQZZ3.js +0 -76
- package/dist/command-config-resolution-BKAgMItc.js +0 -2
- package/dist/command-config-resolution-BUCAmCZ_.js +0 -23
- package/dist/command-config-resolution.runtime-BVtfeARM.js +0 -2
- package/dist/command-registry-C9axn0de.js +0 -4
- package/dist/command-registry-DkcFlIyM.js +0 -9
- package/dist/command-registry-core-DEDRtJmS.js +0 -106
- package/dist/command-secret-gateway-g0alGmKz.js +0 -528
- package/dist/command-status.runtime-Dw6Zj5hL.js +0 -87
- package/dist/commands-acp-De-XFc40.js +0 -77
- package/dist/commands-compact.runtime-6gixR2a8.js +0 -10
- package/dist/commands-handlers.runtime-DCmZAlRN.js +0 -4599
- package/dist/commands-status-CION7GYY.js +0 -16
- package/dist/commands-status.runtime-FBwoHftv.js +0 -3
- package/dist/commands-subagents-control.runtime-C2xgOYKM.js +0 -2
- package/dist/commands-subagents-control.runtime-CgIEblx3.js +0 -3
- package/dist/commands-system-prompt-B-jC-KV-.js +0 -158
- package/dist/commands-system-prompt-DeK5Jhy_.js +0 -2
- package/dist/commands.runtime-CHSb1kYa.js +0 -167
- package/dist/compact-Dwchggv2.js +0 -1118
- package/dist/compact.runtime-jDUYMSjR.js +0 -12
- package/dist/completion-cli-DGiZcg4E.js +0 -328
- package/dist/config-Bnb9qa1S.js +0 -252
- package/dist/config-cli-BuZ5RUhD.js +0 -1078
- package/dist/configure-BLNGlWh0.js +0 -1252
- package/dist/configure-nPzsEeOb.js +0 -2
- package/dist/connect-options-C9cvS-bh.js +0 -699
- package/dist/control-auth-D2-P54fW.js +0 -125
- package/dist/control-service-CqUPgxlx.js +0 -156
- package/dist/control-ui/assets/agents-CA3uz9sP.js +0 -1052
- package/dist/control-ui/assets/canvas-D0sLy568.js +0 -269
- package/dist/control-ui/assets/channel-config-extras-CWzNTLS-.js +0 -2
- package/dist/control-ui/assets/channels-DXgjbWts.js +0 -463
- package/dist/control-ui/assets/cron-D-rffMH6.js +0 -933
- package/dist/control-ui/assets/de-l9FbKtxt.js +0 -2
- package/dist/control-ui/assets/debug-Vf_bLYLB.js +0 -94
- package/dist/control-ui/assets/es-CC-t9AUQ.js +0 -2
- package/dist/control-ui/assets/format-BL-FisEP.js +0 -9
- package/dist/control-ui/assets/fr-DZKceqST.js +0 -2
- package/dist/control-ui/assets/i18n-DFH8x0DD.js +0 -3
- package/dist/control-ui/assets/id-D93YKkrM.js +0 -2
- package/dist/control-ui/assets/index-lWAwAXYo.js +0 -6366
- package/dist/control-ui/assets/instances-BmzzTloa.js +0 -57
- package/dist/control-ui/assets/ja-JP-DoPdk5L_.js +0 -2
- package/dist/control-ui/assets/ko-8TeOGGHm.js +0 -2
- package/dist/control-ui/assets/logs-BjPSImvD.js +0 -74
- package/dist/control-ui/assets/mcp-CQGmuKdR.js +0 -281
- package/dist/control-ui/assets/nodes-CDhqPGsD.js +0 -618
- package/dist/control-ui/assets/pl-BSP1Y3tH.js +0 -2
- package/dist/control-ui/assets/plugins-D4fXQx07.js +0 -273
- package/dist/control-ui/assets/pt-BR-D4-81_zm.js +0 -2
- package/dist/control-ui/assets/sessions-DzjXl7P7.js +0 -306
- package/dist/control-ui/assets/skills-BTQrLVPj.js +0 -323
- package/dist/control-ui/assets/skills-shared-CX4mwYFK.js +0 -11
- package/dist/control-ui/assets/th-DrnubOIu.js +0 -2
- package/dist/control-ui/assets/tr-BMyrj0eZ.js +0 -2
- package/dist/control-ui/assets/uk-CZhU3bHK.js +0 -2
- package/dist/control-ui/assets/wallet-DPb6whuj.js +0 -285
- package/dist/control-ui/assets/zh-CN-CH12jxSw.js +0 -2
- package/dist/control-ui/assets/zh-TW-CaTySceX.js +0 -2
- package/dist/conversation-id-BAzJOKBB.js +0 -235
- package/dist/conversation-id-WJLKuyy9.js +0 -38
- package/dist/conversation-runtime-D8fK5aI0.js +0 -31
- package/dist/core-DywmHt1k.js +0 -275
- package/dist/cron-cli-CeEJRkfR.js +0 -713
- package/dist/daemon-cli-BZZOjJHx.js +0 -12
- package/dist/dashboard-C0NRxmP3.js +0 -81
- package/dist/dashboard-DqhPgQv-.js +0 -2
- package/dist/delegate-DwVbOeR5.js +0 -64
- package/dist/detached-task-runtime-DiDRj-v-.js +0 -73
- package/dist/devices-cli-BKVbpwVc.js +0 -498
- package/dist/diagnostics-gh3UN_iV.js +0 -154
- package/dist/direct-dm-CwHHUkHV.js +0 -64
- package/dist/dispatch-B5af8_1v.js +0 -1131
- package/dist/dispatch-acp-DgOnUWBl.js +0 -981
- package/dist/dispatch-acp-manager.runtime-XWNjVh_M.js +0 -3
- package/dist/dispatch-acp.runtime-BdYL_ZqM.js +0 -19
- package/dist/doctor-device-pairing-CtGzWmXB.js +0 -307
- package/dist/doctor-gateway-daemon-flow-CCBI0jL4.js +0 -250
- package/dist/doctor-gateway-health-CkjqPFDl.js +0 -63
- package/dist/doctor-health-BOhuy1vP.js +0 -59
- package/dist/doctor-health-contributions-ChEuyLAY.js +0 -493
- package/dist/doctor-prompter-9nOTFD0Q.js +0 -56
- package/dist/doctor-workspace-status-CO5Ocwlt.js +0 -75
- package/dist/dreaming-GOPEFPio.js +0 -1574
- package/dist/dreaming-narrative-DfxHaxOU.js +0 -595
- package/dist/embedded-gateway-stub.runtime-B2OWcbsK.js +0 -9
- package/dist/exec-approvals-cli-CGeFtFbB.js +0 -498
- package/dist/fallbacks-CdfWAgNP.js +0 -2
- package/dist/fallbacks-eXbQ8TBp.js +0 -31
- package/dist/fallbacks-shared-akcCu5CD.js +0 -111
- package/dist/gateway-D-dDKqwi.js +0 -115
- package/dist/gateway-cli-DBS06Da8.js +0 -1283
- package/dist/gateway-rpc-Cxa8dVW5.js +0 -14
- package/dist/gateway-rpc.runtime-D76s-oxs.js +0 -23
- package/dist/gateway-runtime-Dhm_gLh1.js +0 -15
- package/dist/gateway-status-C_L_CdOg.js +0 -584
- package/dist/genesis-tools-rRJB3JXY.js +0 -9166
- package/dist/genesis-tools.runtime-6oKokqaA.js +0 -2
- package/dist/get-reply-BkiDsDVY.js +0 -3897
- package/dist/get-reply-from-config.runtime-CHKCcj9D.js +0 -2
- package/dist/graph-users-BnXIYyC5.js +0 -1337
- package/dist/health-ZsJNENSY.js +0 -3
- package/dist/health-osa9LOJf.js +0 -469
- package/dist/health-route-8TdKOYLp.js +0 -2
- package/dist/health-route-BdLtX2Bg.js +0 -41
- package/dist/heartbeat-runner-BCbkAprr.js +0 -1292
- package/dist/heartbeat-runner-Dc1K8S94.js +0 -5
- package/dist/heartbeat-runner.runtime-pJaAsgLY.js +0 -4
- package/dist/hooks-cli-C3ggAz0i.js +0 -433
- package/dist/image-fallbacks-CiSae-lb.js +0 -2
- package/dist/image-fallbacks-vI8KUh6N.js +0 -31
- package/dist/inbound-reply-dispatch-DLM60UDh.js +0 -73
- package/dist/infra-runtime-CrHVeejV.js +0 -39
- package/dist/init-BKeEiV2q.js +0 -59
- package/dist/library-CHB7yTo5.js +0 -45
- package/dist/lifecycle-CUULToPr.js +0 -229
- package/dist/lifecycle-DCMpTRD2.js +0 -571
- package/dist/lifecycle.runtime-CP4gRxWv.js +0 -2
- package/dist/list-0zDFAWTF.js +0 -2
- package/dist/list-BaxVHTAN.js +0 -131
- package/dist/list-CMRMgrPs.js +0 -1212
- package/dist/list-DSrBtnKI.js +0 -2
- package/dist/list.probe-BJYSCsJY.js +0 -419
- package/dist/llm-slug-generator-Bn_wrWYw.js +0 -79
- package/dist/load-config-qC2BWt8E.js +0 -35
- package/dist/local-dispatch.runtime-DyU7urGc.js +0 -8
- package/dist/logs-cli-zK71r_PE.js +0 -265
- package/dist/logs-cli.runtime-k0UtiaRP.js +0 -2
- package/dist/main-session-restart-recovery-DMT0Oj9a.js +0 -206
- package/dist/managed-image-attachments-B6XXE4--.js +0 -635
- package/dist/managed-image-attachments-BTzWoDWE.js +0 -2
- package/dist/manager-BCKuWA67.js +0 -2057
- package/dist/manager-rGwNUzMp.js +0 -2
- package/dist/markdown-to-line-DmPbXQA1.js +0 -790
- package/dist/mcp-cli-CYpPNMcE.js +0 -725
- package/dist/mcp-http-wiE81iKg.js +0 -529
- package/dist/memory-core-host-runtime-cli-BOSQRX1T.js +0 -9
- package/dist/message-CUDzVGD8.js +0 -232
- package/dist/message-action-runner-Dy0IpKa4.js +0 -1407
- package/dist/message-action-runner-KkBFzZdg.js +0 -2
- package/dist/message-actions-Dcdb5aSR.js +0 -143
- package/dist/message.gateway.runtime-D86fFO99.js +0 -2
- package/dist/models-auth-status-DkiX4s0b.js +0 -201
- package/dist/models-cli-CSUot1R3.js +0 -219
- package/dist/monitor-BA8ByMKR.js +0 -2
- package/dist/monitor-Bv1GIHW5.js +0 -1661
- package/dist/monitor-DTFY0ruF.js +0 -788
- package/dist/monitor-DXH-vNGn.js +0 -1459
- package/dist/monitor-Df5k8NGk.js +0 -671
- package/dist/monitor-Dk2YRF26.js +0 -1237
- package/dist/monitor-auth-CZOW753A.js +0 -207
- package/dist/monitor-processing-Clta8N4C.js +0 -1974
- package/dist/monitor.runtime-3ORbPT0X.js +0 -2
- package/dist/monitor.webhook-CRyTxENk.js +0 -180
- package/dist/msteams-BE0VieXF.js +0 -35
- package/dist/native-hook-relay-DAwGGuEx.js +0 -519
- package/dist/nextcloud-talk-DfYlTFsm.js +0 -17
- package/dist/node-cli-Bzyci_X_.js +0 -2276
- package/dist/nodes-cli-Er3OZkuk.js +0 -1046
- package/dist/nodes-utils-Cp8QZO8-.js +0 -84
- package/dist/nodes.helpers-CwKAAnRA.js +0 -34
- package/dist/notify-D_5n_vEJ.js +0 -315
- package/dist/onboard-BE82RudQ.js +0 -2
- package/dist/onboard-Bk4xL8X7.js +0 -70
- package/dist/onboard-helpers-D4WYa-6g.js +0 -204
- package/dist/onboard-helpers-MuFxPZg5.js +0 -6
- package/dist/onboard-interactive-0zmI-9ia.js +0 -24
- package/dist/onboard-non-interactive-DIRB95mT.js +0 -635
- package/dist/onboard-remote-7qR1knbU.js +0 -2
- package/dist/onboard-remote-CLmoySkk.js +0 -193
- package/dist/onboard-skills-C_873OK_.js +0 -134
- package/dist/onboard-skills-DrlBYc0t.js +0 -2
- package/dist/openai-http-DzCBqW6b.js +0 -500
- package/dist/openresponses-http-B2zgO5hQ.js +0 -1128
- package/dist/operator-approvals-client-mGBl4ptH.js +0 -68
- package/dist/outbound.runtime--HS-MxM_.js +0 -2
- package/dist/pair-command-approve-CCTSQKJH.js +0 -44
- package/dist/persistent-bindings.lifecycle-CnmqGsQf.js +0 -85
- package/dist/persistent-bindings.lifecycle-Dav1TX9E.js +0 -2
- package/dist/pi-embedded-BSKL8IgF.js +0 -4
- package/dist/pi-embedded-DMM8Pfp7.js +0 -2905
- package/dist/pi-embedded.runtime-Bv_roBVx.js +0 -4
- package/dist/pi-tool-definition-adapter-OrxjlSIM.js +0 -229
- package/dist/pi-tools-DD1YegeL.js +0 -1057
- package/dist/pi-tools.before-tool-call-J9ujp9Wp.js +0 -433
- package/dist/pi-tools.before-tool-call-hGEgKGZQ.js +0 -2
- package/dist/plugin-Cg3pHepG.js +0 -12195
- package/dist/plugin-enabled-wEQ8BQNw.js +0 -140
- package/dist/plugin-registration-DLcLJgqz.js +0 -23
- package/dist/plugin-service-BogBl5qk.js +0 -2892
- package/dist/policy-Bkh8Xtnb.js +0 -328
- package/dist/prepare.runtime-Cd31ie7u.js +0 -815
- package/dist/probe-9IM22Rkf.js +0 -2
- package/dist/probe-ButCyV3d.js +0 -1443
- package/dist/probe-D7QBUio1.js +0 -45
- package/dist/probe-DV6CWm0r.js +0 -74
- package/dist/probe-DkfetvwA.js +0 -2
- package/dist/probe-Dxo-LQjn.js +0 -2205
- package/dist/probe-nil3qQAV.js +0 -241
- package/dist/program-AcjZFtZQ.js +0 -111
- package/dist/prompt-select-styled-BSf77q2T.js +0 -20
- package/dist/protocol-C4I0nfuT.js +0 -2477
- package/dist/provider-dispatcher-CkiPxKIr.js +0 -22
- package/dist/provider-dispatcher-PmsHJlUO.js +0 -2
- package/dist/qr-cli-BHY0TO2W.js +0 -2
- package/dist/qr-cli-BbjDJSKp.js +0 -349
- package/dist/reaction-runtime-api-DOigJrbq.js +0 -116
- package/dist/reactions-CogkrjNr.js +0 -998
- package/dist/register-service-commands-IA3Nfza5.js +0 -71
- package/dist/register.agent-DD0aSYye.js +0 -248
- package/dist/register.configure-BOy4i7Ah.js +0 -15
- package/dist/register.maintenance-CUp6FEOF.js +0 -363
- package/dist/register.message-DezTIpNI.js +0 -329
- package/dist/register.onboard-Brpxl9p3.js +0 -88
- package/dist/register.runtime-BfH5rSb_.js +0 -81
- package/dist/register.setup-CIt4FVv0.js +0 -150
- package/dist/register.status-health-sessions-IbGZwSaG.js +0 -1215
- package/dist/register.subclis-B1H4fYxP.js +0 -29
- package/dist/register.subclis-D-_xtNVs.js +0 -3
- package/dist/register.subclis-core-CkJelRU8.js +0 -249
- package/dist/reply-dispatch-runtime-Lu4Metex.js +0 -13
- package/dist/reply-runtime-CgPzru94.js +0 -11
- package/dist/reply.runtime-sw14BA5F.js +0 -2
- package/dist/restart-health-1MNBua3p.js +0 -202
- package/dist/restart-health-BWGpwgPv.js +0 -2
- package/dist/root-help-B3zoC2OP.js +0 -44
- package/dist/routes-BM6fbday.js +0 -3341
- package/dist/routes-pVc_QLiP.js +0 -2
- package/dist/rpc-BGOWS7nj.js +0 -61
- package/dist/rpc.runtime-Ca9K3sx8.js +0 -21
- package/dist/run-delivery.runtime-CabntI64.js +0 -530
- package/dist/run-embedded.runtime-Q7wrP6Qn.js +0 -4
- package/dist/run-execution-cli.runtime-CtRUFc-M.js +0 -4
- package/dist/run-executor.runtime-Nm38xsKA.js +0 -277
- package/dist/run-main-kE0nFgvK.js +0 -567
- package/dist/run-subagent-registry.runtime-D9_scMUr.js +0 -2
- package/dist/run-wait-B2K_6JNL.js +0 -135
- package/dist/runtime-BZ296jTK.js +0 -9
- package/dist/runtime-DnZsw7MB.js +0 -973
- package/dist/runtime-api-BL9vpbvb.js +0 -14
- package/dist/runtime-api-BbsLJB4C.js +0 -9
- package/dist/runtime-api-ChwFrQRw.js +0 -9
- package/dist/runtime-api-_fH7M3Qh.js +0 -4
- package/dist/runtime-embedded-pi.runtime-TOdW-E-2.js +0 -2
- package/dist/runtime-internal-DGwOFi_E.js +0 -2
- package/dist/runtime-options-CSPfxkb1.js +0 -275
- package/dist/runtime-schema-CMRvOPkk.js +0 -28576
- package/dist/scan-D6gkNpKl.js +0 -523
- package/dist/scan-_9J5-5L6.js +0 -2
- package/dist/secrets-cli-DlVSRQPM.js +0 -2101
- package/dist/security-cli-DtzNOYL2.js +0 -486
- package/dist/selection-CBJZE_FL.js +0 -7764
- package/dist/selection-XsoEF2p2.js +0 -2
- package/dist/send-BAaDBRfi.js +0 -156
- package/dist/send-BB-M1afy.js +0 -102
- package/dist/send.runtime-CI_75KUP.js +0 -2
- package/dist/server-B_BiVYFv.js +0 -13
- package/dist/server-D58E1Cua.js +0 -77
- package/dist/server-context-D5AnCc1E.js +0 -2
- package/dist/server-context-bt09wrJu.js +0 -847
- package/dist/server-node-events-CUx4-7FL.js +0 -481
- package/dist/server-plugin-bootstrap-CU5P500z.js +0 -12708
- package/dist/server-plugin-bootstrap-CXm9xWXR.js +0 -2
- package/dist/server-restart-sentinel-ByFI_0MB.js +0 -697
- package/dist/server.impl-BBBEDK9u.js +0 -12864
- package/dist/session-kill-http-9MoO6FXC.js +0 -110
- package/dist/session-reset-service-redPsOs-.js +0 -497
- package/dist/session-route-C8oB2UYs.js +0 -93
- package/dist/session-status.runtime-D3bYBPJe.js +0 -2
- package/dist/session-subagent-reactivation.runtime-aat7tUag.js +0 -2
- package/dist/session-tab-registry-CAJ_oDsb.js +0 -581
- package/dist/session-visibility-Dq88jJYB.js +0 -147
- package/dist/sessions-helpers-C8-IkqhO.js +0 -305
- package/dist/sessions-history-http-4Ftuwnes.js +0 -383
- package/dist/sessions-patch-BsyNHOaz.js +0 -309
- package/dist/sessions-resolve-gKLz2Bup.js +0 -174
- package/dist/sessions.runtime-C1W59rQY.js +0 -2
- package/dist/setup-DhvXyU_5.js +0 -636
- package/dist/setup-api-B9Y4qPgq.js +0 -29
- package/dist/setup-core-CdFQ6ZXC.js +0 -176
- package/dist/setup-core-kXUD3Kat.js +0 -171
- package/dist/setup-surface-BFL9WfBs.js +0 -219
- package/dist/setup-surface-Cxg_nSWc.js +0 -286
- package/dist/setup-surface-DbooMj782.js +0 -403
- package/dist/setup.finalize-CKxukDYi.js +0 -547
- package/dist/setup.gateway-config-BhEtXwaB.js +0 -250
- package/dist/shared-BNVKrp5y.js +0 -76
- package/dist/shared-CM3mnx7z.js +0 -198
- package/dist/shared-CfrsSVhL.js +0 -121
- package/dist/slash-state-2Z-om57Q.js +0 -1911
- package/dist/src-DAoKvK_N.js +0 -3974
- package/dist/startup-context-CtYAdYwd.js +0 -312
- package/dist/status-B2M0Imij.js +0 -3
- package/dist/status-Bd-BNmiE.js +0 -2
- package/dist/status-D6nbpHFi.js +0 -397
- package/dist/status-MByUxUGu.js +0 -209
- package/dist/status-QUjO1tkz.js +0 -2
- package/dist/status-all-DPa-BiHk.js +0 -498
- package/dist/status-erNo8YmW.js +0 -190
- package/dist/status-json-command-C9rbAyj-.js +0 -84
- package/dist/status-json-tO3CQXIQ.js +0 -14
- package/dist/status-runtime-shared-DmBB_gmT.js +0 -257
- package/dist/status-subagents.runtime-BXAZr5y0.js +0 -18
- package/dist/status-text-BCeYk0-q.js +0 -237
- package/dist/status.gateway-connection.runtime-bt35dapy.js +0 -2
- package/dist/status.gather-B9a-CEev.js +0 -292
- package/dist/status.gather-ahBLFzk6.js +0 -2
- package/dist/status.runtime-BrErwtfc.js +0 -2
- package/dist/status.scan-D2mvM4II.js +0 -65
- package/dist/status.scan-overview-uOOaqp1t.js +0 -379
- package/dist/status.scan.fast-json-C9dkN28s.js +0 -2
- package/dist/status.scan.fast-json-DY3Or8S4.js +0 -132
- package/dist/status.summary-Cf4p2BPK.js +0 -2
- package/dist/status.summary-DxfZCcNa.js +0 -214
- package/dist/subagent-announce-CyQZsAIm.js +0 -351
- package/dist/subagent-announce-delivery-CgdPNjMA.js +0 -726
- package/dist/subagent-announce-output-D1xi4Tk1.js +0 -364
- package/dist/subagent-control-D-O6I8Mt.js +0 -506
- package/dist/subagent-followup.runtime-BbA7NPAq.js +0 -68
- package/dist/subagent-orphan-recovery-C6_cmAyE.js +0 -305
- package/dist/subagent-registry-Dn_XpDh0.js +0 -1753
- package/dist/subagent-registry-DodFw3pu.js +0 -3
- package/dist/subagent-spawn-Dw5lttXp.js +0 -1005
- package/dist/system-cli-CSqO2Z4K.js +0 -59
- package/dist/targets-CMdwh9lR.js +0 -67
- package/dist/task-executor-DgZSfcBk.js +0 -360
- package/dist/task-owner-access-9c38idlo.js +0 -74
- package/dist/task-registry-Z-lBPkNj.js +0 -2366
- package/dist/task-registry-delivery-runtime-DOV4qoj4.js +0 -2
- package/dist/task-registry-delivery-runtime-EATr0C3C.js +0 -3
- package/dist/task-registry.maintenance-C1YMEwhk.js +0 -416
- package/dist/task-registry.maintenance-CBfaUWcp.js +0 -2
- package/dist/testing-CFk04o9M.js +0 -575
- package/dist/text-report-QhVG354o.js +0 -587
- package/dist/tool-resolution-D6V4tg-G.js +0 -90
- package/dist/tools-effective-inventory-DFU7yYvD.js +0 -152
- package/dist/tools-invoke-http-y6WIa3Ku.js +0 -206
- package/dist/trash-rhbwNhfQ.js +0 -24
- package/dist/tui-cli-BfxeO4YM.js +0 -4575
- package/dist/update-cli-DaN9bvPV.js +0 -1759
- package/dist/upgrade-f5dlIxir.js +0 -1226
- package/dist/video-generation-task-status-yX54iO8n.js +0 -163
- package/dist/wait-for-idle-before-flush-mZrBNr5z.js +0 -5986
- package/dist/wizard-models-D_avLyHR.js +0 -334
|
@@ -0,0 +1,4599 @@
|
|
|
1
|
+
import { i as formatErrorMessage } from "./errors-CufR9eHH.js";
|
|
2
|
+
import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString, i as normalizeFastMode, s as normalizeOptionalLowercaseString } from "./string-coerce-DPP_aYVc.js";
|
|
3
|
+
import { m as resolveUserPath, r as clampInt } from "./utils-CWrkFsp0.js";
|
|
4
|
+
import { _ as resolveStateDir } from "./paths-Bv2rGpO9.js";
|
|
5
|
+
import { r as logVerbose } from "./globals-wYf9_gv5.js";
|
|
6
|
+
import { s as normalizeStringEntries } from "./string-normalization-Bsx26hdl.js";
|
|
7
|
+
import { a as clearPluginManifestRegistryCache } from "./manifest-registry-CUSRRX5s.js";
|
|
8
|
+
import { E as validateConfigObjectWithPlugins, F as setConfigOverride, I as unsetConfigOverride, N as getConfigOverrides, P as resetConfigOverrides, u as readConfigFileSnapshot, y as writeConfigFile } from "./io-B1sv_bx7.js";
|
|
9
|
+
import { r as normalizeOptionalAccountId } from "./account-id-CTXHUezn.js";
|
|
10
|
+
import { u as resolveAgentIdFromSessionKey } from "./session-key-Cj8Hd5K-.js";
|
|
11
|
+
import { o as normalizeChannelId } from "./registry-CdBbOzac.js";
|
|
12
|
+
import { i as normalizeChannelId$1, t as getChannelPlugin } from "./registry-BFggBDHn.js";
|
|
13
|
+
import { i as unsetConfigValueAtPath, n as parseConfigPath, r as setConfigValueAtPath, t as getConfigValueAtPath } from "./config-paths-s_8tbgaF.js";
|
|
14
|
+
import { b as resolveAgentWorkspaceDir, p as resolveSessionAgentId, y as resolveAgentDir } from "./agent-scope-Duyu_T59.js";
|
|
15
|
+
import { t as parseDurationMs } from "./parse-duration-CkHLPGPv.js";
|
|
16
|
+
import { n as isMcpCommandEnabled, r as isRestartEnabled, t as isCommandFlagEnabled } from "./commands.flags-CIvSlgUV.js";
|
|
17
|
+
import "./config-Cuf4dwjh.js";
|
|
18
|
+
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-DZtBR4jU.js";
|
|
19
|
+
import { r as isInternalMessageChannel, u as normalizeMessageChannel } from "./message-channel-bhWoqTRw.js";
|
|
20
|
+
import { n as resolveChannelApprovalCapability } from "./plugins-jnza8oZ-.js";
|
|
21
|
+
import { m as triggerInternalHook, n as createInternalHookEvent } from "./internal-hooks-NxTc8JXb.js";
|
|
22
|
+
import { x as prepareProviderRuntimeAuth } from "./provider-runtime-Bfrieldi.js";
|
|
23
|
+
import { t as ensureGenesisModelsJson } from "./models-config-OmJAbUii.js";
|
|
24
|
+
import { g as resolveResponseUsageMode, m as normalizeUsageDisplay } from "./thinking-ItWMrRTh.js";
|
|
25
|
+
import { t as requireApiKey } from "./model-auth-runtime-shared-Czq1-Ajx.js";
|
|
26
|
+
import { i as discoverModels, r as discoverAuthStorage } from "./pi-model-discovery-CRKskb2u.js";
|
|
27
|
+
import { a as resolveSessionFilePathOptions, i as resolveSessionFilePath, r as resolveDefaultSessionStorePath } from "./paths-CV1IubzZ.js";
|
|
28
|
+
import { t as loadSessionStore } from "./store-load-CZTVJ-lZ.js";
|
|
29
|
+
import { o as resolveFreshSessionTotalTokens } from "./types-DhjMRs-U.js";
|
|
30
|
+
import { o as updateSessionStore } from "./store-4uu5L7Eg.js";
|
|
31
|
+
import { t as extractDeliveryInfo } from "./sessions-qbJQTdke.js";
|
|
32
|
+
import { i as formatUsd, r as formatTokenCount } from "./usage-format-DFAQjLOq.js";
|
|
33
|
+
import { n as stripInboundMetadata } from "./strip-inbound-meta-CQZop7I_.js";
|
|
34
|
+
import { t as diagnosticLogger } from "./diagnostic-runtime-BUG34enQ.js";
|
|
35
|
+
import { n as redactSupportString } from "./diagnostic-support-redaction-CSXpfKpo.js";
|
|
36
|
+
import { C as safeJsonStringify, S as safeTrajectorySessionFileName, b as resolveTrajectoryFilePath, w as sanitizeDiagnosticPayload, x as resolveTrajectoryPointerFilePath, y as TRAJECTORY_RUNTIME_FILE_MAX_BYTES } from "./selection-CqqmU0Hi.js";
|
|
37
|
+
import { S as setTtsProvider, _ as setLastTtsAttempt, a as getTtsMaxLength, b as setTtsEnabled, c as isTtsEnabled, h as resolveTtsPrefsPath, i as getResolvedSpeechProviderConfig, l as isTtsProviderConfigured, m as resolveTtsConfig, o as getTtsProvider, r as getLastTtsAttempt, s as isSummarizationEnabled, v as setSummarizationEnabled, w as textToSpeech, x as setTtsMaxLength } from "./tts-Dk_Qpk02.js";
|
|
38
|
+
import { t as analyzeBootstrapBudget } from "./bootstrap-budget-AwPM5SCG.js";
|
|
39
|
+
import { h as resolveBootstrapTotalMaxChars, p as resolveBootstrapMaxChars } from "./pi-embedded-helpers-DGOg4B7z.js";
|
|
40
|
+
import { n as resolveSandboxRuntimeStatus } from "./runtime-status-D1e_kpiA.js";
|
|
41
|
+
import { i as resolveImageSanitizationLimits, n as sanitizeImageBlocks } from "./tool-images-F6n-h6v3.js";
|
|
42
|
+
import { r as getApiKeyForModel } from "./model-auth-BwQ1st1y.js";
|
|
43
|
+
import { t as registerProviderStreamForModel } from "./provider-stream-DgJKq2ph.js";
|
|
44
|
+
import { m as stripToolResultDetails } from "./transport-stream-shared-CPOJy5ri.js";
|
|
45
|
+
import { i as unsetConfiguredMcpServer, r as setConfiguredMcpServer, t as listConfiguredMcpServers } from "./mcp-config-Dl2DPxNG.js";
|
|
46
|
+
import { t as EmbeddedBlockChunker } from "./pi-embedded-block-chunker-B5DAl_Mk.js";
|
|
47
|
+
import { r as callGateway } from "./call-wY43fzOF.js";
|
|
48
|
+
import { d as writeRestartSentinel, n as buildRestartSuccessContinuation, r as formatDoctorNonInteractiveHint, s as removeRestartSentinelFile } from "./restart-sentinel-BWLOu2lg.js";
|
|
49
|
+
import { l as triggerGenesisRestart, o as scheduleGatewaySigusr1Restart } from "./restart-BFDbf3pm.js";
|
|
50
|
+
import { i as resolveReplyToMode } from "./reply-threading-HxCeZwbf.js";
|
|
51
|
+
import { _ as authorizeConfigWriteShared, b as resolveConfigWriteTargetFromPathShared, v as canBypassConfigWritePolicyShared, y as formatConfigWriteDeniedMessageShared } from "./channel-config-helpers-9w5_d8wL.js";
|
|
52
|
+
import { n as formatTaskStatusDetail, r as formatTaskStatusTitle, t as buildTaskStatusSnapshot } from "./task-status-DPdgYJLA.js";
|
|
53
|
+
import { a as clearSessionQueues } from "./queue-CAzzFO21.js";
|
|
54
|
+
import { r as getSessionBindingService } from "./session-binding-service-UsMQYRwd.js";
|
|
55
|
+
import { h as replyRunRegistry, i as getActiveEmbeddedRunSnapshot } from "./runs-B8F_WpB_.js";
|
|
56
|
+
import "./diagnostic-DWbnEbdj.js";
|
|
57
|
+
import { t as formatDurationCompact } from "./format-duration-FMBoWUPM.js";
|
|
58
|
+
import "./sandbox-Bz5RkkUC.js";
|
|
59
|
+
import { t as buildSystemPromptReport } from "./system-prompt-report-Od6CKNNx.js";
|
|
60
|
+
import { n as estimateTokensFromChars } from "./cjk-chars-XdqLsEKS.js";
|
|
61
|
+
import { i as streamWithPayloadPatch } from "./moonshot-thinking-stream-wrappers-BfVsvTBX.js";
|
|
62
|
+
import { r as resolveModelWithRegistry } from "./model-gCK0R8Nc.js";
|
|
63
|
+
import { i as matchPluginCommand, n as executePluginCommand } from "./commands-DOsvNyGY.js";
|
|
64
|
+
import { t as isApprovalNotFoundError } from "./approval-errors-DRLdl7Rx.js";
|
|
65
|
+
import { r as normalizeCommandBody } from "./commands-registry-normalize-y3pw00Jl.js";
|
|
66
|
+
import { i as setAbortMemory, r as isAbortTrigger } from "./abort-primitives-iywT5nzF.js";
|
|
67
|
+
import "./commands-registry-vIVRcWI1.js";
|
|
68
|
+
import { n as formatTimeAgo } from "./format-relative-CkCeIUFz.js";
|
|
69
|
+
import { o as stripMentions, s as stripStructuralPrefixes } from "./mentions-C-JNJVfc.js";
|
|
70
|
+
import { n as setChannelConversationBindingMaxAgeBySessionKey, t as setChannelConversationBindingIdleTimeoutBySessionKey } from "./conversation-bindings-BLkcLryd.js";
|
|
71
|
+
import { a as readChannelAllowFromStore, l as removeChannelAllowFromStoreEntry, t as addChannelAllowFromStoreEntry } from "./pairing-store-CpOJU8_T.js";
|
|
72
|
+
import { i as installPluginFromPath, r as installPluginFromNpmSpec } from "./install-DHeEjbGx.js";
|
|
73
|
+
import { l as resolveArchiveKind } from "./archive-DQTlkN3s.js";
|
|
74
|
+
import { n as isImplicitSameChatApprovalAuthorization } from "./approval-auth-helpers-yVj8aTGb.js";
|
|
75
|
+
import { n as parseActivationCommand } from "./group-activation-C-Ka3ubh.js";
|
|
76
|
+
import { t as resolveFastModeState } from "./fast-mode-Wj1tPkPb.js";
|
|
77
|
+
import { n as resolveSessionAuthProfileOverride } from "./session-override-DeW6phDW.js";
|
|
78
|
+
import { n as extractExplicitGroupId, t as formatElevatedUnavailableMessage } from "./elevated-unavailable-D_F1Qi1Z.js";
|
|
79
|
+
import { t as resolveRuntimePolicySessionKey } from "./runtime-policy-session-key-C4bUGX5a.js";
|
|
80
|
+
import { a as shouldPersistAbortCutoff, i as resolveAbortCutoffFromContext, t as applyAbortCutoffToSessionEntry } from "./abort-cutoff-DKNuhGko.js";
|
|
81
|
+
import { t as resolveEffectiveToolInventory } from "./tools-effective-inventory-Bo2QC-m8.js";
|
|
82
|
+
import { r as resolveConversationBindingContextFromAcpCommand } from "./conversation-binding-input-CUHe8TjG.js";
|
|
83
|
+
import { n as resolveSessionEntryForKey, r as stopSubagentsForRequester, t as formatAbortReplyText } from "./abort-CcNxEsSq.js";
|
|
84
|
+
import { t as extractBtwQuestion } from "./btw-command-rpRDk_2S.js";
|
|
85
|
+
import { t as formatThreadBindingDurationLabel } from "./thread-bindings-messages-5WoR01mB.js";
|
|
86
|
+
import { n as getSpeechProvider, r as listSpeechProviders, t as canonicalizeSpeechProviderId } from "./provider-registry-Dn8In2oK.js";
|
|
87
|
+
import { a as requireGatewayClientScopeForInternalChannel, i as requireCommandFlagEnabled, n as rejectNonOwnerCommand, r as rejectUnauthorizedCommand, t as buildDisabledCommandReply } from "./command-gates-BCh2pNFa.js";
|
|
88
|
+
import { t as handleAcpCommand } from "./commands-acp-C_zCJPvL.js";
|
|
89
|
+
import { n as buildCommandsMessagePaginated, r as buildHelpMessage, t as buildCommandsMessage } from "./command-status-builders-BLoK6pFx.js";
|
|
90
|
+
import { _ as getFinishedSession, v as getSession } from "./bash-tools.exec-runtime-C3ZPwutq.js";
|
|
91
|
+
import { t as listSkillCommandsForAgents } from "./skill-commands-CI-8S2Ep.js";
|
|
92
|
+
import { r as handleModelsCommand } from "./commands-models-IFPI_KE4.js";
|
|
93
|
+
import { n as setPluginEnabledInConfig } from "./enable-DnHQsOLE.js";
|
|
94
|
+
import { r as createExecTool } from "./bash-tools-tnj1gSbO.js";
|
|
95
|
+
import { n as listTasksForAgentIdForStatus, r as listTasksForSessionKeyForStatus } from "./status-text-BdbRrl1G.js";
|
|
96
|
+
import { n as buildThreadingToolContext } from "./agent-runner-utils-CX2vCMkx.js";
|
|
97
|
+
import { d as resolveChannelAccountId, f as resolveCommandSurfaceChannel, l as resolveSubagentsAction, o as resolveHandledPrefix, s as resolveRequesterSessionKey, u as stopWithText } from "./shared-C8ENgtxM.js";
|
|
98
|
+
import { t as buildToolsMessage } from "./status-CSqsbzr9.js";
|
|
99
|
+
import { t as parseConfigValue } from "./config-value-C_c-ZB8y.js";
|
|
100
|
+
import { t as resolveCommandsSystemPromptBundle } from "./commands-system-prompt-B7moUaCI.js";
|
|
101
|
+
import { a as writeSupportBundleDirectory, i as textSupportBundleFile, n as jsonlSupportBundleFile, r as supportBundleContents, t as jsonSupportBundleFile } from "./diagnostic-support-bundle-icLsUzJJ.js";
|
|
102
|
+
import { t as buildStatusReply } from "./commands-status-BgZ64sA8.js";
|
|
103
|
+
import { i as buildNpmInstallRecordFields, n as persistPluginInstall } from "./plugins-install-persist-CcddHpDG.js";
|
|
104
|
+
import { h as parseClawHubPluginSpec } from "./clawhub-CEuxg1D3.js";
|
|
105
|
+
import { r as installPluginFromClawHub } from "./clawhub-DjVm1ncS.js";
|
|
106
|
+
import { a as buildPluginDiagnosticsReport, c as formatPluginCompatibilityNotice, o as buildPluginInspectReport, s as buildPluginSnapshotReport, t as buildAllPluginInspectReports } from "./status-CChLT1a9.js";
|
|
107
|
+
import { a as decidePreferredClawHubFallback, i as createPluginInstallLogger, n as buildPreferredClawHubSpec, u as resolveFileNpmSpecToLocalPath } from "./plugins-command-helpers-CX675QmU.js";
|
|
108
|
+
import { n as loadCostUsageSummary, r as loadSessionCostSummary } from "./session-cost-usage-CbJsMKMd.js";
|
|
109
|
+
import { fileURLToPath } from "node:url";
|
|
110
|
+
import fs from "node:fs";
|
|
111
|
+
import path from "node:path";
|
|
112
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
113
|
+
import { streamSimple } from "@earendil-works/pi-ai";
|
|
114
|
+
//#region src/channels/plugins/config-writes.ts
|
|
115
|
+
function isInternalConfigWriteMessageChannel(channel) {
|
|
116
|
+
return normalizeLowercaseStringOrEmpty(channel) === "webchat";
|
|
117
|
+
}
|
|
118
|
+
function authorizeConfigWrite(params) {
|
|
119
|
+
return authorizeConfigWriteShared(params);
|
|
120
|
+
}
|
|
121
|
+
function resolveConfigWriteTargetFromPath(path) {
|
|
122
|
+
return resolveConfigWriteTargetFromPathShared({
|
|
123
|
+
path,
|
|
124
|
+
normalizeChannelId: (raw) => normalizeLowercaseStringOrEmpty(raw)
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
function canBypassConfigWritePolicy(params) {
|
|
128
|
+
return canBypassConfigWritePolicyShared({
|
|
129
|
+
...params,
|
|
130
|
+
isInternalMessageChannel: isInternalConfigWriteMessageChannel
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
function formatConfigWriteDeniedMessage(params) {
|
|
134
|
+
return formatConfigWriteDeniedMessageShared(params);
|
|
135
|
+
}
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region src/auto-reply/reply/config-write-authorization.ts
|
|
138
|
+
function resolveConfigWriteDeniedText(params) {
|
|
139
|
+
const writeAuth = authorizeConfigWrite({
|
|
140
|
+
cfg: params.cfg,
|
|
141
|
+
origin: {
|
|
142
|
+
channelId: params.channelId,
|
|
143
|
+
accountId: params.accountId
|
|
144
|
+
},
|
|
145
|
+
target: params.target,
|
|
146
|
+
allowBypass: canBypassConfigWritePolicy({
|
|
147
|
+
channel: params.channel ?? "",
|
|
148
|
+
gatewayClientScopes: params.gatewayClientScopes
|
|
149
|
+
})
|
|
150
|
+
});
|
|
151
|
+
if (writeAuth.allowed) return null;
|
|
152
|
+
return formatConfigWriteDeniedMessage({
|
|
153
|
+
result: writeAuth,
|
|
154
|
+
fallbackChannelId: params.channelId
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/auto-reply/reply/commands-allowlist.ts
|
|
159
|
+
const ACTIONS = new Set([
|
|
160
|
+
"list",
|
|
161
|
+
"add",
|
|
162
|
+
"remove"
|
|
163
|
+
]);
|
|
164
|
+
const SCOPES = new Set([
|
|
165
|
+
"dm",
|
|
166
|
+
"group",
|
|
167
|
+
"all"
|
|
168
|
+
]);
|
|
169
|
+
function resolveAllowlistAccountId(params) {
|
|
170
|
+
const explicitAccountId = normalizeOptionalAccountId(params.parsedAccount);
|
|
171
|
+
if (explicitAccountId) return explicitAccountId;
|
|
172
|
+
const configuredDefaultAccountId = normalizeOptionalString(getChannelPlugin(params.channelId)?.config.defaultAccountId?.(params.cfg));
|
|
173
|
+
const ctxAccountId = normalizeOptionalAccountId(params.ctxAccountId);
|
|
174
|
+
return configuredDefaultAccountId || ctxAccountId || "default";
|
|
175
|
+
}
|
|
176
|
+
function parseAllowlistCommand(raw) {
|
|
177
|
+
const trimmed = raw.trim();
|
|
178
|
+
if (!(normalizeOptionalLowercaseString(trimmed) ?? "").startsWith("/allowlist")) return null;
|
|
179
|
+
const rest = trimmed.slice(10).trim();
|
|
180
|
+
if (!rest) return {
|
|
181
|
+
action: "list",
|
|
182
|
+
scope: "dm"
|
|
183
|
+
};
|
|
184
|
+
const tokens = rest.split(/\s+/);
|
|
185
|
+
let action = "list";
|
|
186
|
+
let scope = "dm";
|
|
187
|
+
let resolve = false;
|
|
188
|
+
let target = "both";
|
|
189
|
+
let channel;
|
|
190
|
+
let account;
|
|
191
|
+
const entryTokens = [];
|
|
192
|
+
let i = 0;
|
|
193
|
+
const firstAction = normalizeOptionalLowercaseString(tokens[i]);
|
|
194
|
+
if (firstAction && ACTIONS.has(firstAction)) {
|
|
195
|
+
action = firstAction;
|
|
196
|
+
i += 1;
|
|
197
|
+
}
|
|
198
|
+
const firstScope = normalizeOptionalLowercaseString(tokens[i]);
|
|
199
|
+
if (firstScope && SCOPES.has(firstScope)) {
|
|
200
|
+
scope = firstScope;
|
|
201
|
+
i += 1;
|
|
202
|
+
}
|
|
203
|
+
for (; i < tokens.length; i += 1) {
|
|
204
|
+
const token = tokens[i];
|
|
205
|
+
const lowered = normalizeOptionalLowercaseString(token) ?? "";
|
|
206
|
+
if (lowered === "--resolve" || lowered === "resolve") {
|
|
207
|
+
resolve = true;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (lowered === "--config" || lowered === "config") {
|
|
211
|
+
target = "config";
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (lowered === "--store" || lowered === "store") {
|
|
215
|
+
target = "store";
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (lowered === "--channel" && tokens[i + 1]) {
|
|
219
|
+
channel = tokens[i + 1];
|
|
220
|
+
i += 1;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (lowered === "--account" && tokens[i + 1]) {
|
|
224
|
+
account = tokens[i + 1];
|
|
225
|
+
i += 1;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
const kv = token.split("=");
|
|
229
|
+
if (kv.length === 2) {
|
|
230
|
+
const key = normalizeOptionalLowercaseString(kv[0]);
|
|
231
|
+
const value = normalizeOptionalString(kv[1]);
|
|
232
|
+
if (key === "channel") {
|
|
233
|
+
if (value) channel = value;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (key === "account") {
|
|
237
|
+
if (value) account = value;
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
const normalizedValue = normalizeOptionalLowercaseString(value);
|
|
241
|
+
if (key === "scope" && normalizedValue && SCOPES.has(normalizedValue)) {
|
|
242
|
+
scope = normalizedValue;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
entryTokens.push(token);
|
|
247
|
+
}
|
|
248
|
+
if (action === "add" || action === "remove") {
|
|
249
|
+
const entry = entryTokens.join(" ").trim();
|
|
250
|
+
if (!entry) return {
|
|
251
|
+
action: "error",
|
|
252
|
+
message: "Usage: /allowlist add|remove <entry>"
|
|
253
|
+
};
|
|
254
|
+
return {
|
|
255
|
+
action,
|
|
256
|
+
scope,
|
|
257
|
+
entry,
|
|
258
|
+
channel,
|
|
259
|
+
account,
|
|
260
|
+
resolve,
|
|
261
|
+
target
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
action: "list",
|
|
266
|
+
scope,
|
|
267
|
+
channel,
|
|
268
|
+
account,
|
|
269
|
+
resolve
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
function normalizeAllowFrom(params) {
|
|
273
|
+
const plugin = getChannelPlugin(params.channelId);
|
|
274
|
+
if (plugin?.config.formatAllowFrom) return plugin.config.formatAllowFrom({
|
|
275
|
+
cfg: params.cfg,
|
|
276
|
+
accountId: params.accountId,
|
|
277
|
+
allowFrom: params.values
|
|
278
|
+
});
|
|
279
|
+
return normalizeStringEntries(params.values);
|
|
280
|
+
}
|
|
281
|
+
function formatEntryList(entries, resolved) {
|
|
282
|
+
if (entries.length === 0) return "(none)";
|
|
283
|
+
return entries.map((entry) => {
|
|
284
|
+
const name = resolved?.get(entry);
|
|
285
|
+
return name ? `${entry} (${name})` : entry;
|
|
286
|
+
}).join(", ");
|
|
287
|
+
}
|
|
288
|
+
async function updatePairingStoreAllowlist(params) {
|
|
289
|
+
const storeEntry = {
|
|
290
|
+
channel: params.channelId,
|
|
291
|
+
entry: params.entry,
|
|
292
|
+
accountId: params.accountId
|
|
293
|
+
};
|
|
294
|
+
if (params.action === "add") {
|
|
295
|
+
await addChannelAllowFromStoreEntry(storeEntry);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
await removeChannelAllowFromStoreEntry(storeEntry);
|
|
299
|
+
if (params.accountId === "default") await removeChannelAllowFromStoreEntry({
|
|
300
|
+
channel: params.channelId,
|
|
301
|
+
entry: params.entry
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
function mapResolvedAllowlistNames(entries) {
|
|
305
|
+
const map = /* @__PURE__ */ new Map();
|
|
306
|
+
for (const entry of entries) if (entry.resolved && entry.name) map.set(entry.input, entry.name);
|
|
307
|
+
return map;
|
|
308
|
+
}
|
|
309
|
+
async function resolveAllowlistNames(params) {
|
|
310
|
+
return mapResolvedAllowlistNames(await getChannelPlugin(params.channelId)?.allowlist?.resolveNames?.({
|
|
311
|
+
cfg: params.cfg,
|
|
312
|
+
accountId: params.accountId,
|
|
313
|
+
scope: params.scope,
|
|
314
|
+
entries: params.entries
|
|
315
|
+
}) ?? []);
|
|
316
|
+
}
|
|
317
|
+
async function readAllowlistConfig(params) {
|
|
318
|
+
return await getChannelPlugin(params.channelId)?.allowlist?.readConfig?.({
|
|
319
|
+
cfg: params.cfg,
|
|
320
|
+
accountId: params.accountId
|
|
321
|
+
}) ?? {};
|
|
322
|
+
}
|
|
323
|
+
const handleAllowlistCommand = async (params, allowTextCommands) => {
|
|
324
|
+
if (!allowTextCommands) return null;
|
|
325
|
+
const parsed = parseAllowlistCommand(params.command.commandBodyNormalized);
|
|
326
|
+
if (!parsed) return null;
|
|
327
|
+
if (parsed.action === "error") return {
|
|
328
|
+
shouldContinue: false,
|
|
329
|
+
reply: { text: `ā ļø ${parsed.message}` }
|
|
330
|
+
};
|
|
331
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/allowlist");
|
|
332
|
+
if (unauthorized) return unauthorized;
|
|
333
|
+
if (parsed.action !== "list") {
|
|
334
|
+
const nonOwner = rejectNonOwnerCommand(params, "/allowlist");
|
|
335
|
+
if (nonOwner) return nonOwner;
|
|
336
|
+
}
|
|
337
|
+
const channelId = normalizeChannelId(parsed.channel) ?? params.command.channelId ?? normalizeChannelId(params.command.channel);
|
|
338
|
+
if (!channelId) return {
|
|
339
|
+
shouldContinue: false,
|
|
340
|
+
reply: { text: "ā ļø Unknown channel. Add channel=<id> to the command." }
|
|
341
|
+
};
|
|
342
|
+
if (normalizeOptionalString(parsed.account) && !normalizeOptionalAccountId(parsed.account)) return {
|
|
343
|
+
shouldContinue: false,
|
|
344
|
+
reply: { text: "ā ļø Invalid account id. Reserved keys (__proto__, constructor, prototype) are blocked." }
|
|
345
|
+
};
|
|
346
|
+
const accountId = resolveAllowlistAccountId({
|
|
347
|
+
cfg: params.cfg,
|
|
348
|
+
channelId,
|
|
349
|
+
parsedAccount: parsed.account,
|
|
350
|
+
ctxAccountId: params.ctx.AccountId
|
|
351
|
+
});
|
|
352
|
+
const plugin = getChannelPlugin(channelId);
|
|
353
|
+
if (parsed.action === "list") {
|
|
354
|
+
const supportsStore = Boolean(plugin?.pairing);
|
|
355
|
+
if (!plugin?.allowlist?.readConfig && !supportsStore) return {
|
|
356
|
+
shouldContinue: false,
|
|
357
|
+
reply: { text: `ā ļø ${channelId} does not expose allowlist configuration.` }
|
|
358
|
+
};
|
|
359
|
+
const storeAllowFrom = supportsStore ? await readChannelAllowFromStore(channelId, process.env, accountId).catch(() => []) : [];
|
|
360
|
+
const configState = await readAllowlistConfig({
|
|
361
|
+
cfg: params.cfg,
|
|
362
|
+
channelId,
|
|
363
|
+
accountId
|
|
364
|
+
});
|
|
365
|
+
const dmAllowFrom = (configState.dmAllowFrom ?? []).map(String);
|
|
366
|
+
const groupAllowFrom = (configState.groupAllowFrom ?? []).map(String);
|
|
367
|
+
const groupOverrides = (configState.groupOverrides ?? []).map((entry) => ({
|
|
368
|
+
label: entry.label,
|
|
369
|
+
entries: entry.entries.map(String).filter(Boolean)
|
|
370
|
+
}));
|
|
371
|
+
const dmDisplay = normalizeAllowFrom({
|
|
372
|
+
cfg: params.cfg,
|
|
373
|
+
channelId,
|
|
374
|
+
accountId,
|
|
375
|
+
values: dmAllowFrom
|
|
376
|
+
});
|
|
377
|
+
const groupDisplay = normalizeAllowFrom({
|
|
378
|
+
cfg: params.cfg,
|
|
379
|
+
channelId,
|
|
380
|
+
accountId,
|
|
381
|
+
values: groupAllowFrom
|
|
382
|
+
});
|
|
383
|
+
const groupOverrideEntries = groupOverrides.flatMap((entry) => entry.entries);
|
|
384
|
+
const groupOverrideDisplay = normalizeAllowFrom({
|
|
385
|
+
cfg: params.cfg,
|
|
386
|
+
channelId,
|
|
387
|
+
accountId,
|
|
388
|
+
values: groupOverrideEntries
|
|
389
|
+
});
|
|
390
|
+
const resolvedDm = parsed.resolve && dmDisplay.length > 0 ? await resolveAllowlistNames({
|
|
391
|
+
cfg: params.cfg,
|
|
392
|
+
channelId,
|
|
393
|
+
accountId,
|
|
394
|
+
scope: "dm",
|
|
395
|
+
entries: dmDisplay
|
|
396
|
+
}) : void 0;
|
|
397
|
+
const resolvedGroup = parsed.resolve && groupOverrideDisplay.length > 0 ? await resolveAllowlistNames({
|
|
398
|
+
cfg: params.cfg,
|
|
399
|
+
channelId,
|
|
400
|
+
accountId,
|
|
401
|
+
scope: "group",
|
|
402
|
+
entries: groupOverrideDisplay
|
|
403
|
+
}) : void 0;
|
|
404
|
+
const lines = ["š§¾ Allowlist"];
|
|
405
|
+
lines.push(`Channel: ${channelId}${accountId ? ` (account ${accountId})` : ""}`);
|
|
406
|
+
if (configState.dmPolicy) lines.push(`DM policy: ${configState.dmPolicy}`);
|
|
407
|
+
if (configState.groupPolicy) lines.push(`Group policy: ${configState.groupPolicy}`);
|
|
408
|
+
const showDm = parsed.scope === "dm" || parsed.scope === "all";
|
|
409
|
+
const showGroup = parsed.scope === "group" || parsed.scope === "all";
|
|
410
|
+
if (showDm) lines.push(`DM allowFrom (config): ${formatEntryList(dmDisplay, resolvedDm)}`);
|
|
411
|
+
if (supportsStore && storeAllowFrom.length > 0) {
|
|
412
|
+
const storeLabel = normalizeAllowFrom({
|
|
413
|
+
cfg: params.cfg,
|
|
414
|
+
channelId,
|
|
415
|
+
accountId,
|
|
416
|
+
values: storeAllowFrom
|
|
417
|
+
});
|
|
418
|
+
lines.push(`Paired allowFrom (store): ${formatEntryList(storeLabel)}`);
|
|
419
|
+
}
|
|
420
|
+
if (showGroup) {
|
|
421
|
+
if (groupAllowFrom.length > 0) lines.push(`Group allowFrom (config): ${formatEntryList(groupDisplay, resolvedGroup)}`);
|
|
422
|
+
if (groupOverrides.length > 0) {
|
|
423
|
+
lines.push("Group overrides:");
|
|
424
|
+
for (const entry of groupOverrides) {
|
|
425
|
+
const normalized = normalizeAllowFrom({
|
|
426
|
+
cfg: params.cfg,
|
|
427
|
+
channelId,
|
|
428
|
+
accountId,
|
|
429
|
+
values: entry.entries
|
|
430
|
+
});
|
|
431
|
+
lines.push(`- ${entry.label}: ${formatEntryList(normalized, resolvedGroup)}`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
shouldContinue: false,
|
|
437
|
+
reply: { text: lines.join("\n") }
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
|
|
441
|
+
label: "/allowlist write",
|
|
442
|
+
allowedScopes: ["operator.admin"],
|
|
443
|
+
missingText: "ā /allowlist add|remove requires operator.admin for gateway clients."
|
|
444
|
+
});
|
|
445
|
+
if (missingAdminScope) return missingAdminScope;
|
|
446
|
+
const disabled = requireCommandFlagEnabled(params.cfg, {
|
|
447
|
+
label: "/allowlist edits",
|
|
448
|
+
configKey: "config",
|
|
449
|
+
disabledVerb: "are"
|
|
450
|
+
});
|
|
451
|
+
if (disabled) return disabled;
|
|
452
|
+
const shouldUpdateConfig = parsed.target !== "store";
|
|
453
|
+
const shouldTouchStore = parsed.target !== "config" && Boolean(plugin?.pairing);
|
|
454
|
+
if (shouldUpdateConfig) {
|
|
455
|
+
if (parsed.scope === "all") return {
|
|
456
|
+
shouldContinue: false,
|
|
457
|
+
reply: { text: "ā ļø /allowlist add|remove requires scope dm or group." }
|
|
458
|
+
};
|
|
459
|
+
if (!plugin?.allowlist?.applyConfigEdit) return {
|
|
460
|
+
shouldContinue: false,
|
|
461
|
+
reply: { text: `ā ļø ${channelId} does not support ${parsed.scope} allowlist edits via /allowlist.` }
|
|
462
|
+
};
|
|
463
|
+
const snapshot = await readConfigFileSnapshot();
|
|
464
|
+
if (!snapshot.valid || !snapshot.parsed || typeof snapshot.parsed !== "object") return {
|
|
465
|
+
shouldContinue: false,
|
|
466
|
+
reply: { text: "ā ļø Config file is invalid; fix it before using /allowlist." }
|
|
467
|
+
};
|
|
468
|
+
const parsedConfig = structuredClone(snapshot.parsed);
|
|
469
|
+
const editResult = await plugin.allowlist.applyConfigEdit({
|
|
470
|
+
cfg: params.cfg,
|
|
471
|
+
parsedConfig,
|
|
472
|
+
accountId,
|
|
473
|
+
scope: parsed.scope,
|
|
474
|
+
action: parsed.action,
|
|
475
|
+
entry: parsed.entry
|
|
476
|
+
});
|
|
477
|
+
if (!editResult) return {
|
|
478
|
+
shouldContinue: false,
|
|
479
|
+
reply: { text: `ā ļø ${channelId} does not support ${parsed.scope} allowlist edits via /allowlist.` }
|
|
480
|
+
};
|
|
481
|
+
if (editResult.kind === "invalid-entry") return {
|
|
482
|
+
shouldContinue: false,
|
|
483
|
+
reply: { text: "ā ļø Invalid allowlist entry." }
|
|
484
|
+
};
|
|
485
|
+
const deniedText = resolveConfigWriteDeniedText({
|
|
486
|
+
cfg: params.cfg,
|
|
487
|
+
channel: params.command.channel,
|
|
488
|
+
channelId,
|
|
489
|
+
accountId,
|
|
490
|
+
gatewayClientScopes: params.ctx.GatewayClientScopes,
|
|
491
|
+
target: editResult.writeTarget
|
|
492
|
+
});
|
|
493
|
+
if (deniedText) return {
|
|
494
|
+
shouldContinue: false,
|
|
495
|
+
reply: { text: deniedText }
|
|
496
|
+
};
|
|
497
|
+
const configChanged = editResult.changed;
|
|
498
|
+
if (configChanged) {
|
|
499
|
+
const validated = validateConfigObjectWithPlugins(parsedConfig);
|
|
500
|
+
if (!validated.ok) {
|
|
501
|
+
const issue = validated.issues[0];
|
|
502
|
+
return {
|
|
503
|
+
shouldContinue: false,
|
|
504
|
+
reply: { text: `ā ļø Config invalid after update (${issue.path}: ${issue.message}).` }
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
await writeConfigFile(validated.config);
|
|
508
|
+
}
|
|
509
|
+
if (!configChanged && !shouldTouchStore) return {
|
|
510
|
+
shouldContinue: false,
|
|
511
|
+
reply: { text: parsed.action === "add" ? "ā
Already allowlisted." : "ā ļø Entry not found." }
|
|
512
|
+
};
|
|
513
|
+
if (shouldTouchStore) await updatePairingStoreAllowlist({
|
|
514
|
+
action: parsed.action,
|
|
515
|
+
channelId,
|
|
516
|
+
accountId,
|
|
517
|
+
entry: parsed.entry
|
|
518
|
+
});
|
|
519
|
+
const actionLabel = parsed.action === "add" ? "added" : "removed";
|
|
520
|
+
const scopeLabel = parsed.scope === "dm" ? "DM" : "group";
|
|
521
|
+
const locations = [];
|
|
522
|
+
if (configChanged) locations.push(editResult.pathLabel);
|
|
523
|
+
if (shouldTouchStore) locations.push("pairing store");
|
|
524
|
+
return {
|
|
525
|
+
shouldContinue: false,
|
|
526
|
+
reply: { text: `ā
${scopeLabel} allowlist ${actionLabel}: ${locations.length > 0 ? locations.join(" + ") : "no-op"}.` }
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
if (!shouldTouchStore) return {
|
|
530
|
+
shouldContinue: false,
|
|
531
|
+
reply: { text: "ā ļø This channel does not support allowlist storage." }
|
|
532
|
+
};
|
|
533
|
+
await updatePairingStoreAllowlist({
|
|
534
|
+
action: parsed.action,
|
|
535
|
+
channelId,
|
|
536
|
+
accountId,
|
|
537
|
+
entry: parsed.entry
|
|
538
|
+
});
|
|
539
|
+
const actionLabel = parsed.action === "add" ? "added" : "removed";
|
|
540
|
+
return {
|
|
541
|
+
shouldContinue: false,
|
|
542
|
+
reply: { text: `ā
${parsed.scope === "dm" ? "DM" : "group"} allowlist ${actionLabel} in pairing store.` }
|
|
543
|
+
};
|
|
544
|
+
};
|
|
545
|
+
//#endregion
|
|
546
|
+
//#region src/infra/channel-approval-auth.ts
|
|
547
|
+
function resolveApprovalCommandAuthorization(params) {
|
|
548
|
+
const channel = normalizeMessageChannel(params.channel);
|
|
549
|
+
if (!channel) return {
|
|
550
|
+
authorized: true,
|
|
551
|
+
explicit: false
|
|
552
|
+
};
|
|
553
|
+
const approvalCapability = resolveChannelApprovalCapability(getChannelPlugin(channel));
|
|
554
|
+
const resolved = approvalCapability?.authorizeActorAction?.({
|
|
555
|
+
cfg: params.cfg,
|
|
556
|
+
accountId: params.accountId,
|
|
557
|
+
senderId: params.senderId,
|
|
558
|
+
action: "approve",
|
|
559
|
+
approvalKind: params.kind
|
|
560
|
+
});
|
|
561
|
+
if (!resolved) return {
|
|
562
|
+
authorized: true,
|
|
563
|
+
explicit: false
|
|
564
|
+
};
|
|
565
|
+
const implicitSameChatAuthorization = isImplicitSameChatApprovalAuthorization(resolved);
|
|
566
|
+
const availability = approvalCapability?.getActionAvailabilityState?.({
|
|
567
|
+
cfg: params.cfg,
|
|
568
|
+
accountId: params.accountId,
|
|
569
|
+
action: "approve",
|
|
570
|
+
approvalKind: params.kind
|
|
571
|
+
});
|
|
572
|
+
return {
|
|
573
|
+
authorized: resolved.authorized,
|
|
574
|
+
reason: resolved.reason,
|
|
575
|
+
explicit: resolved.authorized ? !implicitSameChatAuthorization && availability?.kind !== "disabled" : true
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
//#endregion
|
|
579
|
+
//#region src/auto-reply/reply/commands-approve.ts
|
|
580
|
+
const COMMAND_REGEX = /^\/?approve(?:\s|$)/i;
|
|
581
|
+
const FOREIGN_COMMAND_MENTION_REGEX = /^\/approve@([^\s]+)(?:\s|$)/i;
|
|
582
|
+
const DECISION_ALIASES = {
|
|
583
|
+
allow: "allow-once",
|
|
584
|
+
once: "allow-once",
|
|
585
|
+
"allow-once": "allow-once",
|
|
586
|
+
allowonce: "allow-once",
|
|
587
|
+
always: "allow-always",
|
|
588
|
+
"allow-always": "allow-always",
|
|
589
|
+
allowalways: "allow-always",
|
|
590
|
+
deny: "deny",
|
|
591
|
+
reject: "deny",
|
|
592
|
+
block: "deny"
|
|
593
|
+
};
|
|
594
|
+
const APPROVE_USAGE_TEXT = "Usage: /approve <id> <decision> (see the pending approval message for available decisions)";
|
|
595
|
+
function parseApproveCommand(raw) {
|
|
596
|
+
const trimmed = raw.trim();
|
|
597
|
+
if (FOREIGN_COMMAND_MENTION_REGEX.test(trimmed)) return {
|
|
598
|
+
ok: false,
|
|
599
|
+
error: "ā This /approve command targets a different Telegram bot."
|
|
600
|
+
};
|
|
601
|
+
const commandMatch = trimmed.match(COMMAND_REGEX);
|
|
602
|
+
if (!commandMatch) return null;
|
|
603
|
+
const rest = trimmed.slice(commandMatch[0].length).trim();
|
|
604
|
+
if (!rest) return {
|
|
605
|
+
ok: false,
|
|
606
|
+
error: APPROVE_USAGE_TEXT
|
|
607
|
+
};
|
|
608
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
609
|
+
if (tokens.length < 2) return {
|
|
610
|
+
ok: false,
|
|
611
|
+
error: APPROVE_USAGE_TEXT
|
|
612
|
+
};
|
|
613
|
+
const first = normalizeLowercaseStringOrEmpty(tokens[0]);
|
|
614
|
+
const second = normalizeLowercaseStringOrEmpty(tokens[1]);
|
|
615
|
+
if (DECISION_ALIASES[first]) return {
|
|
616
|
+
ok: true,
|
|
617
|
+
decision: DECISION_ALIASES[first],
|
|
618
|
+
id: tokens.slice(1).join(" ").trim()
|
|
619
|
+
};
|
|
620
|
+
if (DECISION_ALIASES[second]) return {
|
|
621
|
+
ok: true,
|
|
622
|
+
decision: DECISION_ALIASES[second],
|
|
623
|
+
id: tokens[0]
|
|
624
|
+
};
|
|
625
|
+
return {
|
|
626
|
+
ok: false,
|
|
627
|
+
error: APPROVE_USAGE_TEXT
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
function buildResolvedByLabel(params) {
|
|
631
|
+
return `${params.command.channel}:${params.command.senderId ?? "unknown"}`;
|
|
632
|
+
}
|
|
633
|
+
function formatApprovalSubmitError(error) {
|
|
634
|
+
return formatErrorMessage(error);
|
|
635
|
+
}
|
|
636
|
+
function resolveApprovalMethods(params) {
|
|
637
|
+
if (params.approvalId.startsWith("plugin:")) return params.pluginAuthorization.authorized ? ["plugin.approval.resolve"] : [];
|
|
638
|
+
if (params.execAuthorization.authorized && params.pluginAuthorization.authorized) return ["exec.approval.resolve", "plugin.approval.resolve"];
|
|
639
|
+
if (params.execAuthorization.authorized) return ["exec.approval.resolve"];
|
|
640
|
+
if (params.pluginAuthorization.authorized) return ["plugin.approval.resolve"];
|
|
641
|
+
return [];
|
|
642
|
+
}
|
|
643
|
+
function resolveApprovalAuthorizationError(params) {
|
|
644
|
+
if (params.approvalId.startsWith("plugin:")) return params.pluginAuthorization.reason ?? "ā You are not authorized to approve this request.";
|
|
645
|
+
return params.execAuthorization.reason ?? params.pluginAuthorization.reason ?? "ā You are not authorized to approve this request.";
|
|
646
|
+
}
|
|
647
|
+
const handleApproveCommand = async (params, allowTextCommands) => {
|
|
648
|
+
if (!allowTextCommands) return null;
|
|
649
|
+
const normalized = params.command.commandBodyNormalized;
|
|
650
|
+
const parsed = parseApproveCommand(normalized);
|
|
651
|
+
if (!parsed) return null;
|
|
652
|
+
if (!parsed.ok) return {
|
|
653
|
+
shouldContinue: false,
|
|
654
|
+
reply: { text: parsed.error }
|
|
655
|
+
};
|
|
656
|
+
const isPluginId = parsed.id.startsWith("plugin:");
|
|
657
|
+
const effectiveAccountId = resolveChannelAccountId({
|
|
658
|
+
cfg: params.cfg,
|
|
659
|
+
ctx: params.ctx,
|
|
660
|
+
command: params.command
|
|
661
|
+
});
|
|
662
|
+
const approveCommandBehavior = resolveChannelApprovalCapability(getChannelPlugin(params.command.channel))?.resolveApproveCommandBehavior?.({
|
|
663
|
+
cfg: params.cfg,
|
|
664
|
+
accountId: effectiveAccountId,
|
|
665
|
+
senderId: params.command.senderId,
|
|
666
|
+
approvalKind: isPluginId ? "plugin" : "exec"
|
|
667
|
+
});
|
|
668
|
+
if (approveCommandBehavior?.kind === "ignore") return { shouldContinue: false };
|
|
669
|
+
if (approveCommandBehavior?.kind === "reply") return {
|
|
670
|
+
shouldContinue: false,
|
|
671
|
+
reply: { text: approveCommandBehavior.text }
|
|
672
|
+
};
|
|
673
|
+
const execApprovalAuthorization = resolveApprovalCommandAuthorization({
|
|
674
|
+
cfg: params.cfg,
|
|
675
|
+
channel: params.command.channel,
|
|
676
|
+
accountId: effectiveAccountId,
|
|
677
|
+
senderId: params.command.senderId,
|
|
678
|
+
kind: "exec"
|
|
679
|
+
});
|
|
680
|
+
const pluginApprovalAuthorization = resolveApprovalCommandAuthorization({
|
|
681
|
+
cfg: params.cfg,
|
|
682
|
+
channel: params.command.channel,
|
|
683
|
+
accountId: effectiveAccountId,
|
|
684
|
+
senderId: params.command.senderId,
|
|
685
|
+
kind: "plugin"
|
|
686
|
+
});
|
|
687
|
+
const hasExplicitApprovalAuthorization = execApprovalAuthorization.explicit && execApprovalAuthorization.authorized || pluginApprovalAuthorization.explicit && pluginApprovalAuthorization.authorized;
|
|
688
|
+
if (!params.command.isAuthorizedSender && !hasExplicitApprovalAuthorization) {
|
|
689
|
+
logVerbose(`Ignoring /approve from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
690
|
+
return { shouldContinue: false };
|
|
691
|
+
}
|
|
692
|
+
const missingScope = requireGatewayClientScopeForInternalChannel(params, {
|
|
693
|
+
label: "/approve",
|
|
694
|
+
allowedScopes: ["operator.approvals", "operator.admin"],
|
|
695
|
+
missingText: "ā /approve requires operator.approvals for gateway clients."
|
|
696
|
+
});
|
|
697
|
+
if (missingScope) return missingScope;
|
|
698
|
+
const resolvedBy = buildResolvedByLabel(params);
|
|
699
|
+
const callApprovalMethod = async (method) => {
|
|
700
|
+
await callGateway({
|
|
701
|
+
method,
|
|
702
|
+
params: {
|
|
703
|
+
id: parsed.id,
|
|
704
|
+
decision: parsed.decision
|
|
705
|
+
},
|
|
706
|
+
clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
|
|
707
|
+
clientDisplayName: `Chat approval (${resolvedBy})`,
|
|
708
|
+
mode: GATEWAY_CLIENT_MODES.BACKEND
|
|
709
|
+
});
|
|
710
|
+
};
|
|
711
|
+
const methods = resolveApprovalMethods({
|
|
712
|
+
approvalId: parsed.id,
|
|
713
|
+
execAuthorization: execApprovalAuthorization,
|
|
714
|
+
pluginAuthorization: pluginApprovalAuthorization
|
|
715
|
+
});
|
|
716
|
+
if (methods.length === 0) return {
|
|
717
|
+
shouldContinue: false,
|
|
718
|
+
reply: { text: resolveApprovalAuthorizationError({
|
|
719
|
+
approvalId: parsed.id,
|
|
720
|
+
execAuthorization: execApprovalAuthorization,
|
|
721
|
+
pluginAuthorization: pluginApprovalAuthorization
|
|
722
|
+
}) }
|
|
723
|
+
};
|
|
724
|
+
let lastError = null;
|
|
725
|
+
for (const [index, method] of methods.entries()) try {
|
|
726
|
+
await callApprovalMethod(method);
|
|
727
|
+
lastError = null;
|
|
728
|
+
break;
|
|
729
|
+
} catch (error) {
|
|
730
|
+
lastError = error;
|
|
731
|
+
const isLastMethod = index === methods.length - 1;
|
|
732
|
+
if (!isApprovalNotFoundError(error) || isLastMethod) return {
|
|
733
|
+
shouldContinue: false,
|
|
734
|
+
reply: { text: `ā Failed to submit approval: ${formatApprovalSubmitError(error)}` }
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
if (lastError) return {
|
|
738
|
+
shouldContinue: false,
|
|
739
|
+
reply: { text: `ā Failed to submit approval: ${formatApprovalSubmitError(lastError)}` }
|
|
740
|
+
};
|
|
741
|
+
return {
|
|
742
|
+
shouldContinue: false,
|
|
743
|
+
reply: { text: `ā
Approval ${parsed.decision} submitted for ${parsed.id}.` }
|
|
744
|
+
};
|
|
745
|
+
};
|
|
746
|
+
//#endregion
|
|
747
|
+
//#region src/auto-reply/reply/bash-command.ts
|
|
748
|
+
const CHAT_BASH_SCOPE_KEY = "chat:bash";
|
|
749
|
+
const DEFAULT_FOREGROUND_MS = 2e3;
|
|
750
|
+
const MAX_FOREGROUND_MS = 3e4;
|
|
751
|
+
let activeJob = null;
|
|
752
|
+
function resolveForegroundMs(cfg) {
|
|
753
|
+
const raw = cfg.commands?.bashForegroundMs;
|
|
754
|
+
if (typeof raw !== "number" || Number.isNaN(raw)) return DEFAULT_FOREGROUND_MS;
|
|
755
|
+
return clampInt(raw, 0, MAX_FOREGROUND_MS);
|
|
756
|
+
}
|
|
757
|
+
function formatSessionSnippet(sessionId) {
|
|
758
|
+
const trimmed = sessionId.trim();
|
|
759
|
+
if (trimmed.length <= 12) return trimmed;
|
|
760
|
+
return `${trimmed.slice(0, 8)}ā¦`;
|
|
761
|
+
}
|
|
762
|
+
function formatOutputBlock(text) {
|
|
763
|
+
const trimmed = text.trim();
|
|
764
|
+
if (!trimmed) return "(no output)";
|
|
765
|
+
return `\`\`\`txt\n${trimmed}\n\`\`\``;
|
|
766
|
+
}
|
|
767
|
+
function parseBashRequest(raw) {
|
|
768
|
+
const trimmed = raw.trimStart();
|
|
769
|
+
let restSource = "";
|
|
770
|
+
if (normalizeLowercaseStringOrEmpty(trimmed).startsWith("/bash")) {
|
|
771
|
+
const match = trimmed.match(/^\/bash(?:\s*:\s*|\s+|$)([\s\S]*)$/i);
|
|
772
|
+
if (!match) return null;
|
|
773
|
+
restSource = match[1] ?? "";
|
|
774
|
+
} else if (trimmed.startsWith("!")) {
|
|
775
|
+
restSource = trimmed.slice(1);
|
|
776
|
+
if (restSource.trimStart().startsWith(":")) restSource = restSource.trimStart().slice(1);
|
|
777
|
+
} else return null;
|
|
778
|
+
const rest = restSource.trimStart();
|
|
779
|
+
if (!rest) return { action: "help" };
|
|
780
|
+
const tokenMatch = rest.match(/^(\S+)(?:\s+([\s\S]+))?$/);
|
|
781
|
+
const token = normalizeOptionalString(tokenMatch?.[1]) ?? "";
|
|
782
|
+
const remainder = normalizeOptionalString(tokenMatch?.[2]) ?? "";
|
|
783
|
+
const lowered = normalizeLowercaseStringOrEmpty(token);
|
|
784
|
+
if (lowered === "poll") return {
|
|
785
|
+
action: "poll",
|
|
786
|
+
sessionId: remainder || void 0
|
|
787
|
+
};
|
|
788
|
+
if (lowered === "stop") return {
|
|
789
|
+
action: "stop",
|
|
790
|
+
sessionId: remainder || void 0
|
|
791
|
+
};
|
|
792
|
+
if (lowered === "help") return { action: "help" };
|
|
793
|
+
return {
|
|
794
|
+
action: "run",
|
|
795
|
+
command: rest
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
function resolveRawCommandBody(params) {
|
|
799
|
+
const stripped = stripStructuralPrefixes(params.ctx.CommandBody ?? params.ctx.RawBody ?? params.ctx.Body ?? "");
|
|
800
|
+
return params.isGroup ? stripMentions(stripped, params.ctx, params.cfg, params.agentId) : stripped;
|
|
801
|
+
}
|
|
802
|
+
function getScopedSession(sessionId) {
|
|
803
|
+
const running = getSession(sessionId);
|
|
804
|
+
if (running && running.scopeKey === CHAT_BASH_SCOPE_KEY) return { running };
|
|
805
|
+
const finished = getFinishedSession(sessionId);
|
|
806
|
+
if (finished && finished.scopeKey === CHAT_BASH_SCOPE_KEY) return { finished };
|
|
807
|
+
return {};
|
|
808
|
+
}
|
|
809
|
+
function ensureActiveJobState() {
|
|
810
|
+
if (!activeJob) return null;
|
|
811
|
+
if (activeJob.state === "starting") return activeJob;
|
|
812
|
+
const { running, finished } = getScopedSession(activeJob.sessionId);
|
|
813
|
+
if (running) return activeJob;
|
|
814
|
+
if (finished) {
|
|
815
|
+
activeJob = null;
|
|
816
|
+
return null;
|
|
817
|
+
}
|
|
818
|
+
activeJob = null;
|
|
819
|
+
return null;
|
|
820
|
+
}
|
|
821
|
+
function attachActiveWatcher(sessionId) {
|
|
822
|
+
if (!activeJob || activeJob.state !== "running") return;
|
|
823
|
+
if (activeJob.sessionId !== sessionId) return;
|
|
824
|
+
if (activeJob.watcherAttached) return;
|
|
825
|
+
const { running } = getScopedSession(sessionId);
|
|
826
|
+
const child = running?.child;
|
|
827
|
+
if (!child) return;
|
|
828
|
+
activeJob.watcherAttached = true;
|
|
829
|
+
child.once("close", () => {
|
|
830
|
+
if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
function buildUsageReply() {
|
|
834
|
+
return { text: [
|
|
835
|
+
"āļø Usage:",
|
|
836
|
+
"- ! <command>",
|
|
837
|
+
"- !poll | ! poll",
|
|
838
|
+
"- !stop | ! stop",
|
|
839
|
+
"- /bash ... (alias; same subcommands as !)"
|
|
840
|
+
].join("\n") };
|
|
841
|
+
}
|
|
842
|
+
async function handleBashChatCommand(params) {
|
|
843
|
+
if (!isCommandFlagEnabled(params.cfg, "bash")) return buildDisabledCommandReply({
|
|
844
|
+
label: "bash",
|
|
845
|
+
configKey: "bash",
|
|
846
|
+
docsUrl: "https://genesis.pixelzx.com/docs/tools/slash-commands#config"
|
|
847
|
+
});
|
|
848
|
+
const agentId = params.agentId ?? resolveSessionAgentId({
|
|
849
|
+
sessionKey: params.sessionKey,
|
|
850
|
+
config: params.cfg
|
|
851
|
+
});
|
|
852
|
+
if (!params.elevated.enabled || !params.elevated.allowed) {
|
|
853
|
+
const runtimeSandboxed = resolveSandboxRuntimeStatus({
|
|
854
|
+
cfg: params.cfg,
|
|
855
|
+
sessionKey: resolveRuntimePolicySessionKey({
|
|
856
|
+
cfg: params.cfg,
|
|
857
|
+
ctx: params.ctx,
|
|
858
|
+
sessionKey: params.sessionKey
|
|
859
|
+
})
|
|
860
|
+
}).sandboxed;
|
|
861
|
+
return { text: formatElevatedUnavailableMessage({
|
|
862
|
+
runtimeSandboxed,
|
|
863
|
+
failures: params.elevated.failures,
|
|
864
|
+
sessionKey: params.sessionKey
|
|
865
|
+
}) };
|
|
866
|
+
}
|
|
867
|
+
const request = parseBashRequest(resolveRawCommandBody({
|
|
868
|
+
ctx: params.ctx,
|
|
869
|
+
cfg: params.cfg,
|
|
870
|
+
agentId,
|
|
871
|
+
isGroup: params.isGroup
|
|
872
|
+
}).trim());
|
|
873
|
+
if (!request) return { text: "ā ļø Unrecognized bash request." };
|
|
874
|
+
const liveJob = ensureActiveJobState();
|
|
875
|
+
if (request.action === "help") return buildUsageReply();
|
|
876
|
+
if (request.action === "poll") {
|
|
877
|
+
const sessionId = normalizeOptionalString(request.sessionId) || (liveJob?.state === "running" ? liveJob.sessionId : "");
|
|
878
|
+
if (!sessionId) return { text: "āļø No active bash job." };
|
|
879
|
+
const { running, finished } = getScopedSession(sessionId);
|
|
880
|
+
if (running) {
|
|
881
|
+
attachActiveWatcher(sessionId);
|
|
882
|
+
const runtimeSec = Math.max(0, Math.floor((Date.now() - running.startedAt) / 1e3));
|
|
883
|
+
const tail = running.tail || "(no output yet)";
|
|
884
|
+
return { text: [
|
|
885
|
+
`āļø bash still running (session ${formatSessionSnippet(sessionId)}, ${runtimeSec}s).`,
|
|
886
|
+
formatOutputBlock(tail),
|
|
887
|
+
"Hint: !stop (or /bash stop)"
|
|
888
|
+
].join("\n") };
|
|
889
|
+
}
|
|
890
|
+
if (finished) {
|
|
891
|
+
if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
|
|
892
|
+
const exitLabel = finished.exitSignal ? `signal ${String(finished.exitSignal)}` : `code ${String(finished.exitCode ?? 0)}`;
|
|
893
|
+
return { text: [
|
|
894
|
+
`${finished.status === "completed" ? "āļø" : "ā ļø"} bash finished (session ${formatSessionSnippet(sessionId)}).`,
|
|
895
|
+
`Exit: ${exitLabel}`,
|
|
896
|
+
formatOutputBlock(finished.aggregated || finished.tail)
|
|
897
|
+
].join("\n") };
|
|
898
|
+
}
|
|
899
|
+
if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
|
|
900
|
+
return { text: `āļø No bash session found for ${formatSessionSnippet(sessionId)}.` };
|
|
901
|
+
}
|
|
902
|
+
if (request.action === "stop") {
|
|
903
|
+
const sessionId = normalizeOptionalString(request.sessionId) || (liveJob?.state === "running" ? liveJob.sessionId : "");
|
|
904
|
+
if (!sessionId) return { text: "āļø No active bash job." };
|
|
905
|
+
const { running } = getScopedSession(sessionId);
|
|
906
|
+
if (!running) {
|
|
907
|
+
if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
|
|
908
|
+
return { text: `āļø No running bash job found for ${formatSessionSnippet(sessionId)}.` };
|
|
909
|
+
}
|
|
910
|
+
if (!running.backgrounded) return { text: `ā ļø Session ${formatSessionSnippet(sessionId)} is not backgrounded.` };
|
|
911
|
+
const pid = running.pid ?? running.child?.pid;
|
|
912
|
+
if (!pid) return { text: `ā ļø Unable to stop bash session ${formatSessionSnippet(sessionId)} because no process ID is available. Use !poll ${sessionId} to check whether it exits on its own.` };
|
|
913
|
+
const { killProcessTree } = await import("./kill-tree-BRbowqSh.js");
|
|
914
|
+
killProcessTree(pid);
|
|
915
|
+
return { text: `āļø bash stopping (session ${formatSessionSnippet(sessionId)}). Use !poll ${sessionId} to confirm exit.` };
|
|
916
|
+
}
|
|
917
|
+
if (liveJob) return { text: `ā ļø A bash job is already running (${liveJob.state === "running" ? formatSessionSnippet(liveJob.sessionId) : "starting"}). Use !poll / !stop (or /bash poll / /bash stop).` };
|
|
918
|
+
const commandText = request.command.trim();
|
|
919
|
+
if (!commandText) return buildUsageReply();
|
|
920
|
+
activeJob = {
|
|
921
|
+
state: "starting",
|
|
922
|
+
startedAt: Date.now(),
|
|
923
|
+
command: commandText
|
|
924
|
+
};
|
|
925
|
+
try {
|
|
926
|
+
const foregroundMs = resolveForegroundMs(params.cfg);
|
|
927
|
+
const shouldBackgroundImmediately = foregroundMs <= 0;
|
|
928
|
+
const timeoutSec = params.cfg.tools?.exec?.timeoutSec;
|
|
929
|
+
const notifyOnExit = params.cfg.tools?.exec?.notifyOnExit;
|
|
930
|
+
const notifyOnExitEmptySuccess = params.cfg.tools?.exec?.notifyOnExitEmptySuccess;
|
|
931
|
+
const result = await createExecTool({
|
|
932
|
+
scopeKey: CHAT_BASH_SCOPE_KEY,
|
|
933
|
+
allowBackground: true,
|
|
934
|
+
timeoutSec,
|
|
935
|
+
sessionKey: params.sessionKey,
|
|
936
|
+
notifyOnExit,
|
|
937
|
+
notifyOnExitEmptySuccess,
|
|
938
|
+
elevated: {
|
|
939
|
+
enabled: params.elevated.enabled,
|
|
940
|
+
allowed: params.elevated.allowed,
|
|
941
|
+
defaultLevel: "on"
|
|
942
|
+
}
|
|
943
|
+
}).execute("chat-bash", {
|
|
944
|
+
command: commandText,
|
|
945
|
+
background: shouldBackgroundImmediately,
|
|
946
|
+
yieldMs: shouldBackgroundImmediately ? void 0 : foregroundMs,
|
|
947
|
+
timeout: timeoutSec,
|
|
948
|
+
elevated: true
|
|
949
|
+
});
|
|
950
|
+
if (result.details?.status === "running") {
|
|
951
|
+
const sessionId = result.details.sessionId;
|
|
952
|
+
activeJob = {
|
|
953
|
+
state: "running",
|
|
954
|
+
sessionId,
|
|
955
|
+
startedAt: result.details.startedAt,
|
|
956
|
+
command: commandText,
|
|
957
|
+
watcherAttached: false
|
|
958
|
+
};
|
|
959
|
+
attachActiveWatcher(sessionId);
|
|
960
|
+
logVerbose(`Started bash session ${formatSessionSnippet(sessionId)}: ${commandText}`);
|
|
961
|
+
return { text: `āļø bash started (session ${sessionId}). Still running; use !poll / !stop (or /bash poll / /bash stop).` };
|
|
962
|
+
}
|
|
963
|
+
activeJob = null;
|
|
964
|
+
const exitCode = result.details?.status === "completed" ? result.details.exitCode : 0;
|
|
965
|
+
const output = result.details?.status === "completed" ? result.details.aggregated : result.content.map((chunk) => chunk.type === "text" ? chunk.text : "").join("\n");
|
|
966
|
+
return { text: [
|
|
967
|
+
`āļø bash: ${commandText}`,
|
|
968
|
+
`Exit: ${exitCode}`,
|
|
969
|
+
formatOutputBlock(output || "(no output)")
|
|
970
|
+
].join("\n") };
|
|
971
|
+
} catch (err) {
|
|
972
|
+
activeJob = null;
|
|
973
|
+
const message = formatErrorMessage(err);
|
|
974
|
+
return { text: [`ā ļø bash failed: ${commandText}`, formatOutputBlock(message)].join("\n") };
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
//#endregion
|
|
978
|
+
//#region src/auto-reply/reply/commands-bash.ts
|
|
979
|
+
const handleBashCommand = async (params, allowTextCommands) => {
|
|
980
|
+
if (!allowTextCommands) return null;
|
|
981
|
+
const { command } = params;
|
|
982
|
+
const bashSlashRequested = command.commandBodyNormalized === "/bash" || command.commandBodyNormalized.startsWith("/bash ");
|
|
983
|
+
const bashBangRequested = command.commandBodyNormalized.startsWith("!");
|
|
984
|
+
if (!bashSlashRequested && !(bashBangRequested && command.isAuthorizedSender)) return null;
|
|
985
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/bash");
|
|
986
|
+
if (unauthorized) return unauthorized;
|
|
987
|
+
const agentId = params.sessionKey ? resolveSessionAgentId({
|
|
988
|
+
sessionKey: params.sessionKey,
|
|
989
|
+
config: params.cfg
|
|
990
|
+
}) : params.agentId;
|
|
991
|
+
return {
|
|
992
|
+
shouldContinue: false,
|
|
993
|
+
reply: await handleBashChatCommand({
|
|
994
|
+
ctx: params.ctx,
|
|
995
|
+
cfg: params.cfg,
|
|
996
|
+
agentId,
|
|
997
|
+
sessionKey: params.sessionKey,
|
|
998
|
+
isGroup: params.isGroup,
|
|
999
|
+
elevated: params.elevated
|
|
1000
|
+
})
|
|
1001
|
+
};
|
|
1002
|
+
};
|
|
1003
|
+
//#endregion
|
|
1004
|
+
//#region src/agents/btw.ts
|
|
1005
|
+
function collectTextContent(content) {
|
|
1006
|
+
return content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
1007
|
+
}
|
|
1008
|
+
function collectThinkingContent(content) {
|
|
1009
|
+
return content.filter((part) => part.type === "thinking").map((part) => part.thinking).join("");
|
|
1010
|
+
}
|
|
1011
|
+
function buildBtwSystemPrompt() {
|
|
1012
|
+
return [
|
|
1013
|
+
"You are answering an ephemeral /btw side question about the current conversation.",
|
|
1014
|
+
"Use the conversation only as background context.",
|
|
1015
|
+
"Answer only the side question in the last user message.",
|
|
1016
|
+
"Do not continue, resume, or complete any unfinished task from the conversation.",
|
|
1017
|
+
"Do not emit tool calls, pseudo-tool calls, shell commands, file writes, patches, or code unless the side question explicitly asks for them.",
|
|
1018
|
+
"Do not say you will continue the main task after answering.",
|
|
1019
|
+
"If the question can be answered briefly, answer briefly."
|
|
1020
|
+
].join("\n");
|
|
1021
|
+
}
|
|
1022
|
+
function buildBtwQuestionPrompt(question, inFlightPrompt) {
|
|
1023
|
+
const lines = ["Answer this side question only.", "Ignore any unfinished task in the conversation while answering it."];
|
|
1024
|
+
const trimmedPrompt = inFlightPrompt?.trim();
|
|
1025
|
+
if (trimmedPrompt) lines.push("", "Current in-flight main task request for background context only:", "<in_flight_main_task>", trimmedPrompt, "</in_flight_main_task>", "Do not continue or complete that task while answering the side question.");
|
|
1026
|
+
lines.push("", "<btw_side_question>", question.trim(), "</btw_side_question>");
|
|
1027
|
+
return lines.join("\n");
|
|
1028
|
+
}
|
|
1029
|
+
function normalizeBtwContentBlocks(content) {
|
|
1030
|
+
if (Array.isArray(content)) return content;
|
|
1031
|
+
if (content && typeof content === "object") return [content];
|
|
1032
|
+
}
|
|
1033
|
+
function isBtwTextBlock(block) {
|
|
1034
|
+
if (!block || typeof block !== "object") return false;
|
|
1035
|
+
const record = block;
|
|
1036
|
+
return normalizeLowercaseStringOrEmpty(record.type) === "text" && typeof record.text === "string";
|
|
1037
|
+
}
|
|
1038
|
+
function isBtwImageBlock(block) {
|
|
1039
|
+
if (!block || typeof block !== "object") return false;
|
|
1040
|
+
const record = block;
|
|
1041
|
+
return normalizeLowercaseStringOrEmpty(record.type) === "image" && typeof record.data === "string" && typeof record.mimeType === "string";
|
|
1042
|
+
}
|
|
1043
|
+
async function sanitizeBtwUserMessage(params) {
|
|
1044
|
+
if (typeof params.message.content === "string") return params.message;
|
|
1045
|
+
const blocks = normalizeBtwContentBlocks(params.message.content);
|
|
1046
|
+
if (!blocks) return;
|
|
1047
|
+
const content = [];
|
|
1048
|
+
for (const block of blocks) {
|
|
1049
|
+
if (isBtwTextBlock(block)) {
|
|
1050
|
+
content.push({
|
|
1051
|
+
type: "text",
|
|
1052
|
+
text: block.text
|
|
1053
|
+
});
|
|
1054
|
+
continue;
|
|
1055
|
+
}
|
|
1056
|
+
if (!isBtwImageBlock(block)) continue;
|
|
1057
|
+
const { images } = await sanitizeImageBlocks([block], "btw:context", params.imageLimits);
|
|
1058
|
+
const image = images[0];
|
|
1059
|
+
if (image) content.push(image);
|
|
1060
|
+
}
|
|
1061
|
+
if (content.length === 0) return;
|
|
1062
|
+
return {
|
|
1063
|
+
...params.message,
|
|
1064
|
+
content
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
function sanitizeBtwAssistantMessage(message) {
|
|
1068
|
+
const rawContent = message.content;
|
|
1069
|
+
if (typeof rawContent === "string") {
|
|
1070
|
+
const trimmed = rawContent.trim();
|
|
1071
|
+
return trimmed.length > 0 ? {
|
|
1072
|
+
...message,
|
|
1073
|
+
content: [{
|
|
1074
|
+
type: "text",
|
|
1075
|
+
text: trimmed
|
|
1076
|
+
}]
|
|
1077
|
+
} : void 0;
|
|
1078
|
+
}
|
|
1079
|
+
const blocks = normalizeBtwContentBlocks(rawContent);
|
|
1080
|
+
if (!blocks) return;
|
|
1081
|
+
const content = blocks.flatMap((block) => isBtwTextBlock(block) ? [{
|
|
1082
|
+
type: "text",
|
|
1083
|
+
text: block.text
|
|
1084
|
+
}] : []);
|
|
1085
|
+
if (content.length === 0) return;
|
|
1086
|
+
return {
|
|
1087
|
+
...message,
|
|
1088
|
+
content
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
async function toSimpleContextMessages(params) {
|
|
1092
|
+
const contextMessages = [];
|
|
1093
|
+
for (const message of params.messages) {
|
|
1094
|
+
if (!message || typeof message !== "object") continue;
|
|
1095
|
+
const role = message.role;
|
|
1096
|
+
if (role === "user") {
|
|
1097
|
+
const sanitizedMessage = await sanitizeBtwUserMessage({
|
|
1098
|
+
message,
|
|
1099
|
+
imageLimits: params.imageLimits
|
|
1100
|
+
});
|
|
1101
|
+
if (sanitizedMessage) contextMessages.push(sanitizedMessage);
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
if (role !== "assistant") continue;
|
|
1105
|
+
const sanitizedMessage = sanitizeBtwAssistantMessage(message);
|
|
1106
|
+
if (sanitizedMessage) contextMessages.push(sanitizedMessage);
|
|
1107
|
+
}
|
|
1108
|
+
return stripToolResultDetails(contextMessages);
|
|
1109
|
+
}
|
|
1110
|
+
function resolveSessionTranscriptPath(params) {
|
|
1111
|
+
try {
|
|
1112
|
+
const agentId = params.sessionKey?.split(":")[1];
|
|
1113
|
+
const pathOpts = resolveSessionFilePathOptions({
|
|
1114
|
+
agentId,
|
|
1115
|
+
storePath: params.storePath
|
|
1116
|
+
});
|
|
1117
|
+
return resolveSessionFilePath(params.sessionId, params.sessionEntry, pathOpts);
|
|
1118
|
+
} catch (error) {
|
|
1119
|
+
diagnosticLogger.debug(`resolveSessionTranscriptPath failed: sessionId=${params.sessionId} err=${String(error)}`);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
async function resolveRuntimeModel(params) {
|
|
1124
|
+
await ensureGenesisModelsJson(params.cfg, params.agentDir);
|
|
1125
|
+
const modelRegistry = discoverModels(discoverAuthStorage(params.agentDir), params.agentDir);
|
|
1126
|
+
const model = resolveModelWithRegistry({
|
|
1127
|
+
provider: params.provider,
|
|
1128
|
+
modelId: params.model,
|
|
1129
|
+
modelRegistry,
|
|
1130
|
+
cfg: params.cfg
|
|
1131
|
+
});
|
|
1132
|
+
if (!model) throw new Error(`Unknown model: ${params.provider}/${params.model}`);
|
|
1133
|
+
return {
|
|
1134
|
+
model,
|
|
1135
|
+
authProfileId: await resolveSessionAuthProfileOverride({
|
|
1136
|
+
cfg: params.cfg,
|
|
1137
|
+
provider: params.provider,
|
|
1138
|
+
agentDir: params.agentDir,
|
|
1139
|
+
sessionEntry: params.sessionEntry,
|
|
1140
|
+
sessionStore: params.sessionStore,
|
|
1141
|
+
sessionKey: params.sessionKey,
|
|
1142
|
+
storePath: params.storePath,
|
|
1143
|
+
isNewSession: params.isNewSession
|
|
1144
|
+
}),
|
|
1145
|
+
authProfileIdSource: params.sessionEntry?.authProfileOverrideSource
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
async function runBtwSideQuestion(params) {
|
|
1149
|
+
const sessionId = params.sessionEntry.sessionId?.trim();
|
|
1150
|
+
if (!sessionId) throw new Error("No active session context.");
|
|
1151
|
+
const sessionFile = resolveSessionTranscriptPath({
|
|
1152
|
+
sessionId,
|
|
1153
|
+
sessionEntry: params.sessionEntry,
|
|
1154
|
+
sessionKey: params.sessionKey,
|
|
1155
|
+
storePath: params.storePath
|
|
1156
|
+
});
|
|
1157
|
+
if (!sessionFile) throw new Error("No active session transcript.");
|
|
1158
|
+
const sessionManager = SessionManager.open(sessionFile);
|
|
1159
|
+
const activeRunSnapshot = getActiveEmbeddedRunSnapshot(sessionId);
|
|
1160
|
+
const imageLimits = resolveImageSanitizationLimits(params.cfg);
|
|
1161
|
+
let messages = [];
|
|
1162
|
+
let inFlightPrompt;
|
|
1163
|
+
if (Array.isArray(activeRunSnapshot?.messages) && activeRunSnapshot.messages.length > 0) {
|
|
1164
|
+
messages = await toSimpleContextMessages({
|
|
1165
|
+
messages: activeRunSnapshot.messages,
|
|
1166
|
+
imageLimits
|
|
1167
|
+
});
|
|
1168
|
+
inFlightPrompt = activeRunSnapshot.inFlightPrompt;
|
|
1169
|
+
} else if (activeRunSnapshot) {
|
|
1170
|
+
inFlightPrompt = activeRunSnapshot.inFlightPrompt;
|
|
1171
|
+
if (activeRunSnapshot.transcriptLeafId && sessionManager.branch) try {
|
|
1172
|
+
sessionManager.branch(activeRunSnapshot.transcriptLeafId);
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
diagnosticLogger.debug(`btw snapshot leaf unavailable: sessionId=${sessionId} leaf=${activeRunSnapshot.transcriptLeafId} err=${String(error)}`);
|
|
1175
|
+
sessionManager.resetLeaf?.();
|
|
1176
|
+
}
|
|
1177
|
+
else sessionManager.resetLeaf?.();
|
|
1178
|
+
} else {
|
|
1179
|
+
const leafEntry = sessionManager.getLeafEntry?.();
|
|
1180
|
+
if (leafEntry?.type === "message" && leafEntry.message?.role === "user") if (leafEntry.parentId && sessionManager.branch) sessionManager.branch(leafEntry.parentId);
|
|
1181
|
+
else sessionManager.resetLeaf?.();
|
|
1182
|
+
}
|
|
1183
|
+
if (messages.length === 0) {
|
|
1184
|
+
const sessionContext = sessionManager.buildSessionContext();
|
|
1185
|
+
messages = await toSimpleContextMessages({
|
|
1186
|
+
messages: Array.isArray(sessionContext.messages) ? sessionContext.messages : [],
|
|
1187
|
+
imageLimits
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
if (messages.length === 0 && !inFlightPrompt?.trim()) throw new Error("No active session context.");
|
|
1191
|
+
const { model, authProfileId } = await resolveRuntimeModel({
|
|
1192
|
+
cfg: params.cfg,
|
|
1193
|
+
provider: params.provider,
|
|
1194
|
+
model: params.model,
|
|
1195
|
+
agentDir: params.agentDir,
|
|
1196
|
+
sessionEntry: params.sessionEntry,
|
|
1197
|
+
sessionStore: params.sessionStore,
|
|
1198
|
+
sessionKey: params.sessionKey,
|
|
1199
|
+
storePath: params.storePath,
|
|
1200
|
+
isNewSession: params.isNewSession
|
|
1201
|
+
});
|
|
1202
|
+
const apiKeyInfo = await getApiKeyForModel({
|
|
1203
|
+
model,
|
|
1204
|
+
cfg: params.cfg,
|
|
1205
|
+
profileId: authProfileId,
|
|
1206
|
+
agentDir: params.agentDir
|
|
1207
|
+
});
|
|
1208
|
+
let runtimeModel = model;
|
|
1209
|
+
let apiKey = apiKeyInfo.mode === "aws-sdk" && !apiKeyInfo.apiKey ? void 0 : requireApiKey(apiKeyInfo, model.provider);
|
|
1210
|
+
const sessionAgentId = resolveSessionAgentId({
|
|
1211
|
+
sessionKey: params.sessionKey,
|
|
1212
|
+
config: params.cfg
|
|
1213
|
+
});
|
|
1214
|
+
const workspaceDir = resolveAgentWorkspaceDir(params.cfg, sessionAgentId);
|
|
1215
|
+
if (apiKey) {
|
|
1216
|
+
const preparedAuth = await prepareProviderRuntimeAuth({
|
|
1217
|
+
provider: model.provider,
|
|
1218
|
+
config: params.cfg,
|
|
1219
|
+
workspaceDir,
|
|
1220
|
+
env: process.env,
|
|
1221
|
+
context: {
|
|
1222
|
+
config: params.cfg,
|
|
1223
|
+
agentDir: params.agentDir,
|
|
1224
|
+
workspaceDir,
|
|
1225
|
+
env: process.env,
|
|
1226
|
+
provider: model.provider,
|
|
1227
|
+
modelId: model.id,
|
|
1228
|
+
model,
|
|
1229
|
+
apiKey,
|
|
1230
|
+
authMode: apiKeyInfo.mode,
|
|
1231
|
+
profileId: authProfileId
|
|
1232
|
+
}
|
|
1233
|
+
});
|
|
1234
|
+
if (preparedAuth?.baseUrl) runtimeModel = {
|
|
1235
|
+
...runtimeModel,
|
|
1236
|
+
baseUrl: preparedAuth.baseUrl
|
|
1237
|
+
};
|
|
1238
|
+
if (preparedAuth?.apiKey) apiKey = preparedAuth.apiKey;
|
|
1239
|
+
}
|
|
1240
|
+
const providerStreamFn = registerProviderStreamForModel({
|
|
1241
|
+
model: runtimeModel,
|
|
1242
|
+
cfg: params.cfg,
|
|
1243
|
+
agentDir: params.agentDir,
|
|
1244
|
+
workspaceDir,
|
|
1245
|
+
env: process.env
|
|
1246
|
+
});
|
|
1247
|
+
const chunker = params.opts?.onBlockReply && params.blockReplyChunking ? new EmbeddedBlockChunker(params.blockReplyChunking) : void 0;
|
|
1248
|
+
let emittedBlocks = 0;
|
|
1249
|
+
let blockEmitChain = Promise.resolve();
|
|
1250
|
+
let answerText = "";
|
|
1251
|
+
let reasoningText = "";
|
|
1252
|
+
let assistantStarted = false;
|
|
1253
|
+
let sawTextEvent = false;
|
|
1254
|
+
const emitBlockChunk = async (text) => {
|
|
1255
|
+
if (!text.trim() || !params.opts?.onBlockReply) return;
|
|
1256
|
+
emittedBlocks += 1;
|
|
1257
|
+
blockEmitChain = blockEmitChain.then(async () => {
|
|
1258
|
+
await params.opts?.onBlockReply?.({
|
|
1259
|
+
text,
|
|
1260
|
+
btw: { question: params.question }
|
|
1261
|
+
});
|
|
1262
|
+
});
|
|
1263
|
+
await blockEmitChain;
|
|
1264
|
+
};
|
|
1265
|
+
const stream = await streamWithPayloadPatch(providerStreamFn ?? streamSimple, runtimeModel, {
|
|
1266
|
+
systemPrompt: buildBtwSystemPrompt(),
|
|
1267
|
+
messages: [...messages, {
|
|
1268
|
+
role: "user",
|
|
1269
|
+
content: [{
|
|
1270
|
+
type: "text",
|
|
1271
|
+
text: buildBtwQuestionPrompt(params.question, inFlightPrompt)
|
|
1272
|
+
}],
|
|
1273
|
+
timestamp: Date.now()
|
|
1274
|
+
}]
|
|
1275
|
+
}, {
|
|
1276
|
+
apiKey,
|
|
1277
|
+
reasoning: void 0,
|
|
1278
|
+
signal: params.opts?.abortSignal
|
|
1279
|
+
}, (payloadObj) => {
|
|
1280
|
+
if (Array.isArray(payloadObj.tools) && payloadObj.tools.length === 0) delete payloadObj.tools;
|
|
1281
|
+
});
|
|
1282
|
+
let finalEvent;
|
|
1283
|
+
for await (const event of stream) {
|
|
1284
|
+
finalEvent = event.type === "done" || event.type === "error" ? event : finalEvent;
|
|
1285
|
+
if (!assistantStarted && (event.type === "text_start" || event.type === "start")) {
|
|
1286
|
+
assistantStarted = true;
|
|
1287
|
+
await params.opts?.onAssistantMessageStart?.();
|
|
1288
|
+
}
|
|
1289
|
+
if (event.type === "text_delta") {
|
|
1290
|
+
sawTextEvent = true;
|
|
1291
|
+
answerText += event.delta;
|
|
1292
|
+
chunker?.append(event.delta);
|
|
1293
|
+
if (chunker && params.resolvedBlockStreamingBreak === "text_end") chunker.drain({
|
|
1294
|
+
force: false,
|
|
1295
|
+
emit: (chunk) => void emitBlockChunk(chunk)
|
|
1296
|
+
});
|
|
1297
|
+
continue;
|
|
1298
|
+
}
|
|
1299
|
+
if (event.type === "text_end" && chunker && params.resolvedBlockStreamingBreak === "text_end") {
|
|
1300
|
+
chunker.drain({
|
|
1301
|
+
force: true,
|
|
1302
|
+
emit: (chunk) => void emitBlockChunk(chunk)
|
|
1303
|
+
});
|
|
1304
|
+
continue;
|
|
1305
|
+
}
|
|
1306
|
+
if (event.type === "thinking_delta") {
|
|
1307
|
+
reasoningText += event.delta;
|
|
1308
|
+
if (params.resolvedReasoningLevel !== "off") await params.opts?.onReasoningStream?.({
|
|
1309
|
+
text: reasoningText,
|
|
1310
|
+
isReasoning: true
|
|
1311
|
+
});
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
if (event.type === "thinking_end" && params.resolvedReasoningLevel !== "off") await params.opts?.onReasoningEnd?.();
|
|
1315
|
+
}
|
|
1316
|
+
if (chunker && params.resolvedBlockStreamingBreak !== "text_end" && chunker.hasBuffered()) chunker.drain({
|
|
1317
|
+
force: true,
|
|
1318
|
+
emit: (chunk) => void emitBlockChunk(chunk)
|
|
1319
|
+
});
|
|
1320
|
+
await blockEmitChain;
|
|
1321
|
+
if (finalEvent?.type === "error") {
|
|
1322
|
+
const message = collectTextContent(finalEvent.error.content);
|
|
1323
|
+
throw new Error(message || finalEvent.error.errorMessage || "BTW failed.");
|
|
1324
|
+
}
|
|
1325
|
+
const finalMessage = finalEvent?.type === "done" ? finalEvent.message : void 0;
|
|
1326
|
+
if (finalMessage) {
|
|
1327
|
+
if (!sawTextEvent) answerText = collectTextContent(finalMessage.content);
|
|
1328
|
+
if (!reasoningText) reasoningText = collectThinkingContent(finalMessage.content);
|
|
1329
|
+
}
|
|
1330
|
+
const answer = answerText.trim();
|
|
1331
|
+
if (!answer) throw new Error("No BTW response generated.");
|
|
1332
|
+
if (emittedBlocks > 0) return;
|
|
1333
|
+
return { text: answer };
|
|
1334
|
+
}
|
|
1335
|
+
//#endregion
|
|
1336
|
+
//#region src/auto-reply/reply/commands-btw.ts
|
|
1337
|
+
const BTW_USAGE = "Usage: /btw <side question>";
|
|
1338
|
+
const handleBtwCommand = async (params, allowTextCommands) => {
|
|
1339
|
+
if (!allowTextCommands) return null;
|
|
1340
|
+
const question = extractBtwQuestion(params.command.commandBodyNormalized);
|
|
1341
|
+
if (question === null) return null;
|
|
1342
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/btw");
|
|
1343
|
+
if (unauthorized) return unauthorized;
|
|
1344
|
+
if (!question) return {
|
|
1345
|
+
shouldContinue: false,
|
|
1346
|
+
reply: { text: BTW_USAGE }
|
|
1347
|
+
};
|
|
1348
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
1349
|
+
if (!targetSessionEntry?.sessionId) return {
|
|
1350
|
+
shouldContinue: false,
|
|
1351
|
+
reply: { text: "ā ļø /btw requires an active session with existing context." }
|
|
1352
|
+
};
|
|
1353
|
+
const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
|
|
1354
|
+
sessionKey: params.sessionKey,
|
|
1355
|
+
config: params.cfg
|
|
1356
|
+
}) : params.agentId;
|
|
1357
|
+
const agentDir = (sessionAgentId ? resolveAgentDir(params.cfg, sessionAgentId) : void 0) ?? params.agentDir;
|
|
1358
|
+
if (!agentDir) return {
|
|
1359
|
+
shouldContinue: false,
|
|
1360
|
+
reply: { text: "ā ļø /btw is unavailable because the active agent directory could not be resolved." }
|
|
1361
|
+
};
|
|
1362
|
+
try {
|
|
1363
|
+
await params.typing?.startTypingLoop();
|
|
1364
|
+
const reply = await runBtwSideQuestion({
|
|
1365
|
+
cfg: params.cfg,
|
|
1366
|
+
agentDir,
|
|
1367
|
+
provider: params.provider,
|
|
1368
|
+
model: params.model,
|
|
1369
|
+
question,
|
|
1370
|
+
sessionEntry: targetSessionEntry,
|
|
1371
|
+
sessionStore: params.sessionStore,
|
|
1372
|
+
sessionKey: params.sessionKey,
|
|
1373
|
+
storePath: params.storePath,
|
|
1374
|
+
resolvedThinkLevel: "off",
|
|
1375
|
+
resolvedReasoningLevel: "off",
|
|
1376
|
+
blockReplyChunking: params.blockReplyChunking,
|
|
1377
|
+
resolvedBlockStreamingBreak: params.resolvedBlockStreamingBreak,
|
|
1378
|
+
opts: params.opts,
|
|
1379
|
+
isNewSession: false
|
|
1380
|
+
});
|
|
1381
|
+
return {
|
|
1382
|
+
shouldContinue: false,
|
|
1383
|
+
reply: reply ? {
|
|
1384
|
+
...reply,
|
|
1385
|
+
btw: { question }
|
|
1386
|
+
} : reply
|
|
1387
|
+
};
|
|
1388
|
+
} catch (error) {
|
|
1389
|
+
const message = error instanceof Error ? error.message.trim() : "";
|
|
1390
|
+
return {
|
|
1391
|
+
shouldContinue: false,
|
|
1392
|
+
reply: {
|
|
1393
|
+
text: `ā ļø /btw failed${message ? `: ${message}` : "."}`,
|
|
1394
|
+
btw: { question },
|
|
1395
|
+
isError: true
|
|
1396
|
+
}
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
//#endregion
|
|
1401
|
+
//#region src/auto-reply/reply/commands-compact.ts
|
|
1402
|
+
let compactRuntimePromise = null;
|
|
1403
|
+
function loadCompactRuntime() {
|
|
1404
|
+
compactRuntimePromise ??= import("./commands-compact.runtime-B6e3kwMS.js");
|
|
1405
|
+
return compactRuntimePromise;
|
|
1406
|
+
}
|
|
1407
|
+
function extractCompactInstructions(params) {
|
|
1408
|
+
const raw = stripStructuralPrefixes(params.rawBody ?? "");
|
|
1409
|
+
const trimmed = (params.isGroup ? stripMentions(raw, params.ctx, params.cfg, params.agentId) : raw).trim();
|
|
1410
|
+
if (!trimmed) return;
|
|
1411
|
+
const prefix = normalizeLowercaseStringOrEmpty(trimmed).startsWith("/compact") ? "/compact" : null;
|
|
1412
|
+
if (!prefix) return;
|
|
1413
|
+
let rest = trimmed.slice(prefix.length).trimStart();
|
|
1414
|
+
if (rest.startsWith(":")) rest = rest.slice(1).trimStart();
|
|
1415
|
+
return rest.length ? rest : void 0;
|
|
1416
|
+
}
|
|
1417
|
+
function isCompactionSkipReason(reason) {
|
|
1418
|
+
const text = normalizeOptionalLowercaseString(reason) ?? "";
|
|
1419
|
+
return text.includes("nothing to compact") || text.includes("below threshold") || text.includes("already compacted") || text.includes("no real conversation messages");
|
|
1420
|
+
}
|
|
1421
|
+
function formatCompactionReason(reason) {
|
|
1422
|
+
const text = normalizeOptionalString(reason);
|
|
1423
|
+
if (!text) return;
|
|
1424
|
+
const lower = normalizeLowercaseStringOrEmpty(text);
|
|
1425
|
+
if (lower.includes("nothing to compact")) return "nothing compactable in this session yet";
|
|
1426
|
+
if (lower.includes("below threshold")) return "context is below the compaction threshold";
|
|
1427
|
+
if (lower.includes("already compacted")) return "session was already compacted recently";
|
|
1428
|
+
if (lower.includes("no real conversation messages")) return "no real conversation messages yet";
|
|
1429
|
+
return text;
|
|
1430
|
+
}
|
|
1431
|
+
const handleCompactCommand = async (params) => {
|
|
1432
|
+
if (!(params.command.commandBodyNormalized === "/compact" || params.command.commandBodyNormalized.startsWith("/compact "))) return null;
|
|
1433
|
+
if (!params.command.isAuthorizedSender) {
|
|
1434
|
+
logVerbose(`Ignoring /compact from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
1435
|
+
return { shouldContinue: false };
|
|
1436
|
+
}
|
|
1437
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
1438
|
+
if (!targetSessionEntry?.sessionId) return {
|
|
1439
|
+
shouldContinue: false,
|
|
1440
|
+
reply: { text: "āļø Compaction unavailable (missing session id)." }
|
|
1441
|
+
};
|
|
1442
|
+
const runtime = await loadCompactRuntime();
|
|
1443
|
+
const sessionId = targetSessionEntry.sessionId;
|
|
1444
|
+
if (runtime.isEmbeddedPiRunActive(sessionId)) {
|
|
1445
|
+
runtime.abortEmbeddedPiRun(sessionId);
|
|
1446
|
+
await runtime.waitForEmbeddedPiRunEnd(sessionId, 15e3);
|
|
1447
|
+
}
|
|
1448
|
+
const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
|
|
1449
|
+
sessionKey: params.sessionKey,
|
|
1450
|
+
config: params.cfg
|
|
1451
|
+
}) : params.agentId ?? "main";
|
|
1452
|
+
const sessionAgentDir = sessionAgentId === (params.agentId ?? "main") && params.agentDir ? params.agentDir : resolveAgentDir(params.cfg, sessionAgentId);
|
|
1453
|
+
const customInstructions = extractCompactInstructions({
|
|
1454
|
+
rawBody: params.ctx.CommandBody ?? params.ctx.RawBody ?? params.ctx.Body,
|
|
1455
|
+
ctx: params.ctx,
|
|
1456
|
+
cfg: params.cfg,
|
|
1457
|
+
agentId: sessionAgentId,
|
|
1458
|
+
isGroup: params.isGroup
|
|
1459
|
+
});
|
|
1460
|
+
const result = await runtime.compactEmbeddedPiSession({
|
|
1461
|
+
sessionId,
|
|
1462
|
+
sessionKey: params.sessionKey,
|
|
1463
|
+
allowGatewaySubagentBinding: true,
|
|
1464
|
+
messageChannel: params.command.channel,
|
|
1465
|
+
groupId: targetSessionEntry.groupId,
|
|
1466
|
+
groupChannel: targetSessionEntry.groupChannel,
|
|
1467
|
+
groupSpace: targetSessionEntry.space,
|
|
1468
|
+
spawnedBy: targetSessionEntry.spawnedBy,
|
|
1469
|
+
senderId: params.command.senderId,
|
|
1470
|
+
senderName: params.ctx.SenderName,
|
|
1471
|
+
senderUsername: params.ctx.SenderUsername,
|
|
1472
|
+
senderE164: params.ctx.SenderE164,
|
|
1473
|
+
sessionFile: runtime.resolveSessionFilePath(sessionId, targetSessionEntry, runtime.resolveSessionFilePathOptions({
|
|
1474
|
+
agentId: sessionAgentId,
|
|
1475
|
+
storePath: params.storePath
|
|
1476
|
+
})),
|
|
1477
|
+
workspaceDir: params.workspaceDir,
|
|
1478
|
+
agentDir: sessionAgentDir,
|
|
1479
|
+
config: params.cfg,
|
|
1480
|
+
skillsSnapshot: targetSessionEntry.skillsSnapshot,
|
|
1481
|
+
provider: params.provider,
|
|
1482
|
+
model: params.model,
|
|
1483
|
+
agentHarnessId: targetSessionEntry.sessionId === sessionId ? targetSessionEntry.agentHarnessId : void 0,
|
|
1484
|
+
thinkLevel: params.resolvedThinkLevel ?? await params.resolveDefaultThinkingLevel(),
|
|
1485
|
+
bashElevated: {
|
|
1486
|
+
enabled: false,
|
|
1487
|
+
allowed: false,
|
|
1488
|
+
defaultLevel: "off"
|
|
1489
|
+
},
|
|
1490
|
+
customInstructions,
|
|
1491
|
+
trigger: "manual",
|
|
1492
|
+
senderIsOwner: params.command.senderIsOwner,
|
|
1493
|
+
ownerNumbers: params.command.ownerList.length > 0 ? params.command.ownerList : void 0
|
|
1494
|
+
});
|
|
1495
|
+
const compactLabel = result.ok || isCompactionSkipReason(result.reason) ? result.compacted ? result.result?.tokensBefore != null && result.result?.tokensAfter != null ? `Compacted (${runtime.formatTokenCount(result.result.tokensBefore)} ā ${runtime.formatTokenCount(result.result.tokensAfter)})` : result.result?.tokensBefore ? `Compacted (${runtime.formatTokenCount(result.result.tokensBefore)} before)` : "Compacted" : "Compaction skipped" : "Compaction failed";
|
|
1496
|
+
if (result.ok && result.compacted) await runtime.incrementCompactionCount({
|
|
1497
|
+
cfg: params.cfg,
|
|
1498
|
+
sessionEntry: targetSessionEntry,
|
|
1499
|
+
sessionStore: params.sessionStore,
|
|
1500
|
+
sessionKey: params.sessionKey,
|
|
1501
|
+
storePath: params.storePath,
|
|
1502
|
+
tokensAfter: result.result?.tokensAfter
|
|
1503
|
+
});
|
|
1504
|
+
const totalTokens = result.result?.tokensAfter ?? runtime.resolveFreshSessionTotalTokens(targetSessionEntry);
|
|
1505
|
+
const contextSummary = runtime.formatContextUsageShort(typeof totalTokens === "number" && totalTokens > 0 ? totalTokens : null, params.contextTokens ?? targetSessionEntry.contextTokens ?? null);
|
|
1506
|
+
const reason = formatCompactionReason(result.reason);
|
|
1507
|
+
const line = reason ? `${compactLabel}: ${reason} ⢠${contextSummary}` : `${compactLabel} ⢠${contextSummary}`;
|
|
1508
|
+
runtime.enqueueSystemEvent(line, { sessionKey: params.sessionKey });
|
|
1509
|
+
return {
|
|
1510
|
+
shouldContinue: false,
|
|
1511
|
+
reply: { text: `āļø ${line}` }
|
|
1512
|
+
};
|
|
1513
|
+
};
|
|
1514
|
+
//#endregion
|
|
1515
|
+
//#region src/auto-reply/reply/commands-slash-parse.ts
|
|
1516
|
+
function parseSlashCommandActionArgs(raw, slash) {
|
|
1517
|
+
const trimmed = raw.trim();
|
|
1518
|
+
const slashLower = normalizeLowercaseStringOrEmpty(slash);
|
|
1519
|
+
if (!normalizeLowercaseStringOrEmpty(trimmed).startsWith(slashLower)) return { kind: "no-match" };
|
|
1520
|
+
const rest = trimmed.slice(slash.length).trim();
|
|
1521
|
+
if (!rest) return { kind: "empty" };
|
|
1522
|
+
const match = rest.match(/^(\S+)(?:\s+([\s\S]+))?$/);
|
|
1523
|
+
if (!match) return { kind: "invalid" };
|
|
1524
|
+
return {
|
|
1525
|
+
kind: "parsed",
|
|
1526
|
+
action: normalizeLowercaseStringOrEmpty(match[1]),
|
|
1527
|
+
args: (match[2] ?? "").trim()
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
function parseSlashCommandOrNull(raw, slash, opts) {
|
|
1531
|
+
const parsed = parseSlashCommandActionArgs(raw, slash);
|
|
1532
|
+
if (parsed.kind === "no-match") return null;
|
|
1533
|
+
if (parsed.kind === "invalid") return {
|
|
1534
|
+
ok: false,
|
|
1535
|
+
message: opts.invalidMessage
|
|
1536
|
+
};
|
|
1537
|
+
if (parsed.kind === "empty") return {
|
|
1538
|
+
ok: true,
|
|
1539
|
+
action: opts.defaultAction ?? "show",
|
|
1540
|
+
args: ""
|
|
1541
|
+
};
|
|
1542
|
+
return {
|
|
1543
|
+
ok: true,
|
|
1544
|
+
action: parsed.action,
|
|
1545
|
+
args: parsed.args
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
//#endregion
|
|
1549
|
+
//#region src/auto-reply/reply/commands-setunset.ts
|
|
1550
|
+
function parseSetUnsetCommand(params) {
|
|
1551
|
+
const action = params.action;
|
|
1552
|
+
const args = params.args.trim();
|
|
1553
|
+
if (action === "unset") {
|
|
1554
|
+
if (!args) return {
|
|
1555
|
+
kind: "error",
|
|
1556
|
+
message: `Usage: ${params.slash} unset path`
|
|
1557
|
+
};
|
|
1558
|
+
return {
|
|
1559
|
+
kind: "unset",
|
|
1560
|
+
path: args
|
|
1561
|
+
};
|
|
1562
|
+
}
|
|
1563
|
+
if (!args) return {
|
|
1564
|
+
kind: "error",
|
|
1565
|
+
message: `Usage: ${params.slash} set path=value`
|
|
1566
|
+
};
|
|
1567
|
+
const eqIndex = args.indexOf("=");
|
|
1568
|
+
if (eqIndex <= 0) return {
|
|
1569
|
+
kind: "error",
|
|
1570
|
+
message: `Usage: ${params.slash} set path=value`
|
|
1571
|
+
};
|
|
1572
|
+
const path = args.slice(0, eqIndex).trim();
|
|
1573
|
+
const rawValue = args.slice(eqIndex + 1);
|
|
1574
|
+
if (!path) return {
|
|
1575
|
+
kind: "error",
|
|
1576
|
+
message: `Usage: ${params.slash} set path=value`
|
|
1577
|
+
};
|
|
1578
|
+
const parsed = parseConfigValue(rawValue);
|
|
1579
|
+
if (parsed.error) return {
|
|
1580
|
+
kind: "error",
|
|
1581
|
+
message: parsed.error
|
|
1582
|
+
};
|
|
1583
|
+
return {
|
|
1584
|
+
kind: "set",
|
|
1585
|
+
path,
|
|
1586
|
+
value: parsed.value
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
function parseSetUnsetCommandAction(params) {
|
|
1590
|
+
if (params.action !== "set" && params.action !== "unset") return null;
|
|
1591
|
+
const parsed = parseSetUnsetCommand({
|
|
1592
|
+
slash: params.slash,
|
|
1593
|
+
action: params.action,
|
|
1594
|
+
args: params.args
|
|
1595
|
+
});
|
|
1596
|
+
if (parsed.kind === "error") return params.onError(parsed.message);
|
|
1597
|
+
return parsed.kind === "set" ? params.onSet(parsed.path, parsed.value) : params.onUnset(parsed.path);
|
|
1598
|
+
}
|
|
1599
|
+
function parseSlashCommandWithSetUnset(params) {
|
|
1600
|
+
const parsed = parseSlashCommandOrNull(params.raw, params.slash, { invalidMessage: params.invalidMessage });
|
|
1601
|
+
if (!parsed) return null;
|
|
1602
|
+
if (!parsed.ok) return params.onError(parsed.message);
|
|
1603
|
+
const { action, args } = parsed;
|
|
1604
|
+
const setUnset = parseSetUnsetCommandAction({
|
|
1605
|
+
slash: params.slash,
|
|
1606
|
+
action,
|
|
1607
|
+
args,
|
|
1608
|
+
onSet: params.onSet,
|
|
1609
|
+
onUnset: params.onUnset,
|
|
1610
|
+
onError: params.onError
|
|
1611
|
+
});
|
|
1612
|
+
if (setUnset) return setUnset;
|
|
1613
|
+
const knownAction = params.onKnownAction(action, args);
|
|
1614
|
+
if (knownAction) return knownAction;
|
|
1615
|
+
return params.onError(params.usageMessage);
|
|
1616
|
+
}
|
|
1617
|
+
//#endregion
|
|
1618
|
+
//#region src/auto-reply/reply/commands-setunset-standard.ts
|
|
1619
|
+
function parseStandardSetUnsetSlashCommand(params) {
|
|
1620
|
+
return parseSlashCommandWithSetUnset({
|
|
1621
|
+
raw: params.raw,
|
|
1622
|
+
slash: params.slash,
|
|
1623
|
+
invalidMessage: params.invalidMessage,
|
|
1624
|
+
usageMessage: params.usageMessage,
|
|
1625
|
+
onKnownAction: params.onKnownAction,
|
|
1626
|
+
onSet: params.onSet ?? ((path, value) => ({
|
|
1627
|
+
action: "set",
|
|
1628
|
+
path,
|
|
1629
|
+
value
|
|
1630
|
+
})),
|
|
1631
|
+
onUnset: params.onUnset ?? ((path) => ({
|
|
1632
|
+
action: "unset",
|
|
1633
|
+
path
|
|
1634
|
+
})),
|
|
1635
|
+
onError: params.onError ?? ((message) => ({
|
|
1636
|
+
action: "error",
|
|
1637
|
+
message
|
|
1638
|
+
}))
|
|
1639
|
+
});
|
|
1640
|
+
}
|
|
1641
|
+
//#endregion
|
|
1642
|
+
//#region src/auto-reply/reply/config-commands.ts
|
|
1643
|
+
function parseConfigCommand(raw) {
|
|
1644
|
+
return parseStandardSetUnsetSlashCommand({
|
|
1645
|
+
raw,
|
|
1646
|
+
slash: "/config",
|
|
1647
|
+
invalidMessage: "Invalid /config syntax.",
|
|
1648
|
+
usageMessage: "Usage: /config show|set|unset",
|
|
1649
|
+
onKnownAction: (action, args) => {
|
|
1650
|
+
if (action === "show" || action === "get") return {
|
|
1651
|
+
action: "show",
|
|
1652
|
+
path: args || void 0
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
//#endregion
|
|
1658
|
+
//#region src/auto-reply/reply/debug-commands.ts
|
|
1659
|
+
function parseDebugCommand(raw) {
|
|
1660
|
+
return parseStandardSetUnsetSlashCommand({
|
|
1661
|
+
raw,
|
|
1662
|
+
slash: "/debug",
|
|
1663
|
+
invalidMessage: "Invalid /debug syntax.",
|
|
1664
|
+
usageMessage: "Usage: /debug show|set|unset|reset",
|
|
1665
|
+
onKnownAction: (action) => {
|
|
1666
|
+
if (action === "show") return { action: "show" };
|
|
1667
|
+
if (action === "reset") return { action: "reset" };
|
|
1668
|
+
}
|
|
1669
|
+
});
|
|
1670
|
+
}
|
|
1671
|
+
//#endregion
|
|
1672
|
+
//#region src/auto-reply/reply/commands-config.ts
|
|
1673
|
+
const handleConfigCommand = async (params, allowTextCommands) => {
|
|
1674
|
+
if (!allowTextCommands) return null;
|
|
1675
|
+
const configCommand = parseConfigCommand(params.command.commandBodyNormalized);
|
|
1676
|
+
if (!configCommand) return null;
|
|
1677
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/config");
|
|
1678
|
+
if (unauthorized) return unauthorized;
|
|
1679
|
+
const nonOwner = configCommand.action === "show" && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/config");
|
|
1680
|
+
if (nonOwner) return nonOwner;
|
|
1681
|
+
const disabled = requireCommandFlagEnabled(params.cfg, {
|
|
1682
|
+
label: "/config",
|
|
1683
|
+
configKey: "config"
|
|
1684
|
+
});
|
|
1685
|
+
if (disabled) return disabled;
|
|
1686
|
+
if (configCommand.action === "error") return {
|
|
1687
|
+
shouldContinue: false,
|
|
1688
|
+
reply: { text: `ā ļø ${configCommand.message}` }
|
|
1689
|
+
};
|
|
1690
|
+
let parsedWritePath;
|
|
1691
|
+
if (configCommand.action === "set" || configCommand.action === "unset") {
|
|
1692
|
+
const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
|
|
1693
|
+
label: "/config write",
|
|
1694
|
+
allowedScopes: ["operator.admin"],
|
|
1695
|
+
missingText: "ā /config set|unset requires operator.admin for gateway clients."
|
|
1696
|
+
});
|
|
1697
|
+
if (missingAdminScope) return missingAdminScope;
|
|
1698
|
+
const parsedPath = parseConfigPath(configCommand.path);
|
|
1699
|
+
if (!parsedPath.ok || !parsedPath.path) return {
|
|
1700
|
+
shouldContinue: false,
|
|
1701
|
+
reply: { text: `ā ļø ${parsedPath.error ?? "Invalid path."}` }
|
|
1702
|
+
};
|
|
1703
|
+
parsedWritePath = parsedPath.path;
|
|
1704
|
+
const channelId = params.command.channelId ?? normalizeChannelId(params.command.channel);
|
|
1705
|
+
const deniedText = resolveConfigWriteDeniedText({
|
|
1706
|
+
cfg: params.cfg,
|
|
1707
|
+
channel: params.command.channel,
|
|
1708
|
+
channelId,
|
|
1709
|
+
accountId: resolveChannelAccountId({
|
|
1710
|
+
cfg: params.cfg,
|
|
1711
|
+
ctx: params.ctx,
|
|
1712
|
+
command: params.command
|
|
1713
|
+
}),
|
|
1714
|
+
gatewayClientScopes: params.ctx.GatewayClientScopes,
|
|
1715
|
+
target: resolveConfigWriteTargetFromPath(parsedWritePath)
|
|
1716
|
+
});
|
|
1717
|
+
if (deniedText) return {
|
|
1718
|
+
shouldContinue: false,
|
|
1719
|
+
reply: { text: deniedText }
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
const snapshot = await readConfigFileSnapshot();
|
|
1723
|
+
if (!snapshot.valid || !snapshot.parsed || typeof snapshot.parsed !== "object") return {
|
|
1724
|
+
shouldContinue: false,
|
|
1725
|
+
reply: { text: "ā ļø Config file is invalid; fix it before using /config." }
|
|
1726
|
+
};
|
|
1727
|
+
const parsedBase = structuredClone(snapshot.parsed);
|
|
1728
|
+
if (configCommand.action === "show") {
|
|
1729
|
+
const pathRaw = normalizeOptionalString(configCommand.path);
|
|
1730
|
+
if (pathRaw) {
|
|
1731
|
+
const parsedPath = parseConfigPath(pathRaw);
|
|
1732
|
+
if (!parsedPath.ok || !parsedPath.path) return {
|
|
1733
|
+
shouldContinue: false,
|
|
1734
|
+
reply: { text: `ā ļø ${parsedPath.error ?? "Invalid path."}` }
|
|
1735
|
+
};
|
|
1736
|
+
const value = getConfigValueAtPath(parsedBase, parsedPath.path);
|
|
1737
|
+
return {
|
|
1738
|
+
shouldContinue: false,
|
|
1739
|
+
reply: { text: `āļø Config ${pathRaw}:\n\`\`\`json\n${JSON.stringify(value ?? null, null, 2)}\n\`\`\`` }
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
return {
|
|
1743
|
+
shouldContinue: false,
|
|
1744
|
+
reply: { text: `āļø Config (raw):\n\`\`\`json\n${JSON.stringify(parsedBase, null, 2)}\n\`\`\`` }
|
|
1745
|
+
};
|
|
1746
|
+
}
|
|
1747
|
+
if (configCommand.action === "unset") {
|
|
1748
|
+
if (!unsetConfigValueAtPath(parsedBase, parsedWritePath ?? [])) return {
|
|
1749
|
+
shouldContinue: false,
|
|
1750
|
+
reply: { text: `āļø No config value found for ${configCommand.path}.` }
|
|
1751
|
+
};
|
|
1752
|
+
const validated = validateConfigObjectWithPlugins(parsedBase);
|
|
1753
|
+
if (!validated.ok) {
|
|
1754
|
+
const issue = validated.issues[0];
|
|
1755
|
+
return {
|
|
1756
|
+
shouldContinue: false,
|
|
1757
|
+
reply: { text: `ā ļø Config invalid after unset (${issue.path}: ${issue.message}).` }
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
await writeConfigFile(validated.config);
|
|
1761
|
+
return {
|
|
1762
|
+
shouldContinue: false,
|
|
1763
|
+
reply: { text: `āļø Config updated: ${configCommand.path} removed.` }
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
if (configCommand.action === "set") {
|
|
1767
|
+
setConfigValueAtPath(parsedBase, parsedWritePath ?? [], configCommand.value);
|
|
1768
|
+
const validated = validateConfigObjectWithPlugins(parsedBase);
|
|
1769
|
+
if (!validated.ok) {
|
|
1770
|
+
const issue = validated.issues[0];
|
|
1771
|
+
return {
|
|
1772
|
+
shouldContinue: false,
|
|
1773
|
+
reply: { text: `ā ļø Config invalid after set (${issue.path}: ${issue.message}).` }
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
1776
|
+
await writeConfigFile(validated.config);
|
|
1777
|
+
const valueLabel = typeof configCommand.value === "string" ? `"${configCommand.value}"` : JSON.stringify(configCommand.value);
|
|
1778
|
+
return {
|
|
1779
|
+
shouldContinue: false,
|
|
1780
|
+
reply: { text: `āļø Config updated: ${configCommand.path}=${valueLabel ?? "null"}` }
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
return null;
|
|
1784
|
+
};
|
|
1785
|
+
const handleDebugCommand = async (params, allowTextCommands) => {
|
|
1786
|
+
if (!allowTextCommands) return null;
|
|
1787
|
+
const debugCommand = parseDebugCommand(params.command.commandBodyNormalized);
|
|
1788
|
+
if (!debugCommand) return null;
|
|
1789
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/debug");
|
|
1790
|
+
if (unauthorized) return unauthorized;
|
|
1791
|
+
const nonOwner = rejectNonOwnerCommand(params, "/debug");
|
|
1792
|
+
if (nonOwner) return nonOwner;
|
|
1793
|
+
const disabled = requireCommandFlagEnabled(params.cfg, {
|
|
1794
|
+
label: "/debug",
|
|
1795
|
+
configKey: "debug"
|
|
1796
|
+
});
|
|
1797
|
+
if (disabled) return disabled;
|
|
1798
|
+
if (debugCommand.action === "error") return {
|
|
1799
|
+
shouldContinue: false,
|
|
1800
|
+
reply: { text: `ā ļø ${debugCommand.message}` }
|
|
1801
|
+
};
|
|
1802
|
+
if (debugCommand.action === "show") {
|
|
1803
|
+
const overrides = getConfigOverrides();
|
|
1804
|
+
if (!(Object.keys(overrides).length > 0)) return {
|
|
1805
|
+
shouldContinue: false,
|
|
1806
|
+
reply: { text: "āļø Debug overrides: (none)" }
|
|
1807
|
+
};
|
|
1808
|
+
return {
|
|
1809
|
+
shouldContinue: false,
|
|
1810
|
+
reply: { text: `āļø Debug overrides (memory-only):\n\`\`\`json\n${JSON.stringify(overrides, null, 2)}\n\`\`\`` }
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
if (debugCommand.action === "reset") {
|
|
1814
|
+
resetConfigOverrides();
|
|
1815
|
+
return {
|
|
1816
|
+
shouldContinue: false,
|
|
1817
|
+
reply: { text: "āļø Debug overrides cleared; using config on disk." }
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
if (debugCommand.action === "unset") {
|
|
1821
|
+
const result = unsetConfigOverride(debugCommand.path);
|
|
1822
|
+
if (!result.ok) return {
|
|
1823
|
+
shouldContinue: false,
|
|
1824
|
+
reply: { text: `ā ļø ${result.error ?? "Invalid path."}` }
|
|
1825
|
+
};
|
|
1826
|
+
if (!result.removed) return {
|
|
1827
|
+
shouldContinue: false,
|
|
1828
|
+
reply: { text: `āļø No debug override found for ${debugCommand.path}.` }
|
|
1829
|
+
};
|
|
1830
|
+
return {
|
|
1831
|
+
shouldContinue: false,
|
|
1832
|
+
reply: { text: `āļø Debug override removed for ${debugCommand.path}.` }
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
if (debugCommand.action === "set") {
|
|
1836
|
+
const result = setConfigOverride(debugCommand.path, debugCommand.value);
|
|
1837
|
+
if (!result.ok) return {
|
|
1838
|
+
shouldContinue: false,
|
|
1839
|
+
reply: { text: `ā ļø ${result.error ?? "Invalid override."}` }
|
|
1840
|
+
};
|
|
1841
|
+
const valueLabel = typeof debugCommand.value === "string" ? `"${debugCommand.value}"` : JSON.stringify(debugCommand.value);
|
|
1842
|
+
return {
|
|
1843
|
+
shouldContinue: false,
|
|
1844
|
+
reply: { text: `āļø Debug override set: ${debugCommand.path}=${valueLabel ?? "null"}` }
|
|
1845
|
+
};
|
|
1846
|
+
}
|
|
1847
|
+
return null;
|
|
1848
|
+
};
|
|
1849
|
+
//#endregion
|
|
1850
|
+
//#region src/auto-reply/reply/commands-context-report.ts
|
|
1851
|
+
function formatInt(n) {
|
|
1852
|
+
return new Intl.NumberFormat("en-US").format(n);
|
|
1853
|
+
}
|
|
1854
|
+
function formatCharsAndTokens(chars) {
|
|
1855
|
+
return `${formatInt(chars)} chars (~${formatInt(estimateTokensFromChars(chars))} tok)`;
|
|
1856
|
+
}
|
|
1857
|
+
function parseContextArgs(commandBodyNormalized) {
|
|
1858
|
+
if (commandBodyNormalized === "/context") return "";
|
|
1859
|
+
if (commandBodyNormalized.startsWith("/context ")) return commandBodyNormalized.slice(8).trim();
|
|
1860
|
+
return "";
|
|
1861
|
+
}
|
|
1862
|
+
function formatListTop(entries, cap) {
|
|
1863
|
+
const sorted = [...entries].toSorted((a, b) => b.value - a.value);
|
|
1864
|
+
const top = sorted.slice(0, cap);
|
|
1865
|
+
const omitted = Math.max(0, sorted.length - top.length);
|
|
1866
|
+
return {
|
|
1867
|
+
lines: top.map((e) => `- ${e.name}: ${formatCharsAndTokens(e.value)}`),
|
|
1868
|
+
omitted
|
|
1869
|
+
};
|
|
1870
|
+
}
|
|
1871
|
+
async function resolveContextReport(params) {
|
|
1872
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
1873
|
+
const existing = targetSessionEntry?.systemPromptReport;
|
|
1874
|
+
if (existing && existing.source === "run") return existing;
|
|
1875
|
+
const bootstrapMaxChars = resolveBootstrapMaxChars(params.cfg);
|
|
1876
|
+
const bootstrapTotalMaxChars = resolveBootstrapTotalMaxChars(params.cfg);
|
|
1877
|
+
const { resolveCommandsSystemPromptBundle } = await import("./commands-system-prompt-DTUkp9TH.js");
|
|
1878
|
+
const { systemPrompt, tools, skillsPrompt, bootstrapFiles, injectedFiles, sandboxRuntime } = await resolveCommandsSystemPromptBundle(params);
|
|
1879
|
+
return buildSystemPromptReport({
|
|
1880
|
+
source: "estimate",
|
|
1881
|
+
generatedAt: Date.now(),
|
|
1882
|
+
sessionId: targetSessionEntry?.sessionId,
|
|
1883
|
+
sessionKey: params.sessionKey,
|
|
1884
|
+
provider: params.provider,
|
|
1885
|
+
model: params.model,
|
|
1886
|
+
workspaceDir: params.workspaceDir,
|
|
1887
|
+
bootstrapMaxChars,
|
|
1888
|
+
bootstrapTotalMaxChars,
|
|
1889
|
+
sandbox: {
|
|
1890
|
+
mode: sandboxRuntime.mode,
|
|
1891
|
+
sandboxed: sandboxRuntime.sandboxed
|
|
1892
|
+
},
|
|
1893
|
+
systemPrompt,
|
|
1894
|
+
bootstrapFiles,
|
|
1895
|
+
injectedFiles,
|
|
1896
|
+
skillsPrompt,
|
|
1897
|
+
tools
|
|
1898
|
+
});
|
|
1899
|
+
}
|
|
1900
|
+
async function buildContextReply(params) {
|
|
1901
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
1902
|
+
const sub = normalizeLowercaseStringOrEmpty(parseContextArgs(params.command.commandBodyNormalized).split(/\s+/).find(Boolean));
|
|
1903
|
+
if (!sub || sub === "help") return { text: [
|
|
1904
|
+
"š§ /context",
|
|
1905
|
+
"",
|
|
1906
|
+
"What counts as context (high-level), plus a breakdown mode.",
|
|
1907
|
+
"",
|
|
1908
|
+
"Try:",
|
|
1909
|
+
"- /context list (short breakdown)",
|
|
1910
|
+
"- /context detail (per-file + per-tool + per-skill + system prompt size)",
|
|
1911
|
+
"- /context json (same, machine-readable)",
|
|
1912
|
+
"",
|
|
1913
|
+
"Inline shortcut = a command token inside a normal message (e.g. āhey /statusā). It runs immediately (allowlisted senders only) and is stripped before the model sees the remaining text."
|
|
1914
|
+
].join("\n") };
|
|
1915
|
+
const report = await resolveContextReport(params);
|
|
1916
|
+
const cachedContextUsageTokens = resolveFreshSessionTotalTokens(targetSessionEntry);
|
|
1917
|
+
const session = {
|
|
1918
|
+
totalTokens: targetSessionEntry?.totalTokens ?? null,
|
|
1919
|
+
totalTokensFresh: targetSessionEntry?.totalTokensFresh ?? null,
|
|
1920
|
+
inputTokens: targetSessionEntry?.inputTokens ?? null,
|
|
1921
|
+
outputTokens: targetSessionEntry?.outputTokens ?? null,
|
|
1922
|
+
contextTokens: params.contextTokens ?? null
|
|
1923
|
+
};
|
|
1924
|
+
if (sub === "json") return { text: JSON.stringify({
|
|
1925
|
+
report,
|
|
1926
|
+
session
|
|
1927
|
+
}, null, 2) };
|
|
1928
|
+
if (sub !== "list" && sub !== "show" && sub !== "detail" && sub !== "deep") return { text: ["Unknown /context mode.", "Use: /context, /context list, /context detail, or /context json"].join("\n") };
|
|
1929
|
+
const fileLines = report.injectedWorkspaceFiles.map((f) => {
|
|
1930
|
+
const status = f.missing ? "MISSING" : f.truncated ? "TRUNCATED" : "OK";
|
|
1931
|
+
const raw = f.missing ? "0" : formatCharsAndTokens(f.rawChars);
|
|
1932
|
+
const injected = f.missing ? "0" : formatCharsAndTokens(f.injectedChars);
|
|
1933
|
+
return `- ${f.name}: ${status} | raw ${raw} | injected ${injected}`;
|
|
1934
|
+
});
|
|
1935
|
+
const sandboxLine = `Sandbox: mode=${report.sandbox?.mode ?? "unknown"} sandboxed=${report.sandbox?.sandboxed ?? false}`;
|
|
1936
|
+
const toolSchemaLine = `Tool schemas (JSON): ${formatCharsAndTokens(report.tools.schemaChars)} (counts toward context; not shown as text)`;
|
|
1937
|
+
const toolListLine = `Tool list (system prompt text): ${formatCharsAndTokens(report.tools.listChars)}`;
|
|
1938
|
+
const skillNameSet = new Set(report.skills.entries.map((s) => s.name));
|
|
1939
|
+
const skillNames = Array.from(skillNameSet);
|
|
1940
|
+
const toolNames = report.tools.entries.map((t) => t.name);
|
|
1941
|
+
const formatNameList = (names, cap) => names.length <= cap ? names.join(", ") : `${names.slice(0, cap).join(", ")}, ⦠(+${names.length - cap} more)`;
|
|
1942
|
+
const skillsLine = `Skills list (system prompt text): ${formatCharsAndTokens(report.skills.promptChars)} (${skillNameSet.size} skills)`;
|
|
1943
|
+
const skillsNamesLine = skillNameSet.size ? `Skills: ${formatNameList(skillNames, 20)}` : "Skills: (none)";
|
|
1944
|
+
const toolsNamesLine = toolNames.length ? `Tools: ${formatNameList(toolNames, 30)}` : "Tools: (none)";
|
|
1945
|
+
const systemPromptLine = `System prompt (${report.source}): ${formatCharsAndTokens(report.systemPrompt.chars)} (Project Context ${formatCharsAndTokens(report.systemPrompt.projectContextChars)})`;
|
|
1946
|
+
const workspaceLabel = report.workspaceDir ?? params.workspaceDir;
|
|
1947
|
+
const bootstrapMaxChars = typeof report.bootstrapMaxChars === "number" && Number.isFinite(report.bootstrapMaxChars) && report.bootstrapMaxChars > 0 ? report.bootstrapMaxChars : resolveBootstrapMaxChars(params.cfg);
|
|
1948
|
+
const bootstrapTotalMaxChars = typeof report.bootstrapTotalMaxChars === "number" && Number.isFinite(report.bootstrapTotalMaxChars) && report.bootstrapTotalMaxChars > 0 ? report.bootstrapTotalMaxChars : resolveBootstrapTotalMaxChars(params.cfg);
|
|
1949
|
+
const bootstrapMaxLabel = `${formatInt(bootstrapMaxChars)} chars`;
|
|
1950
|
+
const bootstrapTotalLabel = `${formatInt(bootstrapTotalMaxChars)} chars`;
|
|
1951
|
+
const bootstrapAnalysis = analyzeBootstrapBudget({
|
|
1952
|
+
files: report.injectedWorkspaceFiles,
|
|
1953
|
+
bootstrapMaxChars,
|
|
1954
|
+
bootstrapTotalMaxChars
|
|
1955
|
+
});
|
|
1956
|
+
const truncatedBootstrapFiles = bootstrapAnalysis.truncatedFiles;
|
|
1957
|
+
const truncationCauseCounts = truncatedBootstrapFiles.reduce((acc, file) => {
|
|
1958
|
+
for (const cause of file.causes) if (cause === "per-file-limit") acc.perFile += 1;
|
|
1959
|
+
else if (cause === "total-limit") acc.total += 1;
|
|
1960
|
+
return acc;
|
|
1961
|
+
}, {
|
|
1962
|
+
perFile: 0,
|
|
1963
|
+
total: 0
|
|
1964
|
+
});
|
|
1965
|
+
const truncationCauseParts = [truncationCauseCounts.perFile > 0 ? `${truncationCauseCounts.perFile} file(s) exceeded max/file` : null, truncationCauseCounts.total > 0 ? `${truncationCauseCounts.total} file(s) hit max/total` : null].filter(Boolean);
|
|
1966
|
+
const bootstrapWarningLines = truncatedBootstrapFiles.length > 0 ? [
|
|
1967
|
+
`ā Bootstrap context is over configured limits: ${truncatedBootstrapFiles.length} file(s) truncated (${formatInt(bootstrapAnalysis.totals.rawChars)} raw chars -> ${formatInt(bootstrapAnalysis.totals.injectedChars)} injected chars).`,
|
|
1968
|
+
...truncationCauseParts.length ? [`Causes: ${truncationCauseParts.join("; ")}.`] : [],
|
|
1969
|
+
"Tip: increase `agents.defaults.bootstrapMaxChars` and/or `agents.defaults.bootstrapTotalMaxChars` if this truncation is not intentional."
|
|
1970
|
+
] : [];
|
|
1971
|
+
const contextWindowLabel = session.contextTokens != null ? formatInt(session.contextTokens) : "?";
|
|
1972
|
+
const totalsLine = cachedContextUsageTokens != null ? `Session tokens (cached): ${formatInt(cachedContextUsageTokens)} total / ctx=${contextWindowLabel}` : `Session tokens (cached): unknown / ctx=${contextWindowLabel}`;
|
|
1973
|
+
const sharedContextLines = [
|
|
1974
|
+
`Workspace: ${workspaceLabel}`,
|
|
1975
|
+
`Bootstrap max/file: ${bootstrapMaxLabel}`,
|
|
1976
|
+
`Bootstrap max/total: ${bootstrapTotalLabel}`,
|
|
1977
|
+
sandboxLine,
|
|
1978
|
+
systemPromptLine,
|
|
1979
|
+
...bootstrapWarningLines.length ? ["", ...bootstrapWarningLines] : [],
|
|
1980
|
+
"",
|
|
1981
|
+
"Injected workspace files:",
|
|
1982
|
+
...fileLines,
|
|
1983
|
+
"",
|
|
1984
|
+
skillsLine,
|
|
1985
|
+
skillsNamesLine
|
|
1986
|
+
];
|
|
1987
|
+
if (sub === "detail" || sub === "deep") {
|
|
1988
|
+
const perSkill = formatListTop(report.skills.entries.map((s) => ({
|
|
1989
|
+
name: s.name,
|
|
1990
|
+
value: s.blockChars
|
|
1991
|
+
})), 30);
|
|
1992
|
+
const perToolSchema = formatListTop(report.tools.entries.map((t) => ({
|
|
1993
|
+
name: t.name,
|
|
1994
|
+
value: t.schemaChars
|
|
1995
|
+
})), 30);
|
|
1996
|
+
const perToolSummary = formatListTop(report.tools.entries.map((t) => ({
|
|
1997
|
+
name: t.name,
|
|
1998
|
+
value: t.summaryChars
|
|
1999
|
+
})), 30);
|
|
2000
|
+
const toolPropsLines = report.tools.entries.filter((t) => t.propertiesCount != null).toSorted((a, b) => (b.propertiesCount ?? 0) - (a.propertiesCount ?? 0)).slice(0, 30).map((t) => `- ${t.name}: ${t.propertiesCount} params`);
|
|
2001
|
+
const trackedPromptChars = report.systemPrompt.chars + report.tools.schemaChars;
|
|
2002
|
+
const trackedPromptLine = `Tracked prompt estimate: ${formatCharsAndTokens(trackedPromptChars)}`;
|
|
2003
|
+
const actualContextLine = cachedContextUsageTokens != null ? `Actual context usage (cached): ${formatInt(cachedContextUsageTokens)} tok` : "Actual context usage (cached): unavailable";
|
|
2004
|
+
const overheadTokens = cachedContextUsageTokens != null ? cachedContextUsageTokens - estimateTokensFromChars(trackedPromptChars) : null;
|
|
2005
|
+
const overheadLine = overheadTokens == null ? null : overheadTokens > 0 ? `Untracked provider/runtime overhead: ~${formatInt(overheadTokens)} tok` : "Untracked provider/runtime overhead: not observed in cached usage";
|
|
2006
|
+
return { text: [
|
|
2007
|
+
"š§ Context breakdown (detailed)",
|
|
2008
|
+
...sharedContextLines,
|
|
2009
|
+
...perSkill.lines.length ? ["Top skills (prompt entry size):", ...perSkill.lines] : [],
|
|
2010
|
+
...perSkill.omitted ? [`⦠(+${perSkill.omitted} more skills)`] : [],
|
|
2011
|
+
"",
|
|
2012
|
+
toolListLine,
|
|
2013
|
+
toolSchemaLine,
|
|
2014
|
+
toolsNamesLine,
|
|
2015
|
+
"Top tools (schema size):",
|
|
2016
|
+
...perToolSchema.lines,
|
|
2017
|
+
...perToolSchema.omitted ? [`⦠(+${perToolSchema.omitted} more tools)`] : [],
|
|
2018
|
+
"",
|
|
2019
|
+
"Top tools (summary text size):",
|
|
2020
|
+
...perToolSummary.lines,
|
|
2021
|
+
...perToolSummary.omitted ? [`⦠(+${perToolSummary.omitted} more tools)`] : [],
|
|
2022
|
+
...toolPropsLines.length ? [
|
|
2023
|
+
"",
|
|
2024
|
+
"Tools (param count):",
|
|
2025
|
+
...toolPropsLines
|
|
2026
|
+
] : [],
|
|
2027
|
+
"",
|
|
2028
|
+
trackedPromptLine,
|
|
2029
|
+
actualContextLine,
|
|
2030
|
+
...overheadLine ? [overheadLine] : [],
|
|
2031
|
+
"",
|
|
2032
|
+
totalsLine,
|
|
2033
|
+
"",
|
|
2034
|
+
"Inline shortcut: a command token inside normal text (e.g. āhey /statusā) that runs immediately (allowlisted senders only) and is stripped before the model sees the remaining message."
|
|
2035
|
+
].filter(Boolean).join("\n") };
|
|
2036
|
+
}
|
|
2037
|
+
return { text: [
|
|
2038
|
+
"š§ Context breakdown",
|
|
2039
|
+
...sharedContextLines,
|
|
2040
|
+
toolListLine,
|
|
2041
|
+
toolSchemaLine,
|
|
2042
|
+
toolsNamesLine,
|
|
2043
|
+
"",
|
|
2044
|
+
totalsLine,
|
|
2045
|
+
"",
|
|
2046
|
+
"Inline shortcut: a command token inside normal text (e.g. āhey /statusā) that runs immediately (allowlisted senders only) and is stripped before the model sees the remaining message."
|
|
2047
|
+
].join("\n") };
|
|
2048
|
+
}
|
|
2049
|
+
//#endregion
|
|
2050
|
+
//#region src/auto-reply/reply/commands-context-command.ts
|
|
2051
|
+
const handleContextCommand = async (params, allowTextCommands) => {
|
|
2052
|
+
if (!allowTextCommands) return null;
|
|
2053
|
+
const normalized = params.command.commandBodyNormalized;
|
|
2054
|
+
if (normalized !== "/context" && !normalized.startsWith("/context ")) return null;
|
|
2055
|
+
if (!params.command.isAuthorizedSender) {
|
|
2056
|
+
logVerbose(`Ignoring /context from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
2057
|
+
return { shouldContinue: false };
|
|
2058
|
+
}
|
|
2059
|
+
return {
|
|
2060
|
+
shouldContinue: false,
|
|
2061
|
+
reply: await buildContextReply(params)
|
|
2062
|
+
};
|
|
2063
|
+
};
|
|
2064
|
+
//#endregion
|
|
2065
|
+
//#region src/auto-reply/reply/commands-export-common.ts
|
|
2066
|
+
function escapeRegExp(value) {
|
|
2067
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2068
|
+
}
|
|
2069
|
+
function parseExportCommandOutputPath(commandBodyNormalized, aliases) {
|
|
2070
|
+
const normalized = commandBodyNormalized.trim();
|
|
2071
|
+
if (aliases.some((alias) => normalized === `/${alias}`)) return {};
|
|
2072
|
+
const aliasPattern = aliases.map(escapeRegExp).join("|");
|
|
2073
|
+
return { outputPath: normalized.replace(new RegExp(`^/(${aliasPattern})\\s*`), "").trim().split(/\s+/).find((part) => !part.startsWith("-")) };
|
|
2074
|
+
}
|
|
2075
|
+
function resolveExportCommandSessionTarget(params) {
|
|
2076
|
+
const targetAgentId = resolveAgentIdFromSessionKey(params.sessionKey) || params.agentId;
|
|
2077
|
+
const storePath = params.storePath ?? resolveDefaultSessionStorePath(targetAgentId);
|
|
2078
|
+
const entry = loadSessionStore(storePath, { skipCache: true })[params.sessionKey];
|
|
2079
|
+
if (!entry?.sessionId) return { text: `ā Session not found: ${params.sessionKey}` };
|
|
2080
|
+
try {
|
|
2081
|
+
return {
|
|
2082
|
+
entry,
|
|
2083
|
+
sessionFile: resolveSessionFilePath(entry.sessionId, entry, resolveSessionFilePathOptions({
|
|
2084
|
+
agentId: targetAgentId,
|
|
2085
|
+
storePath
|
|
2086
|
+
}))
|
|
2087
|
+
};
|
|
2088
|
+
} catch (err) {
|
|
2089
|
+
return { text: `ā Failed to resolve session file: ${formatErrorMessage(err)}` };
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
function isReplyPayload(value) {
|
|
2093
|
+
return "text" in value;
|
|
2094
|
+
}
|
|
2095
|
+
//#endregion
|
|
2096
|
+
//#region src/auto-reply/reply/commands-export-session.ts
|
|
2097
|
+
const EXPORT_HTML_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "export-html");
|
|
2098
|
+
function loadTemplate(fileName) {
|
|
2099
|
+
return fs.readFileSync(path.join(EXPORT_HTML_DIR, fileName), "utf-8");
|
|
2100
|
+
}
|
|
2101
|
+
function generateHtml(sessionData) {
|
|
2102
|
+
const template = loadTemplate("template.html");
|
|
2103
|
+
const templateCss = loadTemplate("template.css");
|
|
2104
|
+
const templateJs = loadTemplate("template.js");
|
|
2105
|
+
const markedJs = loadTemplate(path.join("vendor", "marked.min.js"));
|
|
2106
|
+
const hljsJs = loadTemplate(path.join("vendor", "highlight.min.js"));
|
|
2107
|
+
const themeVars = `
|
|
2108
|
+
--cyan: #00d7ff;
|
|
2109
|
+
--blue: #5f87ff;
|
|
2110
|
+
--green: #b5bd68;
|
|
2111
|
+
--red: #cc6666;
|
|
2112
|
+
--yellow: #ffff00;
|
|
2113
|
+
--gray: #808080;
|
|
2114
|
+
--dimGray: #666666;
|
|
2115
|
+
--darkGray: #505050;
|
|
2116
|
+
--accent: #8abeb7;
|
|
2117
|
+
--selectedBg: #3a3a4a;
|
|
2118
|
+
--userMsgBg: #343541;
|
|
2119
|
+
--toolPendingBg: #282832;
|
|
2120
|
+
--toolSuccessBg: #283228;
|
|
2121
|
+
--toolErrorBg: #3c2828;
|
|
2122
|
+
--customMsgBg: #2d2838;
|
|
2123
|
+
--text: #e0e0e0;
|
|
2124
|
+
--dim: #666666;
|
|
2125
|
+
--muted: #808080;
|
|
2126
|
+
--border: #5f87ff;
|
|
2127
|
+
--borderAccent: #00d7ff;
|
|
2128
|
+
--borderMuted: #505050;
|
|
2129
|
+
--success: #b5bd68;
|
|
2130
|
+
--error: #cc6666;
|
|
2131
|
+
--warning: #ffff00;
|
|
2132
|
+
--thinkingText: #808080;
|
|
2133
|
+
--userMessageBg: #343541;
|
|
2134
|
+
--userMessageText: #e0e0e0;
|
|
2135
|
+
--customMessageBg: #2d2838;
|
|
2136
|
+
--customMessageText: #e0e0e0;
|
|
2137
|
+
--customMessageLabel: #9575cd;
|
|
2138
|
+
--toolTitle: #e0e0e0;
|
|
2139
|
+
--toolOutput: #808080;
|
|
2140
|
+
--mdHeading: #f0c674;
|
|
2141
|
+
--mdLink: #81a2be;
|
|
2142
|
+
--mdLinkUrl: #666666;
|
|
2143
|
+
--mdCode: #8abeb7;
|
|
2144
|
+
--mdCodeBlock: #b5bd68;
|
|
2145
|
+
`;
|
|
2146
|
+
const bodyBg = "#1e1e28";
|
|
2147
|
+
const containerBg = "#282832";
|
|
2148
|
+
const infoBg = "#343541";
|
|
2149
|
+
const sessionDataBase64 = Buffer.from(JSON.stringify(sessionData)).toString("base64");
|
|
2150
|
+
const css = templateCss.replace("/* {{THEME_VARS}} */", themeVars.trim()).replace("/* {{BODY_BG_DECL}} */", `--body-bg: ${bodyBg};`).replace("/* {{CONTAINER_BG_DECL}} */", `--container-bg: ${containerBg};`).replace("/* {{INFO_BG_DECL}} */", `--info-bg: ${infoBg};`);
|
|
2151
|
+
return template.replace("{{CSS}}", css).replace("{{JS}}", templateJs).replace("{{SESSION_DATA}}", sessionDataBase64).replace("{{MARKED_JS}}", markedJs).replace("{{HIGHLIGHT_JS}}", hljsJs);
|
|
2152
|
+
}
|
|
2153
|
+
async function buildExportSessionReply(params) {
|
|
2154
|
+
const args = parseExportCommandOutputPath(params.command.commandBodyNormalized, ["export-session", "export"]);
|
|
2155
|
+
const sessionTarget = resolveExportCommandSessionTarget(params);
|
|
2156
|
+
if (isReplyPayload(sessionTarget)) return sessionTarget;
|
|
2157
|
+
const { entry, sessionFile } = sessionTarget;
|
|
2158
|
+
if (!fs.existsSync(sessionFile)) return { text: `ā Session file not found: ${sessionFile}` };
|
|
2159
|
+
const sessionManager = SessionManager.open(sessionFile);
|
|
2160
|
+
const entries = sessionManager.getEntries();
|
|
2161
|
+
const header = sessionManager.getHeader();
|
|
2162
|
+
const leafId = sessionManager.getLeafId();
|
|
2163
|
+
const { systemPrompt, tools } = await resolveCommandsSystemPromptBundle({
|
|
2164
|
+
...params,
|
|
2165
|
+
sessionEntry: entry
|
|
2166
|
+
});
|
|
2167
|
+
const html = generateHtml({
|
|
2168
|
+
header,
|
|
2169
|
+
entries,
|
|
2170
|
+
leafId,
|
|
2171
|
+
systemPrompt,
|
|
2172
|
+
tools: tools.map((t) => ({
|
|
2173
|
+
name: t.name,
|
|
2174
|
+
description: t.description,
|
|
2175
|
+
parameters: t.parameters
|
|
2176
|
+
}))
|
|
2177
|
+
});
|
|
2178
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
2179
|
+
const defaultFileName = `genesis-session-${entry.sessionId.slice(0, 8)}-${timestamp}.html`;
|
|
2180
|
+
const outputPath = args.outputPath ? path.resolve(args.outputPath.startsWith("~") ? args.outputPath.replace("~", process.env.HOME ?? "") : args.outputPath) : path.join(params.workspaceDir, defaultFileName);
|
|
2181
|
+
const outputDir = path.dirname(outputPath);
|
|
2182
|
+
if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
|
|
2183
|
+
fs.writeFileSync(outputPath, html, "utf-8");
|
|
2184
|
+
const relativePath = path.relative(params.workspaceDir, outputPath);
|
|
2185
|
+
return { text: [
|
|
2186
|
+
"ā
Session exported!",
|
|
2187
|
+
"",
|
|
2188
|
+
`š File: ${relativePath.startsWith("..") ? outputPath : relativePath}`,
|
|
2189
|
+
`š Entries: ${entries.length}`,
|
|
2190
|
+
`š§ System prompt: ${systemPrompt.length.toLocaleString()} chars`,
|
|
2191
|
+
`š§ Tools: ${tools.length}`
|
|
2192
|
+
].join("\n") };
|
|
2193
|
+
}
|
|
2194
|
+
//#endregion
|
|
2195
|
+
//#region src/trajectory/export.ts
|
|
2196
|
+
const MAX_TRAJECTORY_RUNTIME_EVENTS = 2e5;
|
|
2197
|
+
const MAX_TRAJECTORY_TOTAL_EVENTS = 25e4;
|
|
2198
|
+
const MAX_TRAJECTORY_SESSION_FILE_BYTES = 50 * 1024 * 1024;
|
|
2199
|
+
function parseSessionEntries(content) {
|
|
2200
|
+
return content.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean).flatMap((line) => {
|
|
2201
|
+
try {
|
|
2202
|
+
return [JSON.parse(line)];
|
|
2203
|
+
} catch {
|
|
2204
|
+
return [];
|
|
2205
|
+
}
|
|
2206
|
+
});
|
|
2207
|
+
}
|
|
2208
|
+
function migrateLegacySessionEntries(entries) {
|
|
2209
|
+
const version = entries.find((entry) => entry.type === "session")?.version ?? 1;
|
|
2210
|
+
if (version < 2) {
|
|
2211
|
+
let previousId = null;
|
|
2212
|
+
let index = 0;
|
|
2213
|
+
for (const entry of entries) {
|
|
2214
|
+
if (entry.type === "session") {
|
|
2215
|
+
entry.version = 2;
|
|
2216
|
+
continue;
|
|
2217
|
+
}
|
|
2218
|
+
const mutable = entry;
|
|
2219
|
+
if (typeof mutable.id !== "string") mutable.id = `legacy-${index++}`;
|
|
2220
|
+
mutable.parentId = previousId;
|
|
2221
|
+
const entryId = mutable.id;
|
|
2222
|
+
previousId = typeof entryId === "string" ? entryId : null;
|
|
2223
|
+
if (entry.type === "compaction" && typeof mutable.firstKeptEntryIndex === "number") {
|
|
2224
|
+
const target = entries[mutable.firstKeptEntryIndex];
|
|
2225
|
+
if (target && target.type !== "session") mutable.firstKeptEntryId = target.id;
|
|
2226
|
+
delete mutable.firstKeptEntryIndex;
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
if (version < 3) for (const entry of entries) {
|
|
2231
|
+
if (entry.type === "session") {
|
|
2232
|
+
entry.version = 3;
|
|
2233
|
+
continue;
|
|
2234
|
+
}
|
|
2235
|
+
if (entry.type === "message") {
|
|
2236
|
+
const message = entry.message;
|
|
2237
|
+
if (message?.role === "hookMessage") message.role = "custom";
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
function readSessionBranch(filePath) {
|
|
2242
|
+
const fileEntries = parseSessionEntries(fs.readFileSync(filePath, "utf8"));
|
|
2243
|
+
migrateLegacySessionEntries(fileEntries);
|
|
2244
|
+
const header = fileEntries.find((entry) => entry.type === "session") ?? null;
|
|
2245
|
+
const entries = fileEntries.filter((entry) => entry.type !== "session" && typeof entry.id === "string" && (typeof entry.timestamp === "string" || typeof entry.timestamp === "number"));
|
|
2246
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
2247
|
+
const leafId = entries.at(-1)?.id ?? null;
|
|
2248
|
+
const branchEntries = [];
|
|
2249
|
+
let current = leafId ? byId.get(leafId) : void 0;
|
|
2250
|
+
while (current) {
|
|
2251
|
+
branchEntries.unshift(current);
|
|
2252
|
+
current = current.parentId ? byId.get(current.parentId) : void 0;
|
|
2253
|
+
}
|
|
2254
|
+
return {
|
|
2255
|
+
header,
|
|
2256
|
+
leafId,
|
|
2257
|
+
branchEntries
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
function parseJsonlFile(filePath, params) {
|
|
2261
|
+
if (!fs.existsSync(filePath)) return [];
|
|
2262
|
+
const stat = fs.statSync(filePath);
|
|
2263
|
+
if (stat.size > params.maxBytes) throw new Error(`Trajectory runtime file is too large to export (${stat.size} bytes; limit ${params.maxBytes})`);
|
|
2264
|
+
const rows = fs.readFileSync(filePath, "utf8").split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
|
|
2265
|
+
const parsed = [];
|
|
2266
|
+
for (const row of rows) {
|
|
2267
|
+
if (parsed.length >= params.maxEvents) throw new Error(`Trajectory runtime file has too many events to export (limit ${params.maxEvents})`);
|
|
2268
|
+
try {
|
|
2269
|
+
const value = JSON.parse(row);
|
|
2270
|
+
if (!params.validate || params.validate(value)) parsed.push(value);
|
|
2271
|
+
} catch {}
|
|
2272
|
+
}
|
|
2273
|
+
return parsed;
|
|
2274
|
+
}
|
|
2275
|
+
function isFiniteNumber(value) {
|
|
2276
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
2277
|
+
}
|
|
2278
|
+
function isRecord(value) {
|
|
2279
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
2280
|
+
}
|
|
2281
|
+
function isRuntimeTrajectoryEventForSession(value, sessionId) {
|
|
2282
|
+
if (!isRecord(value)) return false;
|
|
2283
|
+
return value.traceSchema === "genesis-trajectory" && value.schemaVersion === 1 && value.source === "runtime" && typeof value.type === "string" && typeof value.ts === "string" && !Number.isNaN(Date.parse(value.ts)) && isFiniteNumber(value.seq) && value.sessionId === sessionId && (!("data" in value) || value.data === void 0 || isRecord(value.data));
|
|
2284
|
+
}
|
|
2285
|
+
function isRegularNonSymlinkFile(filePath) {
|
|
2286
|
+
try {
|
|
2287
|
+
const linkStat = fs.lstatSync(filePath);
|
|
2288
|
+
if (linkStat.isSymbolicLink() || !linkStat.isFile()) return false;
|
|
2289
|
+
const stat = fs.statSync(filePath);
|
|
2290
|
+
return stat.isFile() && stat.dev === linkStat.dev && stat.ino === linkStat.ino;
|
|
2291
|
+
} catch {
|
|
2292
|
+
return false;
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
function readRuntimePointerFile(sessionFile, sessionId) {
|
|
2296
|
+
const pointerPath = resolveTrajectoryPointerFilePath(sessionFile);
|
|
2297
|
+
if (!isRegularNonSymlinkFile(pointerPath)) return;
|
|
2298
|
+
try {
|
|
2299
|
+
const parsed = JSON.parse(fs.readFileSync(pointerPath, "utf8"));
|
|
2300
|
+
if (!isRecord(parsed)) return;
|
|
2301
|
+
if (parsed.sessionId !== sessionId || typeof parsed.runtimeFile !== "string") return;
|
|
2302
|
+
const runtimeFile = path.resolve(parsed.runtimeFile);
|
|
2303
|
+
const safeRuntimeFileName = `${safeTrajectorySessionFileName(sessionId)}.jsonl`;
|
|
2304
|
+
if (runtimeFile !== path.resolve(resolveTrajectoryFilePath({
|
|
2305
|
+
env: {},
|
|
2306
|
+
sessionFile,
|
|
2307
|
+
sessionId
|
|
2308
|
+
})) && path.basename(runtimeFile) !== safeRuntimeFileName) return;
|
|
2309
|
+
return runtimeFile;
|
|
2310
|
+
} catch {
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
function resolveTrajectoryRuntimeFile(params) {
|
|
2315
|
+
if (params.runtimeFile) return params.runtimeFile;
|
|
2316
|
+
return [
|
|
2317
|
+
readRuntimePointerFile(params.sessionFile, params.sessionId),
|
|
2318
|
+
resolveTrajectoryFilePath({
|
|
2319
|
+
env: {},
|
|
2320
|
+
sessionFile: params.sessionFile,
|
|
2321
|
+
sessionId: params.sessionId
|
|
2322
|
+
}),
|
|
2323
|
+
resolveTrajectoryFilePath({
|
|
2324
|
+
sessionFile: params.sessionFile,
|
|
2325
|
+
sessionId: params.sessionId
|
|
2326
|
+
})
|
|
2327
|
+
].filter((candidate) => Boolean(candidate)).find((candidate) => isRegularNonSymlinkFile(candidate));
|
|
2328
|
+
}
|
|
2329
|
+
function normalizeTimestamp(value) {
|
|
2330
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
2331
|
+
const parsed = new Date(value);
|
|
2332
|
+
if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
|
|
2333
|
+
}
|
|
2334
|
+
if (typeof value === "string") {
|
|
2335
|
+
const parsed = new Date(value);
|
|
2336
|
+
if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
|
|
2337
|
+
}
|
|
2338
|
+
return (/* @__PURE__ */ new Date(0)).toISOString();
|
|
2339
|
+
}
|
|
2340
|
+
function resolveMessageEventType(message) {
|
|
2341
|
+
if (message.role === "user") return "user.message";
|
|
2342
|
+
if (message.role === "assistant") return "assistant.message";
|
|
2343
|
+
if (message.role === "toolResult") return "tool.result";
|
|
2344
|
+
return `message.${message.role}`;
|
|
2345
|
+
}
|
|
2346
|
+
function extractAssistantToolCalls(message) {
|
|
2347
|
+
if (message.role !== "assistant" || !Array.isArray(message.content)) return [];
|
|
2348
|
+
return message.content.flatMap((block, index) => {
|
|
2349
|
+
if (!block || typeof block !== "object") return [];
|
|
2350
|
+
const typedBlock = block;
|
|
2351
|
+
const blockType = typeof typedBlock.type === "string" ? typedBlock.type.trim().toLowerCase() : "";
|
|
2352
|
+
if (blockType !== "toolcall" && blockType !== "tooluse" && blockType !== "functioncall") return [];
|
|
2353
|
+
return [{
|
|
2354
|
+
id: typeof typedBlock.id === "string" ? typedBlock.id : void 0,
|
|
2355
|
+
name: typeof typedBlock.name === "string" ? typedBlock.name : void 0,
|
|
2356
|
+
arguments: typedBlock.arguments ?? typedBlock.input ?? typedBlock.parameters,
|
|
2357
|
+
index
|
|
2358
|
+
}];
|
|
2359
|
+
});
|
|
2360
|
+
}
|
|
2361
|
+
function buildTranscriptEvents(params) {
|
|
2362
|
+
const events = [];
|
|
2363
|
+
let seq = 0;
|
|
2364
|
+
for (const entry of params.entries) {
|
|
2365
|
+
const push = (type, data) => {
|
|
2366
|
+
events.push({
|
|
2367
|
+
traceSchema: "genesis-trajectory",
|
|
2368
|
+
schemaVersion: 1,
|
|
2369
|
+
traceId: params.traceId,
|
|
2370
|
+
source: "transcript",
|
|
2371
|
+
type,
|
|
2372
|
+
ts: normalizeTimestamp(entry.timestamp),
|
|
2373
|
+
seq: 0,
|
|
2374
|
+
sourceSeq: seq += 1,
|
|
2375
|
+
sessionId: params.sessionId,
|
|
2376
|
+
sessionKey: params.sessionKey,
|
|
2377
|
+
workspaceDir: params.workspaceDir,
|
|
2378
|
+
entryId: entry.id,
|
|
2379
|
+
parentEntryId: entry.parentId,
|
|
2380
|
+
data
|
|
2381
|
+
});
|
|
2382
|
+
};
|
|
2383
|
+
switch (entry.type) {
|
|
2384
|
+
case "message":
|
|
2385
|
+
push(resolveMessageEventType(entry.message), { message: sanitizeDiagnosticPayload(entry.message) });
|
|
2386
|
+
for (const toolCall of extractAssistantToolCalls(entry.message)) push("tool.call", {
|
|
2387
|
+
toolCallId: toolCall.id,
|
|
2388
|
+
name: toolCall.name,
|
|
2389
|
+
arguments: sanitizeDiagnosticPayload(toolCall.arguments),
|
|
2390
|
+
assistantEntryId: entry.id,
|
|
2391
|
+
blockIndex: toolCall.index
|
|
2392
|
+
});
|
|
2393
|
+
break;
|
|
2394
|
+
case "compaction":
|
|
2395
|
+
push("session.compaction", {
|
|
2396
|
+
summary: entry.summary,
|
|
2397
|
+
firstKeptEntryId: entry.firstKeptEntryId,
|
|
2398
|
+
tokensBefore: entry.tokensBefore,
|
|
2399
|
+
details: sanitizeDiagnosticPayload(entry.details),
|
|
2400
|
+
fromHook: entry.fromHook ?? false
|
|
2401
|
+
});
|
|
2402
|
+
break;
|
|
2403
|
+
case "branch_summary":
|
|
2404
|
+
push("session.branch_summary", {
|
|
2405
|
+
fromId: entry.fromId,
|
|
2406
|
+
summary: entry.summary,
|
|
2407
|
+
details: sanitizeDiagnosticPayload(entry.details),
|
|
2408
|
+
fromHook: entry.fromHook ?? false
|
|
2409
|
+
});
|
|
2410
|
+
break;
|
|
2411
|
+
case "custom":
|
|
2412
|
+
push("session.custom", {
|
|
2413
|
+
customType: entry.customType,
|
|
2414
|
+
data: sanitizeDiagnosticPayload(entry.data)
|
|
2415
|
+
});
|
|
2416
|
+
break;
|
|
2417
|
+
case "custom_message":
|
|
2418
|
+
push("session.custom_message", {
|
|
2419
|
+
customType: entry.customType,
|
|
2420
|
+
content: sanitizeDiagnosticPayload(entry.content),
|
|
2421
|
+
details: sanitizeDiagnosticPayload(entry.details),
|
|
2422
|
+
display: entry.display
|
|
2423
|
+
});
|
|
2424
|
+
break;
|
|
2425
|
+
case "thinking_level_change":
|
|
2426
|
+
push("session.thinking_level_change", { thinkingLevel: entry.thinkingLevel });
|
|
2427
|
+
break;
|
|
2428
|
+
case "model_change":
|
|
2429
|
+
push("session.model_change", {
|
|
2430
|
+
provider: entry.provider,
|
|
2431
|
+
modelId: entry.modelId
|
|
2432
|
+
});
|
|
2433
|
+
break;
|
|
2434
|
+
case "label":
|
|
2435
|
+
push("session.label", {
|
|
2436
|
+
targetId: entry.targetId,
|
|
2437
|
+
label: entry.label
|
|
2438
|
+
});
|
|
2439
|
+
break;
|
|
2440
|
+
case "session_info":
|
|
2441
|
+
push("session.info", { name: entry.name });
|
|
2442
|
+
break;
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
return events;
|
|
2446
|
+
}
|
|
2447
|
+
function sortTrajectoryEvents(events) {
|
|
2448
|
+
const sourceOrder = {
|
|
2449
|
+
runtime: 0,
|
|
2450
|
+
transcript: 1,
|
|
2451
|
+
export: 2
|
|
2452
|
+
};
|
|
2453
|
+
const sorted = events.toSorted((left, right) => {
|
|
2454
|
+
const byTs = left.ts.localeCompare(right.ts);
|
|
2455
|
+
if (byTs !== 0) return byTs;
|
|
2456
|
+
const bySource = sourceOrder[left.source] - sourceOrder[right.source];
|
|
2457
|
+
if (bySource !== 0) return bySource;
|
|
2458
|
+
return (left.sourceSeq ?? left.seq) - (right.sourceSeq ?? right.seq);
|
|
2459
|
+
});
|
|
2460
|
+
for (const [index, event] of sorted.entries()) event.seq = index + 1;
|
|
2461
|
+
return sorted;
|
|
2462
|
+
}
|
|
2463
|
+
function trajectoryJsonlFile(pathName, events) {
|
|
2464
|
+
return jsonlSupportBundleFile(pathName, events.map((event) => safeJsonStringify(event)).filter((line) => Boolean(line)));
|
|
2465
|
+
}
|
|
2466
|
+
function buildTrajectoryExportRedaction(params) {
|
|
2467
|
+
const env = process.env;
|
|
2468
|
+
return {
|
|
2469
|
+
env,
|
|
2470
|
+
stateDir: resolveStateDir(env),
|
|
2471
|
+
workspaceDir: path.resolve(params.workspaceDir)
|
|
2472
|
+
};
|
|
2473
|
+
}
|
|
2474
|
+
function redactWorkspacePathString(value, redaction) {
|
|
2475
|
+
const workspaceDir = redaction.workspaceDir;
|
|
2476
|
+
if (!workspaceDir) return value;
|
|
2477
|
+
const normalizedWorkspaceDir = workspaceDir.replaceAll("\\", "/");
|
|
2478
|
+
let next = value;
|
|
2479
|
+
for (const candidate of new Set([workspaceDir, normalizedWorkspaceDir])) {
|
|
2480
|
+
if (!candidate) continue;
|
|
2481
|
+
const escaped = candidate.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
2482
|
+
next = next.replace(new RegExp(`${escaped}(?=$|[\\\\/])`, "gu"), "$WORKSPACE_DIR");
|
|
2483
|
+
}
|
|
2484
|
+
return next;
|
|
2485
|
+
}
|
|
2486
|
+
function maybeRedactPathString(value, redaction) {
|
|
2487
|
+
const workspaceRedacted = redactWorkspacePathString(value, redaction);
|
|
2488
|
+
if (workspaceRedacted !== value || path.isAbsolute(workspaceRedacted) || workspaceRedacted.includes(redaction.stateDir) || (redaction.env.HOME ? workspaceRedacted.includes(redaction.env.HOME) : false) || (redaction.env.USERPROFILE ? workspaceRedacted.includes(redaction.env.USERPROFILE) : false)) return redactSupportString(workspaceRedacted, redaction);
|
|
2489
|
+
return workspaceRedacted;
|
|
2490
|
+
}
|
|
2491
|
+
function redactLocalPathValues(value, redaction) {
|
|
2492
|
+
if (typeof value === "string") return maybeRedactPathString(value, redaction);
|
|
2493
|
+
if (Array.isArray(value)) return value.map((entry) => redactLocalPathValues(entry, redaction));
|
|
2494
|
+
if (!value || typeof value !== "object") return value;
|
|
2495
|
+
const record = value;
|
|
2496
|
+
const next = {};
|
|
2497
|
+
for (const [key, entry] of Object.entries(record)) next[key] = redactLocalPathValues(entry, redaction);
|
|
2498
|
+
return next;
|
|
2499
|
+
}
|
|
2500
|
+
function redactEventForExport(event, redaction) {
|
|
2501
|
+
return {
|
|
2502
|
+
...event,
|
|
2503
|
+
workspaceDir: event.workspaceDir ? maybeRedactPathString(event.workspaceDir, redaction) : void 0,
|
|
2504
|
+
data: event.data ? redactLocalPathValues(event.data, redaction) : void 0
|
|
2505
|
+
};
|
|
2506
|
+
}
|
|
2507
|
+
function resolveRuntimeContext(runtimeEvents) {
|
|
2508
|
+
const runtimeData = runtimeEvents.slice().toReversed().find((event) => event.type === "context.compiled")?.data;
|
|
2509
|
+
const toolsValue = Array.isArray(runtimeData?.tools) ? runtimeData.tools : void 0;
|
|
2510
|
+
return {
|
|
2511
|
+
systemPrompt: typeof runtimeData?.systemPrompt === "string" ? runtimeData.systemPrompt : void 0,
|
|
2512
|
+
tools: toolsValue
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
function resolveLatestRuntimeEventData(runtimeEvents, type) {
|
|
2516
|
+
return runtimeEvents.slice().toReversed().find((candidate) => candidate.type === type)?.data;
|
|
2517
|
+
}
|
|
2518
|
+
function normalizePathForMatch(value) {
|
|
2519
|
+
return value.replaceAll("\\", "/").trim().toLowerCase();
|
|
2520
|
+
}
|
|
2521
|
+
function collectPotentialPathStrings(value) {
|
|
2522
|
+
const found = /* @__PURE__ */ new Set();
|
|
2523
|
+
const visit = (input) => {
|
|
2524
|
+
if (!input || typeof input !== "object") return;
|
|
2525
|
+
if (Array.isArray(input)) {
|
|
2526
|
+
for (const entry of input) visit(entry);
|
|
2527
|
+
return;
|
|
2528
|
+
}
|
|
2529
|
+
for (const [key, entry] of Object.entries(input)) if (typeof entry === "string" && (key.toLowerCase().includes("path") || entry.endsWith("SKILL.md") || entry.endsWith("skill.md"))) found.add(entry);
|
|
2530
|
+
else visit(entry);
|
|
2531
|
+
};
|
|
2532
|
+
visit(value);
|
|
2533
|
+
return [...found];
|
|
2534
|
+
}
|
|
2535
|
+
function markInvokedSkills(params) {
|
|
2536
|
+
if (!params.skills || typeof params.skills !== "object") return params.skills;
|
|
2537
|
+
const skillsRecord = params.skills;
|
|
2538
|
+
if (!Array.isArray(skillsRecord.entries) || skillsRecord.entries.length === 0) return params.skills;
|
|
2539
|
+
const invokedPaths = new Set(params.events.flatMap((event) => {
|
|
2540
|
+
if (event.type !== "tool.call") return [];
|
|
2541
|
+
return collectPotentialPathStrings(event.data?.arguments);
|
|
2542
|
+
}));
|
|
2543
|
+
const normalizedInvokedPaths = new Set([...invokedPaths].map((value) => normalizePathForMatch(value)));
|
|
2544
|
+
const entries = skillsRecord.entries.map((entry) => {
|
|
2545
|
+
const rawPath = typeof entry.filePath === "string" ? entry.filePath : void 0;
|
|
2546
|
+
const normalizedPath = rawPath ? normalizePathForMatch(rawPath) : void 0;
|
|
2547
|
+
const skillDirName = rawPath?.replaceAll("\\", "/").split("/").slice(-2, -1)[0]?.toLowerCase() ?? void 0;
|
|
2548
|
+
const invoked = normalizedPath ? [...normalizedInvokedPaths].some((candidate) => candidate === normalizedPath || candidate.endsWith(normalizedPath) || (skillDirName ? candidate.endsWith(`/${skillDirName}/skill.md`) : false)) : false;
|
|
2549
|
+
return invoked ? {
|
|
2550
|
+
...entry,
|
|
2551
|
+
invoked,
|
|
2552
|
+
invocationDetectedBy: "tool-call-file-path"
|
|
2553
|
+
} : {
|
|
2554
|
+
...entry,
|
|
2555
|
+
invoked: false
|
|
2556
|
+
};
|
|
2557
|
+
});
|
|
2558
|
+
return {
|
|
2559
|
+
...skillsRecord,
|
|
2560
|
+
entries
|
|
2561
|
+
};
|
|
2562
|
+
}
|
|
2563
|
+
function buildMetadataCapture(params) {
|
|
2564
|
+
const runtimeMetadata = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.metadata");
|
|
2565
|
+
if (!runtimeMetadata) return;
|
|
2566
|
+
const modelFallback = (() => {
|
|
2567
|
+
const latest = params.runtimeEvents.slice().toReversed().find((event) => event.provider || event.modelId || event.modelApi);
|
|
2568
|
+
if (!latest?.provider && !latest?.modelId && !latest?.modelApi) return;
|
|
2569
|
+
return {
|
|
2570
|
+
provider: latest.provider,
|
|
2571
|
+
name: latest.modelId,
|
|
2572
|
+
api: latest.modelApi
|
|
2573
|
+
};
|
|
2574
|
+
})();
|
|
2575
|
+
return {
|
|
2576
|
+
traceSchema: "genesis-trajectory",
|
|
2577
|
+
schemaVersion: 1,
|
|
2578
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2579
|
+
traceId: params.manifest.traceId,
|
|
2580
|
+
sessionId: params.manifest.sessionId,
|
|
2581
|
+
sessionKey: params.manifest.sessionKey,
|
|
2582
|
+
harness: runtimeMetadata.harness,
|
|
2583
|
+
model: runtimeMetadata.model ?? modelFallback,
|
|
2584
|
+
config: runtimeMetadata.config,
|
|
2585
|
+
plugins: runtimeMetadata.plugins,
|
|
2586
|
+
skills: markInvokedSkills({
|
|
2587
|
+
skills: runtimeMetadata.skills,
|
|
2588
|
+
events: params.events
|
|
2589
|
+
}),
|
|
2590
|
+
prompting: runtimeMetadata.prompting,
|
|
2591
|
+
redaction: runtimeMetadata.redaction,
|
|
2592
|
+
metadata: runtimeMetadata.metadata
|
|
2593
|
+
};
|
|
2594
|
+
}
|
|
2595
|
+
function buildArtifactsCapture(params) {
|
|
2596
|
+
const runtimeArtifacts = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.artifacts");
|
|
2597
|
+
const runtimeCompletion = resolveLatestRuntimeEventData(params.runtimeEvents, "model.completed");
|
|
2598
|
+
const runtimeEnd = resolveLatestRuntimeEventData(params.runtimeEvents, "session.ended");
|
|
2599
|
+
if (!runtimeArtifacts && !runtimeCompletion && !runtimeEnd) return;
|
|
2600
|
+
return {
|
|
2601
|
+
traceSchema: "genesis-trajectory",
|
|
2602
|
+
schemaVersion: 1,
|
|
2603
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2604
|
+
traceId: params.manifest.traceId,
|
|
2605
|
+
sessionId: params.manifest.sessionId,
|
|
2606
|
+
sessionKey: params.manifest.sessionKey,
|
|
2607
|
+
finalStatus: runtimeArtifacts?.finalStatus ?? runtimeEnd?.status,
|
|
2608
|
+
aborted: runtimeArtifacts?.aborted ?? runtimeEnd?.aborted,
|
|
2609
|
+
externalAbort: runtimeArtifacts?.externalAbort ?? runtimeEnd?.externalAbort,
|
|
2610
|
+
timedOut: runtimeArtifacts?.timedOut ?? runtimeEnd?.timedOut,
|
|
2611
|
+
idleTimedOut: runtimeArtifacts?.idleTimedOut ?? runtimeEnd?.idleTimedOut,
|
|
2612
|
+
timedOutDuringCompaction: runtimeArtifacts?.timedOutDuringCompaction ?? runtimeEnd?.timedOutDuringCompaction,
|
|
2613
|
+
promptError: runtimeArtifacts?.promptError ?? runtimeEnd?.promptError ?? runtimeCompletion?.promptError,
|
|
2614
|
+
promptErrorSource: runtimeArtifacts?.promptErrorSource ?? runtimeCompletion?.promptErrorSource,
|
|
2615
|
+
usage: runtimeArtifacts?.usage ?? runtimeCompletion?.usage,
|
|
2616
|
+
promptCache: runtimeArtifacts?.promptCache ?? runtimeCompletion?.promptCache,
|
|
2617
|
+
compactionCount: runtimeArtifacts?.compactionCount ?? runtimeCompletion?.compactionCount,
|
|
2618
|
+
assistantTexts: runtimeArtifacts?.assistantTexts ?? runtimeCompletion?.assistantTexts,
|
|
2619
|
+
finalPromptText: runtimeArtifacts?.finalPromptText ?? runtimeCompletion?.finalPromptText,
|
|
2620
|
+
itemLifecycle: runtimeArtifacts?.itemLifecycle,
|
|
2621
|
+
toolMetas: runtimeArtifacts?.toolMetas,
|
|
2622
|
+
didSendViaMessagingTool: runtimeArtifacts?.didSendViaMessagingTool,
|
|
2623
|
+
successfulCronAdds: runtimeArtifacts?.successfulCronAdds,
|
|
2624
|
+
messagingToolSentTexts: runtimeArtifacts?.messagingToolSentTexts,
|
|
2625
|
+
messagingToolSentMediaUrls: runtimeArtifacts?.messagingToolSentMediaUrls,
|
|
2626
|
+
messagingToolSentTargets: runtimeArtifacts?.messagingToolSentTargets,
|
|
2627
|
+
lastToolError: runtimeArtifacts?.lastToolError
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
function buildPromptsCapture(params) {
|
|
2631
|
+
const runtimeMetadata = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.metadata");
|
|
2632
|
+
const latestCompiled = resolveLatestRuntimeEventData(params.runtimeEvents, "context.compiled");
|
|
2633
|
+
const submittedPrompts = params.runtimeEvents.filter((event) => event.type === "prompt.submitted").map((event) => event.data?.prompt).filter((prompt) => typeof prompt === "string");
|
|
2634
|
+
const systemPrompt = (typeof latestCompiled?.systemPrompt === "string" ? latestCompiled.systemPrompt : void 0) ?? params.runtimeContext.systemPrompt;
|
|
2635
|
+
const skillsPrompt = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.skillsPrompt === "string" ? runtimeMetadata.prompting.skillsPrompt : void 0;
|
|
2636
|
+
const userPromptPrefixText = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.userPromptPrefixText === "string" ? runtimeMetadata.prompting.userPromptPrefixText : void 0;
|
|
2637
|
+
const promptReport = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.systemPromptReport === "object" ? runtimeMetadata.prompting.systemPromptReport : void 0;
|
|
2638
|
+
if (!systemPrompt && submittedPrompts.length === 0 && !skillsPrompt && !userPromptPrefixText) return;
|
|
2639
|
+
return {
|
|
2640
|
+
traceSchema: "genesis-trajectory",
|
|
2641
|
+
schemaVersion: 1,
|
|
2642
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2643
|
+
traceId: params.manifest.traceId,
|
|
2644
|
+
sessionId: params.manifest.sessionId,
|
|
2645
|
+
sessionKey: params.manifest.sessionKey,
|
|
2646
|
+
system: systemPrompt,
|
|
2647
|
+
submittedPrompts,
|
|
2648
|
+
latestSubmittedPrompt: submittedPrompts.at(-1),
|
|
2649
|
+
skillsPrompt,
|
|
2650
|
+
userPromptPrefixText,
|
|
2651
|
+
systemPromptReport: promptReport
|
|
2652
|
+
};
|
|
2653
|
+
}
|
|
2654
|
+
function resolveDefaultTrajectoryExportDir(params) {
|
|
2655
|
+
const timestamp = (params.now ?? /* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
2656
|
+
const sessionFileName = safeTrajectorySessionFileName(params.sessionId);
|
|
2657
|
+
return path.join(params.workspaceDir, ".genesis", "trajectory-exports", `genesis-trajectory-${sessionFileName.slice(0, 8)}-${timestamp}`);
|
|
2658
|
+
}
|
|
2659
|
+
function exportTrajectoryBundle(params) {
|
|
2660
|
+
const redaction = buildTrajectoryExportRedaction({ workspaceDir: params.workspaceDir });
|
|
2661
|
+
const sessionStat = fs.statSync(params.sessionFile);
|
|
2662
|
+
if (sessionStat.size > MAX_TRAJECTORY_SESSION_FILE_BYTES) throw new Error(`Trajectory session file is too large to export (${sessionStat.size} bytes; limit ${MAX_TRAJECTORY_SESSION_FILE_BYTES})`);
|
|
2663
|
+
const { header, leafId, branchEntries } = readSessionBranch(params.sessionFile);
|
|
2664
|
+
const runtimeFile = resolveTrajectoryRuntimeFile({
|
|
2665
|
+
runtimeFile: params.runtimeFile,
|
|
2666
|
+
sessionFile: params.sessionFile,
|
|
2667
|
+
sessionId: params.sessionId
|
|
2668
|
+
});
|
|
2669
|
+
const runtimeEvents = runtimeFile ? parseJsonlFile(runtimeFile, {
|
|
2670
|
+
maxBytes: TRAJECTORY_RUNTIME_FILE_MAX_BYTES,
|
|
2671
|
+
maxEvents: MAX_TRAJECTORY_RUNTIME_EVENTS,
|
|
2672
|
+
validate: (value) => isRuntimeTrajectoryEventForSession(value, params.sessionId)
|
|
2673
|
+
}) : [];
|
|
2674
|
+
const transcriptEvents = buildTranscriptEvents({
|
|
2675
|
+
entries: branchEntries,
|
|
2676
|
+
sessionId: params.sessionId,
|
|
2677
|
+
sessionKey: params.sessionKey,
|
|
2678
|
+
workspaceDir: params.workspaceDir,
|
|
2679
|
+
traceId: params.sessionId
|
|
2680
|
+
});
|
|
2681
|
+
const maxTotalEvents = params.maxTotalEvents ?? MAX_TRAJECTORY_TOTAL_EVENTS;
|
|
2682
|
+
const totalEventCount = runtimeEvents.length + transcriptEvents.length;
|
|
2683
|
+
if (totalEventCount > maxTotalEvents) throw new Error(`Trajectory export has too many events (${totalEventCount}; limit ${maxTotalEvents})`);
|
|
2684
|
+
const rawEvents = sortTrajectoryEvents([...runtimeEvents, ...transcriptEvents]);
|
|
2685
|
+
const events = rawEvents.map((event) => redactEventForExport(event, redaction));
|
|
2686
|
+
const manifest = {
|
|
2687
|
+
traceSchema: "genesis-trajectory",
|
|
2688
|
+
schemaVersion: 1,
|
|
2689
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2690
|
+
traceId: params.sessionId,
|
|
2691
|
+
sessionId: params.sessionId,
|
|
2692
|
+
sessionKey: params.sessionKey,
|
|
2693
|
+
workspaceDir: maybeRedactPathString(params.workspaceDir, redaction),
|
|
2694
|
+
leafId,
|
|
2695
|
+
eventCount: events.length,
|
|
2696
|
+
runtimeEventCount: runtimeEvents.length,
|
|
2697
|
+
transcriptEventCount: transcriptEvents.length,
|
|
2698
|
+
sourceFiles: {
|
|
2699
|
+
session: maybeRedactPathString(params.sessionFile, redaction),
|
|
2700
|
+
runtime: runtimeFile && isRegularNonSymlinkFile(runtimeFile) ? maybeRedactPathString(runtimeFile, redaction) : void 0
|
|
2701
|
+
}
|
|
2702
|
+
};
|
|
2703
|
+
const bundleRuntimeContext = resolveRuntimeContext(runtimeEvents);
|
|
2704
|
+
const files = [];
|
|
2705
|
+
const supplementalFiles = [];
|
|
2706
|
+
const metadataCapture = buildMetadataCapture({
|
|
2707
|
+
manifest,
|
|
2708
|
+
runtimeEvents,
|
|
2709
|
+
events: rawEvents
|
|
2710
|
+
});
|
|
2711
|
+
const artifactsCapture = buildArtifactsCapture({
|
|
2712
|
+
manifest,
|
|
2713
|
+
runtimeEvents
|
|
2714
|
+
});
|
|
2715
|
+
const promptsCapture = buildPromptsCapture({
|
|
2716
|
+
manifest,
|
|
2717
|
+
runtimeEvents,
|
|
2718
|
+
runtimeContext: bundleRuntimeContext
|
|
2719
|
+
});
|
|
2720
|
+
if (metadataCapture) {
|
|
2721
|
+
files.push(jsonSupportBundleFile("metadata.json", redactLocalPathValues(metadataCapture, redaction)));
|
|
2722
|
+
supplementalFiles.push("metadata.json");
|
|
2723
|
+
}
|
|
2724
|
+
if (artifactsCapture) {
|
|
2725
|
+
files.push(jsonSupportBundleFile("artifacts.json", redactLocalPathValues(artifactsCapture, redaction)));
|
|
2726
|
+
supplementalFiles.push("artifacts.json");
|
|
2727
|
+
}
|
|
2728
|
+
if (promptsCapture) {
|
|
2729
|
+
files.push(jsonSupportBundleFile("prompts.json", redactLocalPathValues(promptsCapture, redaction)));
|
|
2730
|
+
supplementalFiles.push("prompts.json");
|
|
2731
|
+
}
|
|
2732
|
+
if (supplementalFiles.length > 0) manifest.supplementalFiles = supplementalFiles;
|
|
2733
|
+
files.push(trajectoryJsonlFile("events.jsonl", events));
|
|
2734
|
+
files.push(jsonSupportBundleFile("session-branch.json", redactLocalPathValues(sanitizeDiagnosticPayload({
|
|
2735
|
+
header,
|
|
2736
|
+
leafId,
|
|
2737
|
+
entries: branchEntries
|
|
2738
|
+
}), redaction)));
|
|
2739
|
+
if (bundleRuntimeContext.systemPrompt) files.push(textSupportBundleFile("system-prompt.txt", redactLocalPathValues(bundleRuntimeContext.systemPrompt, redaction)));
|
|
2740
|
+
if (bundleRuntimeContext.tools) files.push(jsonSupportBundleFile("tools.json", redactLocalPathValues(bundleRuntimeContext.tools, redaction)));
|
|
2741
|
+
manifest.contents = [...supportBundleContents(files)];
|
|
2742
|
+
writeSupportBundleDirectory({
|
|
2743
|
+
outputDir: params.outputDir,
|
|
2744
|
+
files: [jsonSupportBundleFile("manifest.json", manifest), ...files]
|
|
2745
|
+
});
|
|
2746
|
+
return {
|
|
2747
|
+
manifest,
|
|
2748
|
+
outputDir: params.outputDir,
|
|
2749
|
+
events,
|
|
2750
|
+
header,
|
|
2751
|
+
runtimeFile: runtimeFile && isRegularNonSymlinkFile(runtimeFile) ? runtimeFile : void 0,
|
|
2752
|
+
supplementalFiles
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
2755
|
+
//#endregion
|
|
2756
|
+
//#region src/auto-reply/reply/commands-export-trajectory.ts
|
|
2757
|
+
function isPathInsideOrEqual(baseDir, candidate) {
|
|
2758
|
+
const relative = path.relative(baseDir, candidate);
|
|
2759
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
2760
|
+
}
|
|
2761
|
+
function validateExistingExportDirectory(params) {
|
|
2762
|
+
const linkStat = fs.lstatSync(params.dir);
|
|
2763
|
+
if (linkStat.isSymbolicLink() || !linkStat.isDirectory()) throw new Error(`${params.label} must be a real directory inside the workspace`);
|
|
2764
|
+
const realDir = fs.realpathSync(params.dir);
|
|
2765
|
+
if (!isPathInsideOrEqual(params.realWorkspace, realDir)) throw new Error("Trajectory exports directory must stay inside the workspace");
|
|
2766
|
+
return realDir;
|
|
2767
|
+
}
|
|
2768
|
+
function mkdirIfMissingThenValidate(params) {
|
|
2769
|
+
if (!fs.existsSync(params.dir)) try {
|
|
2770
|
+
fs.mkdirSync(params.dir, { mode: 448 });
|
|
2771
|
+
} catch (error) {
|
|
2772
|
+
if (error.code !== "EEXIST") throw error;
|
|
2773
|
+
}
|
|
2774
|
+
return validateExistingExportDirectory(params);
|
|
2775
|
+
}
|
|
2776
|
+
function resolveTrajectoryExportBaseDir(workspaceDir) {
|
|
2777
|
+
const workspacePath = path.resolve(workspaceDir);
|
|
2778
|
+
const realWorkspace = fs.realpathSync(workspacePath);
|
|
2779
|
+
const stateDir = path.join(workspacePath, ".genesis");
|
|
2780
|
+
mkdirIfMissingThenValidate({
|
|
2781
|
+
dir: stateDir,
|
|
2782
|
+
label: "Genesis state directory",
|
|
2783
|
+
realWorkspace
|
|
2784
|
+
});
|
|
2785
|
+
const baseDir = path.join(stateDir, "trajectory-exports");
|
|
2786
|
+
const realBase = mkdirIfMissingThenValidate({
|
|
2787
|
+
dir: baseDir,
|
|
2788
|
+
label: "Trajectory exports directory",
|
|
2789
|
+
realWorkspace
|
|
2790
|
+
});
|
|
2791
|
+
return {
|
|
2792
|
+
baseDir: path.resolve(baseDir),
|
|
2793
|
+
realBase
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
function resolveTrajectoryCommandOutputDir(params) {
|
|
2797
|
+
const { baseDir, realBase } = resolveTrajectoryExportBaseDir(params.workspaceDir);
|
|
2798
|
+
const raw = params.outputPath?.trim();
|
|
2799
|
+
if (!raw) {
|
|
2800
|
+
const defaultDir = resolveDefaultTrajectoryExportDir({
|
|
2801
|
+
workspaceDir: params.workspaceDir,
|
|
2802
|
+
sessionId: params.sessionId
|
|
2803
|
+
});
|
|
2804
|
+
return path.join(baseDir, path.basename(defaultDir));
|
|
2805
|
+
}
|
|
2806
|
+
if (path.isAbsolute(raw) || raw.startsWith("~")) throw new Error("Output path must be relative to the workspace trajectory exports directory");
|
|
2807
|
+
const resolvedBase = path.resolve(baseDir);
|
|
2808
|
+
const outputDir = path.resolve(resolvedBase, raw);
|
|
2809
|
+
const relative = path.relative(resolvedBase, outputDir);
|
|
2810
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("Output path must stay inside the workspace trajectory exports directory");
|
|
2811
|
+
let existingParent = outputDir;
|
|
2812
|
+
while (!fs.existsSync(existingParent)) {
|
|
2813
|
+
const next = path.dirname(existingParent);
|
|
2814
|
+
if (next === existingParent) break;
|
|
2815
|
+
existingParent = next;
|
|
2816
|
+
}
|
|
2817
|
+
if (!isPathInsideOrEqual(realBase, fs.realpathSync(existingParent))) throw new Error("Output path must stay inside the real trajectory exports directory");
|
|
2818
|
+
return outputDir;
|
|
2819
|
+
}
|
|
2820
|
+
async function buildExportTrajectoryReply(params) {
|
|
2821
|
+
const args = parseExportCommandOutputPath(params.command.commandBodyNormalized, ["export-trajectory", "trajectory"]);
|
|
2822
|
+
const sessionTarget = resolveExportCommandSessionTarget(params);
|
|
2823
|
+
if (isReplyPayload(sessionTarget)) return sessionTarget;
|
|
2824
|
+
const { entry, sessionFile } = sessionTarget;
|
|
2825
|
+
if (!fs.existsSync(sessionFile)) return { text: "ā Session file not found." };
|
|
2826
|
+
let outputDir;
|
|
2827
|
+
try {
|
|
2828
|
+
outputDir = resolveTrajectoryCommandOutputDir({
|
|
2829
|
+
outputPath: args.outputPath,
|
|
2830
|
+
workspaceDir: params.workspaceDir,
|
|
2831
|
+
sessionId: entry.sessionId
|
|
2832
|
+
});
|
|
2833
|
+
} catch (err) {
|
|
2834
|
+
return { text: `ā Failed to resolve output path: ${formatErrorMessage(err)}` };
|
|
2835
|
+
}
|
|
2836
|
+
let bundle;
|
|
2837
|
+
try {
|
|
2838
|
+
bundle = exportTrajectoryBundle({
|
|
2839
|
+
outputDir,
|
|
2840
|
+
sessionFile,
|
|
2841
|
+
sessionId: entry.sessionId,
|
|
2842
|
+
sessionKey: params.sessionKey,
|
|
2843
|
+
workspaceDir: params.workspaceDir
|
|
2844
|
+
});
|
|
2845
|
+
} catch (err) {
|
|
2846
|
+
return { text: `ā Failed to export trajectory: ${formatErrorMessage(err)}` };
|
|
2847
|
+
}
|
|
2848
|
+
const relativePath = path.relative(params.workspaceDir, bundle.outputDir);
|
|
2849
|
+
const displayPath = relativePath && !relativePath.startsWith("..") && !path.isAbsolute(relativePath) ? relativePath : path.basename(bundle.outputDir);
|
|
2850
|
+
const files = [
|
|
2851
|
+
"manifest.json",
|
|
2852
|
+
"events.jsonl",
|
|
2853
|
+
"session-branch.json"
|
|
2854
|
+
];
|
|
2855
|
+
if (bundle.events.some((event) => event.type === "context.compiled")) files.push("system-prompt.txt", "tools.json");
|
|
2856
|
+
files.push(...bundle.supplementalFiles);
|
|
2857
|
+
return { text: [
|
|
2858
|
+
"ā
Trajectory exported!",
|
|
2859
|
+
"",
|
|
2860
|
+
`š¦ Bundle: ${displayPath}`,
|
|
2861
|
+
`š§µ Session: ${entry.sessionId}`,
|
|
2862
|
+
`š Events: ${bundle.manifest.eventCount}`,
|
|
2863
|
+
`š§Ŗ Runtime events: ${bundle.manifest.runtimeEventCount}`,
|
|
2864
|
+
`š Transcript events: ${bundle.manifest.transcriptEventCount}`,
|
|
2865
|
+
`š Files: ${files.join(", ")}`
|
|
2866
|
+
].join("\n") };
|
|
2867
|
+
}
|
|
2868
|
+
//#endregion
|
|
2869
|
+
//#region src/auto-reply/reply/commands-whoami.ts
|
|
2870
|
+
const handleWhoamiCommand = async (params, allowTextCommands) => {
|
|
2871
|
+
if (!allowTextCommands) return null;
|
|
2872
|
+
if (params.command.commandBodyNormalized !== "/whoami") return null;
|
|
2873
|
+
if (!params.command.isAuthorizedSender) {
|
|
2874
|
+
logVerbose(`Ignoring /whoami from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
2875
|
+
return { shouldContinue: false };
|
|
2876
|
+
}
|
|
2877
|
+
const senderId = params.ctx.SenderId ?? "";
|
|
2878
|
+
const senderUsername = params.ctx.SenderUsername ?? "";
|
|
2879
|
+
const lines = ["š§ Identity", `Channel: ${params.command.channel}`];
|
|
2880
|
+
if (senderId) lines.push(`User id: ${senderId}`);
|
|
2881
|
+
if (senderUsername) {
|
|
2882
|
+
const handle = senderUsername.startsWith("@") ? senderUsername : `@${senderUsername}`;
|
|
2883
|
+
lines.push(`Username: ${handle}`);
|
|
2884
|
+
}
|
|
2885
|
+
if (params.ctx.ChatType === "group" && params.ctx.From) lines.push(`Chat: ${params.ctx.From}`);
|
|
2886
|
+
if (params.ctx.MessageThreadId != null) lines.push(`Thread: ${params.ctx.MessageThreadId}`);
|
|
2887
|
+
const allowFromSender = params.command.senderId ?? "";
|
|
2888
|
+
if (allowFromSender) lines.push(`AllowFrom: ${allowFromSender}`);
|
|
2889
|
+
return {
|
|
2890
|
+
shouldContinue: false,
|
|
2891
|
+
reply: { text: lines.join("\n") }
|
|
2892
|
+
};
|
|
2893
|
+
};
|
|
2894
|
+
//#endregion
|
|
2895
|
+
//#region src/auto-reply/reply/commands-info.ts
|
|
2896
|
+
const handleHelpCommand = async (params, allowTextCommands) => {
|
|
2897
|
+
if (!allowTextCommands) return null;
|
|
2898
|
+
if (params.command.commandBodyNormalized !== "/help") return null;
|
|
2899
|
+
if (!params.command.isAuthorizedSender) {
|
|
2900
|
+
logVerbose(`Ignoring /help from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
2901
|
+
return { shouldContinue: false };
|
|
2902
|
+
}
|
|
2903
|
+
return {
|
|
2904
|
+
shouldContinue: false,
|
|
2905
|
+
reply: { text: buildHelpMessage(params.cfg) }
|
|
2906
|
+
};
|
|
2907
|
+
};
|
|
2908
|
+
const handleCommandsListCommand = async (params, allowTextCommands) => {
|
|
2909
|
+
if (!allowTextCommands) return null;
|
|
2910
|
+
if (params.command.commandBodyNormalized !== "/commands") return null;
|
|
2911
|
+
if (!params.command.isAuthorizedSender) {
|
|
2912
|
+
logVerbose(`Ignoring /commands from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
2913
|
+
return { shouldContinue: false };
|
|
2914
|
+
}
|
|
2915
|
+
const agentId = params.sessionKey ? resolveSessionAgentId({
|
|
2916
|
+
sessionKey: params.sessionKey,
|
|
2917
|
+
config: params.cfg
|
|
2918
|
+
}) : params.agentId;
|
|
2919
|
+
const skillCommands = params.skillCommands ?? listSkillCommandsForAgents({
|
|
2920
|
+
cfg: params.cfg,
|
|
2921
|
+
agentIds: agentId ? [agentId] : void 0
|
|
2922
|
+
});
|
|
2923
|
+
const surface = params.ctx.Surface;
|
|
2924
|
+
const commandPlugin = surface ? getChannelPlugin(surface) : null;
|
|
2925
|
+
const paginated = buildCommandsMessagePaginated(params.cfg, skillCommands, {
|
|
2926
|
+
page: 1,
|
|
2927
|
+
surface
|
|
2928
|
+
});
|
|
2929
|
+
const channelData = commandPlugin?.commands?.buildCommandsListChannelData?.({
|
|
2930
|
+
currentPage: paginated.currentPage,
|
|
2931
|
+
totalPages: paginated.totalPages,
|
|
2932
|
+
agentId
|
|
2933
|
+
});
|
|
2934
|
+
if (channelData) return {
|
|
2935
|
+
shouldContinue: false,
|
|
2936
|
+
reply: {
|
|
2937
|
+
text: paginated.text,
|
|
2938
|
+
channelData
|
|
2939
|
+
}
|
|
2940
|
+
};
|
|
2941
|
+
return {
|
|
2942
|
+
shouldContinue: false,
|
|
2943
|
+
reply: { text: buildCommandsMessage(params.cfg, skillCommands, { surface }) }
|
|
2944
|
+
};
|
|
2945
|
+
};
|
|
2946
|
+
const handleToolsCommand = async (params, allowTextCommands) => {
|
|
2947
|
+
if (!allowTextCommands) return null;
|
|
2948
|
+
const normalized = params.command.commandBodyNormalized;
|
|
2949
|
+
let verbose = false;
|
|
2950
|
+
if (normalized === "/tools" || normalized === "/tools compact") verbose = false;
|
|
2951
|
+
else if (normalized === "/tools verbose") verbose = true;
|
|
2952
|
+
else if (normalized.startsWith("/tools ")) return {
|
|
2953
|
+
shouldContinue: false,
|
|
2954
|
+
reply: { text: "Usage: /tools [compact|verbose]" }
|
|
2955
|
+
};
|
|
2956
|
+
else return null;
|
|
2957
|
+
if (!params.command.isAuthorizedSender) {
|
|
2958
|
+
logVerbose(`Ignoring /tools from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
2959
|
+
return { shouldContinue: false };
|
|
2960
|
+
}
|
|
2961
|
+
try {
|
|
2962
|
+
const effectiveAccountId = resolveChannelAccountId({
|
|
2963
|
+
cfg: params.cfg,
|
|
2964
|
+
ctx: params.ctx,
|
|
2965
|
+
command: params.command
|
|
2966
|
+
});
|
|
2967
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
2968
|
+
const sessionBound = Boolean(params.sessionKey);
|
|
2969
|
+
const agentId = sessionBound ? resolveSessionAgentId({
|
|
2970
|
+
sessionKey: params.sessionKey,
|
|
2971
|
+
config: params.cfg
|
|
2972
|
+
}) : params.agentId;
|
|
2973
|
+
const threadingContext = buildThreadingToolContext({
|
|
2974
|
+
sessionCtx: params.ctx,
|
|
2975
|
+
config: params.cfg,
|
|
2976
|
+
hasRepliedRef: void 0
|
|
2977
|
+
});
|
|
2978
|
+
return {
|
|
2979
|
+
shouldContinue: false,
|
|
2980
|
+
reply: { text: buildToolsMessage(resolveEffectiveToolInventory({
|
|
2981
|
+
cfg: params.cfg,
|
|
2982
|
+
agentId,
|
|
2983
|
+
sessionKey: params.sessionKey,
|
|
2984
|
+
workspaceDir: params.workspaceDir,
|
|
2985
|
+
agentDir: sessionBound ? void 0 : params.agentDir,
|
|
2986
|
+
modelProvider: params.provider,
|
|
2987
|
+
modelId: params.model,
|
|
2988
|
+
messageProvider: params.command.channel,
|
|
2989
|
+
senderIsOwner: params.command.senderIsOwner,
|
|
2990
|
+
senderId: params.command.senderId,
|
|
2991
|
+
senderName: params.ctx.SenderName,
|
|
2992
|
+
senderUsername: params.ctx.SenderUsername,
|
|
2993
|
+
senderE164: params.ctx.SenderE164,
|
|
2994
|
+
accountId: effectiveAccountId,
|
|
2995
|
+
currentChannelId: threadingContext.currentChannelId,
|
|
2996
|
+
currentThreadTs: typeof params.ctx.MessageThreadId === "string" || typeof params.ctx.MessageThreadId === "number" ? String(params.ctx.MessageThreadId) : void 0,
|
|
2997
|
+
currentMessageId: threadingContext.currentMessageId,
|
|
2998
|
+
groupId: targetSessionEntry?.groupId ?? extractExplicitGroupId(params.ctx.From),
|
|
2999
|
+
groupChannel: targetSessionEntry?.groupChannel ?? params.ctx.GroupChannel ?? params.ctx.GroupSubject,
|
|
3000
|
+
groupSpace: targetSessionEntry?.space ?? params.ctx.GroupSpace,
|
|
3001
|
+
replyToMode: resolveReplyToMode(params.cfg, params.ctx.OriginatingChannel ?? params.ctx.Provider, effectiveAccountId, params.ctx.ChatType)
|
|
3002
|
+
}), { verbose }) }
|
|
3003
|
+
};
|
|
3004
|
+
} catch (err) {
|
|
3005
|
+
return {
|
|
3006
|
+
shouldContinue: false,
|
|
3007
|
+
reply: { text: String(err).includes("missing scope:") ? "You do not have permission to view available tools." : "Couldn't load available tools right now. Try again in a moment." }
|
|
3008
|
+
};
|
|
3009
|
+
}
|
|
3010
|
+
};
|
|
3011
|
+
const handleStatusCommand = async (params, allowTextCommands) => {
|
|
3012
|
+
if (!allowTextCommands) return null;
|
|
3013
|
+
if (!(params.directives.hasStatusDirective || params.command.commandBodyNormalized === "/status")) return null;
|
|
3014
|
+
if (!params.command.isAuthorizedSender) {
|
|
3015
|
+
logVerbose(`Ignoring /status from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
3016
|
+
return { shouldContinue: false };
|
|
3017
|
+
}
|
|
3018
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
3019
|
+
return {
|
|
3020
|
+
shouldContinue: false,
|
|
3021
|
+
reply: await buildStatusReply({
|
|
3022
|
+
cfg: params.cfg,
|
|
3023
|
+
command: params.command,
|
|
3024
|
+
sessionEntry: targetSessionEntry,
|
|
3025
|
+
sessionKey: params.sessionKey,
|
|
3026
|
+
parentSessionKey: targetSessionEntry?.parentSessionKey ?? params.ctx.ParentSessionKey,
|
|
3027
|
+
sessionScope: params.sessionScope,
|
|
3028
|
+
storePath: params.storePath,
|
|
3029
|
+
provider: params.provider,
|
|
3030
|
+
model: params.model,
|
|
3031
|
+
contextTokens: params.contextTokens,
|
|
3032
|
+
resolvedThinkLevel: params.resolvedThinkLevel,
|
|
3033
|
+
resolvedFastMode: params.resolvedFastMode,
|
|
3034
|
+
resolvedVerboseLevel: params.resolvedVerboseLevel,
|
|
3035
|
+
resolvedReasoningLevel: params.resolvedReasoningLevel,
|
|
3036
|
+
resolvedElevatedLevel: params.resolvedElevatedLevel,
|
|
3037
|
+
resolveDefaultThinkingLevel: params.resolveDefaultThinkingLevel,
|
|
3038
|
+
isGroup: params.isGroup,
|
|
3039
|
+
defaultGroupActivation: params.defaultGroupActivation,
|
|
3040
|
+
mediaDecisions: params.ctx.MediaUnderstandingDecisions
|
|
3041
|
+
})
|
|
3042
|
+
};
|
|
3043
|
+
};
|
|
3044
|
+
const handleExportSessionCommand = async (params, allowTextCommands) => {
|
|
3045
|
+
if (!allowTextCommands) return null;
|
|
3046
|
+
const normalized = params.command.commandBodyNormalized;
|
|
3047
|
+
if (normalized !== "/export-session" && !normalized.startsWith("/export-session ") && normalized !== "/export" && !normalized.startsWith("/export ")) return null;
|
|
3048
|
+
if (!params.command.isAuthorizedSender) {
|
|
3049
|
+
logVerbose(`Ignoring /export-session from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
3050
|
+
return { shouldContinue: false };
|
|
3051
|
+
}
|
|
3052
|
+
return {
|
|
3053
|
+
shouldContinue: false,
|
|
3054
|
+
reply: await buildExportSessionReply(params)
|
|
3055
|
+
};
|
|
3056
|
+
};
|
|
3057
|
+
const handleExportTrajectoryCommand = async (params, allowTextCommands) => {
|
|
3058
|
+
if (!allowTextCommands) return null;
|
|
3059
|
+
const normalized = params.command.commandBodyNormalized;
|
|
3060
|
+
if (normalized !== "/export-trajectory" && !normalized.startsWith("/export-trajectory ") && normalized !== "/trajectory" && !normalized.startsWith("/trajectory ")) return null;
|
|
3061
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/export-trajectory");
|
|
3062
|
+
if (unauthorized) return unauthorized;
|
|
3063
|
+
const nonOwner = rejectNonOwnerCommand(params, "/export-trajectory");
|
|
3064
|
+
if (nonOwner) return nonOwner;
|
|
3065
|
+
return {
|
|
3066
|
+
shouldContinue: false,
|
|
3067
|
+
reply: await buildExportTrajectoryReply(params)
|
|
3068
|
+
};
|
|
3069
|
+
};
|
|
3070
|
+
//#endregion
|
|
3071
|
+
//#region src/auto-reply/reply/mcp-commands.ts
|
|
3072
|
+
function parseMcpCommand(raw) {
|
|
3073
|
+
return parseStandardSetUnsetSlashCommand({
|
|
3074
|
+
raw,
|
|
3075
|
+
slash: "/mcp",
|
|
3076
|
+
invalidMessage: "Invalid /mcp syntax.",
|
|
3077
|
+
usageMessage: "Usage: /mcp show|set|unset",
|
|
3078
|
+
onKnownAction: (action, args) => {
|
|
3079
|
+
if (action === "show" || action === "get") return {
|
|
3080
|
+
action: "show",
|
|
3081
|
+
name: args || void 0
|
|
3082
|
+
};
|
|
3083
|
+
},
|
|
3084
|
+
onSet: (name, value) => ({
|
|
3085
|
+
action: "set",
|
|
3086
|
+
name,
|
|
3087
|
+
value
|
|
3088
|
+
}),
|
|
3089
|
+
onUnset: (name) => ({
|
|
3090
|
+
action: "unset",
|
|
3091
|
+
name
|
|
3092
|
+
})
|
|
3093
|
+
});
|
|
3094
|
+
}
|
|
3095
|
+
//#endregion
|
|
3096
|
+
//#region src/auto-reply/reply/commands-mcp.ts
|
|
3097
|
+
function renderJsonBlock$1(label, value) {
|
|
3098
|
+
return `${label}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
|
|
3099
|
+
}
|
|
3100
|
+
const handleMcpCommand = async (params, allowTextCommands) => {
|
|
3101
|
+
if (!allowTextCommands) return null;
|
|
3102
|
+
const mcpCommand = parseMcpCommand(params.command.commandBodyNormalized);
|
|
3103
|
+
if (!mcpCommand) return null;
|
|
3104
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/mcp");
|
|
3105
|
+
if (unauthorized) return unauthorized;
|
|
3106
|
+
const nonOwner = mcpCommand.action === "show" && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/mcp");
|
|
3107
|
+
if (nonOwner) return nonOwner;
|
|
3108
|
+
if (!isMcpCommandEnabled(params.cfg)) return {
|
|
3109
|
+
shouldContinue: false,
|
|
3110
|
+
reply: buildDisabledCommandReply({
|
|
3111
|
+
label: "/mcp",
|
|
3112
|
+
configKey: "mcp"
|
|
3113
|
+
})
|
|
3114
|
+
};
|
|
3115
|
+
if (mcpCommand.action === "error") return {
|
|
3116
|
+
shouldContinue: false,
|
|
3117
|
+
reply: { text: `ā ļø ${mcpCommand.message}` }
|
|
3118
|
+
};
|
|
3119
|
+
if (mcpCommand.action === "show") {
|
|
3120
|
+
const loaded = await listConfiguredMcpServers();
|
|
3121
|
+
if (!loaded.ok) return {
|
|
3122
|
+
shouldContinue: false,
|
|
3123
|
+
reply: { text: `ā ļø ${loaded.error}` }
|
|
3124
|
+
};
|
|
3125
|
+
if (mcpCommand.name) {
|
|
3126
|
+
const server = loaded.mcpServers[mcpCommand.name];
|
|
3127
|
+
if (!server) return {
|
|
3128
|
+
shouldContinue: false,
|
|
3129
|
+
reply: { text: `š No MCP server named "${mcpCommand.name}" in ${loaded.path}.` }
|
|
3130
|
+
};
|
|
3131
|
+
return {
|
|
3132
|
+
shouldContinue: false,
|
|
3133
|
+
reply: { text: renderJsonBlock$1(`š MCP server "${mcpCommand.name}" (${loaded.path})`, server) }
|
|
3134
|
+
};
|
|
3135
|
+
}
|
|
3136
|
+
if (Object.keys(loaded.mcpServers).length === 0) return {
|
|
3137
|
+
shouldContinue: false,
|
|
3138
|
+
reply: { text: `š No MCP servers configured in ${loaded.path}.` }
|
|
3139
|
+
};
|
|
3140
|
+
return {
|
|
3141
|
+
shouldContinue: false,
|
|
3142
|
+
reply: { text: renderJsonBlock$1(`š MCP servers (${loaded.path})`, loaded.mcpServers) }
|
|
3143
|
+
};
|
|
3144
|
+
}
|
|
3145
|
+
const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
|
|
3146
|
+
label: "/mcp write",
|
|
3147
|
+
allowedScopes: ["operator.admin"],
|
|
3148
|
+
missingText: "ā /mcp set|unset requires operator.admin for gateway clients."
|
|
3149
|
+
});
|
|
3150
|
+
if (missingAdminScope) return missingAdminScope;
|
|
3151
|
+
if (mcpCommand.action === "set") {
|
|
3152
|
+
const result = await setConfiguredMcpServer({
|
|
3153
|
+
name: mcpCommand.name,
|
|
3154
|
+
server: mcpCommand.value
|
|
3155
|
+
});
|
|
3156
|
+
if (!result.ok) return {
|
|
3157
|
+
shouldContinue: false,
|
|
3158
|
+
reply: { text: `ā ļø ${result.error}` }
|
|
3159
|
+
};
|
|
3160
|
+
return {
|
|
3161
|
+
shouldContinue: false,
|
|
3162
|
+
reply: { text: `š MCP server "${mcpCommand.name}" saved to ${result.path}.` }
|
|
3163
|
+
};
|
|
3164
|
+
}
|
|
3165
|
+
const result = await unsetConfiguredMcpServer({ name: mcpCommand.name });
|
|
3166
|
+
if (!result.ok) return {
|
|
3167
|
+
shouldContinue: false,
|
|
3168
|
+
reply: { text: `ā ļø ${result.error}` }
|
|
3169
|
+
};
|
|
3170
|
+
if (!result.removed) return {
|
|
3171
|
+
shouldContinue: false,
|
|
3172
|
+
reply: { text: `š No MCP server named "${mcpCommand.name}" in ${result.path}.` }
|
|
3173
|
+
};
|
|
3174
|
+
return {
|
|
3175
|
+
shouldContinue: false,
|
|
3176
|
+
reply: { text: `š MCP server "${mcpCommand.name}" removed from ${result.path}.` }
|
|
3177
|
+
};
|
|
3178
|
+
};
|
|
3179
|
+
//#endregion
|
|
3180
|
+
//#region src/auto-reply/reply/commands-plugin.ts
|
|
3181
|
+
/**
|
|
3182
|
+
* Plugin Command Handler
|
|
3183
|
+
*
|
|
3184
|
+
* Handles commands registered by plugins, bypassing the LLM agent.
|
|
3185
|
+
* This handler is called before built-in command handlers.
|
|
3186
|
+
*/
|
|
3187
|
+
/**
|
|
3188
|
+
* Handle plugin-registered commands.
|
|
3189
|
+
* Returns a result if a plugin command was matched and executed,
|
|
3190
|
+
* or null to continue to the next handler.
|
|
3191
|
+
*/
|
|
3192
|
+
const handlePluginCommand = async (params, allowTextCommands) => {
|
|
3193
|
+
const { command, cfg } = params;
|
|
3194
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
3195
|
+
if (!allowTextCommands) return null;
|
|
3196
|
+
const match = matchPluginCommand(command.commandBodyNormalized);
|
|
3197
|
+
if (!match) return null;
|
|
3198
|
+
return {
|
|
3199
|
+
shouldContinue: false,
|
|
3200
|
+
reply: await executePluginCommand({
|
|
3201
|
+
command: match.command,
|
|
3202
|
+
args: match.args,
|
|
3203
|
+
senderId: command.senderId,
|
|
3204
|
+
channel: command.channel,
|
|
3205
|
+
channelId: command.channelId,
|
|
3206
|
+
isAuthorizedSender: command.isAuthorizedSender,
|
|
3207
|
+
gatewayClientScopes: params.ctx.GatewayClientScopes,
|
|
3208
|
+
sessionKey: params.sessionKey,
|
|
3209
|
+
sessionId: targetSessionEntry?.sessionId,
|
|
3210
|
+
sessionFile: targetSessionEntry?.sessionFile,
|
|
3211
|
+
commandBody: command.commandBodyNormalized,
|
|
3212
|
+
config: cfg,
|
|
3213
|
+
from: command.from,
|
|
3214
|
+
to: command.to,
|
|
3215
|
+
accountId: params.ctx.AccountId ?? void 0,
|
|
3216
|
+
messageThreadId: typeof params.ctx.MessageThreadId === "string" || typeof params.ctx.MessageThreadId === "number" ? params.ctx.MessageThreadId : void 0,
|
|
3217
|
+
threadParentId: normalizeOptionalString(params.ctx.ThreadParentId)
|
|
3218
|
+
})
|
|
3219
|
+
};
|
|
3220
|
+
};
|
|
3221
|
+
//#endregion
|
|
3222
|
+
//#region src/auto-reply/reply/plugins-commands.ts
|
|
3223
|
+
function parsePluginsCommand(raw) {
|
|
3224
|
+
const match = raw.match(/^\/plugins?(?:\s+(.*))?$/i);
|
|
3225
|
+
if (!match) return null;
|
|
3226
|
+
const tail = normalizeOptionalString(match?.[1]) ?? "";
|
|
3227
|
+
if (!tail) return { action: "list" };
|
|
3228
|
+
const [rawAction, ...rest] = tail.split(/\s+/);
|
|
3229
|
+
const action = normalizeOptionalLowercaseString(rawAction);
|
|
3230
|
+
const name = rest.join(" ").trim();
|
|
3231
|
+
if (action === "list") return name ? {
|
|
3232
|
+
action: "error",
|
|
3233
|
+
message: "Usage: /plugins list|inspect|show|get|enable|disable [plugin]"
|
|
3234
|
+
} : { action: "list" };
|
|
3235
|
+
if (action === "inspect" || action === "show" || action === "get") return {
|
|
3236
|
+
action: "inspect",
|
|
3237
|
+
name: name || void 0
|
|
3238
|
+
};
|
|
3239
|
+
if (action === "install" || action === "add") {
|
|
3240
|
+
if (!name) return {
|
|
3241
|
+
action: "error",
|
|
3242
|
+
message: "Usage: /plugins install <path|archive|npm-spec|clawhub:pkg>"
|
|
3243
|
+
};
|
|
3244
|
+
return {
|
|
3245
|
+
action: "install",
|
|
3246
|
+
spec: name
|
|
3247
|
+
};
|
|
3248
|
+
}
|
|
3249
|
+
if (action === "enable" || action === "disable") {
|
|
3250
|
+
if (!name) return {
|
|
3251
|
+
action: "error",
|
|
3252
|
+
message: `Usage: /plugins ${action} <plugin-id-or-name>`
|
|
3253
|
+
};
|
|
3254
|
+
return {
|
|
3255
|
+
action,
|
|
3256
|
+
name
|
|
3257
|
+
};
|
|
3258
|
+
}
|
|
3259
|
+
return {
|
|
3260
|
+
action: "error",
|
|
3261
|
+
message: "Usage: /plugins list|inspect|show|get|install|enable|disable [plugin]"
|
|
3262
|
+
};
|
|
3263
|
+
}
|
|
3264
|
+
//#endregion
|
|
3265
|
+
//#region src/auto-reply/reply/commands-plugins.ts
|
|
3266
|
+
function renderJsonBlock(label, value) {
|
|
3267
|
+
return `${label}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
|
|
3268
|
+
}
|
|
3269
|
+
function buildPluginInspectJson(params) {
|
|
3270
|
+
const inspect = buildPluginInspectReport({
|
|
3271
|
+
id: params.id,
|
|
3272
|
+
config: params.config,
|
|
3273
|
+
report: params.report
|
|
3274
|
+
});
|
|
3275
|
+
if (!inspect) return null;
|
|
3276
|
+
return {
|
|
3277
|
+
inspect,
|
|
3278
|
+
compatibilityWarnings: inspect.compatibility.map((warning) => ({
|
|
3279
|
+
code: warning.code,
|
|
3280
|
+
severity: warning.severity,
|
|
3281
|
+
message: formatPluginCompatibilityNotice(warning)
|
|
3282
|
+
})),
|
|
3283
|
+
install: params.config.plugins?.installs?.[inspect.plugin.id] ?? null
|
|
3284
|
+
};
|
|
3285
|
+
}
|
|
3286
|
+
function buildAllPluginInspectJson(params) {
|
|
3287
|
+
return buildAllPluginInspectReports({
|
|
3288
|
+
config: params.config,
|
|
3289
|
+
report: params.report
|
|
3290
|
+
}).map((inspect) => ({
|
|
3291
|
+
inspect,
|
|
3292
|
+
compatibilityWarnings: inspect.compatibility.map((warning) => ({
|
|
3293
|
+
code: warning.code,
|
|
3294
|
+
severity: warning.severity,
|
|
3295
|
+
message: formatPluginCompatibilityNotice(warning)
|
|
3296
|
+
})),
|
|
3297
|
+
install: params.config.plugins?.installs?.[inspect.plugin.id] ?? null
|
|
3298
|
+
}));
|
|
3299
|
+
}
|
|
3300
|
+
function formatPluginLabel(plugin) {
|
|
3301
|
+
if (!plugin.name || plugin.name === plugin.id) return plugin.id;
|
|
3302
|
+
return `${plugin.name} (${plugin.id})`;
|
|
3303
|
+
}
|
|
3304
|
+
function formatPluginsList(report) {
|
|
3305
|
+
if (report.plugins.length === 0) return `š No plugins found for workspace ${report.workspaceDir ?? "(unknown workspace)"}.`;
|
|
3306
|
+
return [`š Plugins (${report.plugins.filter((plugin) => plugin.status === "loaded").length}/${report.plugins.length} loaded)`, ...report.plugins.map((plugin) => {
|
|
3307
|
+
const format = plugin.bundleFormat ? `${plugin.format ?? "genesis"}/${plugin.bundleFormat}` : plugin.format ?? "genesis";
|
|
3308
|
+
return `- ${formatPluginLabel(plugin)} [${plugin.status}] ${format}`;
|
|
3309
|
+
})].join("\n");
|
|
3310
|
+
}
|
|
3311
|
+
function findPlugin(report, rawName) {
|
|
3312
|
+
const target = normalizeOptionalLowercaseString(rawName);
|
|
3313
|
+
if (!target) return;
|
|
3314
|
+
return report.plugins.find((plugin) => normalizeOptionalLowercaseString(plugin.id) === target || normalizeOptionalLowercaseString(plugin.name) === target);
|
|
3315
|
+
}
|
|
3316
|
+
function looksLikeLocalPluginInstallSpec(raw) {
|
|
3317
|
+
return raw.startsWith(".") || raw.startsWith("~") || raw.startsWith("/") || raw.endsWith(".ts") || raw.endsWith(".js") || raw.endsWith(".mjs") || raw.endsWith(".cjs") || raw.endsWith(".tgz") || raw.endsWith(".tar.gz") || raw.endsWith(".tar") || raw.endsWith(".zip");
|
|
3318
|
+
}
|
|
3319
|
+
async function installPluginFromPluginsCommand(params) {
|
|
3320
|
+
const fileSpec = resolveFileNpmSpecToLocalPath(params.raw);
|
|
3321
|
+
if (fileSpec && !fileSpec.ok) return {
|
|
3322
|
+
ok: false,
|
|
3323
|
+
error: fileSpec.error
|
|
3324
|
+
};
|
|
3325
|
+
const resolved = resolveUserPath(fileSpec && fileSpec.ok ? fileSpec.path : params.raw);
|
|
3326
|
+
if (fs.existsSync(resolved)) {
|
|
3327
|
+
const result = await installPluginFromPath({
|
|
3328
|
+
path: resolved,
|
|
3329
|
+
logger: createPluginInstallLogger()
|
|
3330
|
+
});
|
|
3331
|
+
if (!result.ok) return {
|
|
3332
|
+
ok: false,
|
|
3333
|
+
error: result.error
|
|
3334
|
+
};
|
|
3335
|
+
clearPluginManifestRegistryCache();
|
|
3336
|
+
const source = resolveArchiveKind(resolved) ? "archive" : "path";
|
|
3337
|
+
await persistPluginInstall({
|
|
3338
|
+
config: params.config,
|
|
3339
|
+
pluginId: result.pluginId,
|
|
3340
|
+
install: {
|
|
3341
|
+
source,
|
|
3342
|
+
sourcePath: resolved,
|
|
3343
|
+
installPath: result.targetDir,
|
|
3344
|
+
version: result.version
|
|
3345
|
+
}
|
|
3346
|
+
});
|
|
3347
|
+
return {
|
|
3348
|
+
ok: true,
|
|
3349
|
+
pluginId: result.pluginId
|
|
3350
|
+
};
|
|
3351
|
+
}
|
|
3352
|
+
if (looksLikeLocalPluginInstallSpec(params.raw)) return {
|
|
3353
|
+
ok: false,
|
|
3354
|
+
error: `Path not found: ${resolved}`
|
|
3355
|
+
};
|
|
3356
|
+
if (parseClawHubPluginSpec(params.raw)) {
|
|
3357
|
+
const result = await installPluginFromClawHub({
|
|
3358
|
+
spec: params.raw,
|
|
3359
|
+
logger: createPluginInstallLogger()
|
|
3360
|
+
});
|
|
3361
|
+
if (!result.ok) return {
|
|
3362
|
+
ok: false,
|
|
3363
|
+
error: result.error
|
|
3364
|
+
};
|
|
3365
|
+
clearPluginManifestRegistryCache();
|
|
3366
|
+
await persistPluginInstall({
|
|
3367
|
+
config: params.config,
|
|
3368
|
+
pluginId: result.pluginId,
|
|
3369
|
+
install: {
|
|
3370
|
+
source: "clawhub",
|
|
3371
|
+
spec: params.raw,
|
|
3372
|
+
installPath: result.targetDir,
|
|
3373
|
+
version: result.version,
|
|
3374
|
+
integrity: result.clawhub.integrity,
|
|
3375
|
+
resolvedAt: result.clawhub.resolvedAt,
|
|
3376
|
+
clawhubUrl: result.clawhub.clawhubUrl,
|
|
3377
|
+
clawhubPackage: result.clawhub.clawhubPackage,
|
|
3378
|
+
clawhubFamily: result.clawhub.clawhubFamily,
|
|
3379
|
+
clawhubChannel: result.clawhub.clawhubChannel
|
|
3380
|
+
}
|
|
3381
|
+
});
|
|
3382
|
+
return {
|
|
3383
|
+
ok: true,
|
|
3384
|
+
pluginId: result.pluginId
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
const preferredClawHubSpec = buildPreferredClawHubSpec(params.raw);
|
|
3388
|
+
if (preferredClawHubSpec) {
|
|
3389
|
+
const clawhubResult = await installPluginFromClawHub({
|
|
3390
|
+
spec: preferredClawHubSpec,
|
|
3391
|
+
logger: createPluginInstallLogger()
|
|
3392
|
+
});
|
|
3393
|
+
if (clawhubResult.ok) {
|
|
3394
|
+
clearPluginManifestRegistryCache();
|
|
3395
|
+
await persistPluginInstall({
|
|
3396
|
+
config: params.config,
|
|
3397
|
+
pluginId: clawhubResult.pluginId,
|
|
3398
|
+
install: {
|
|
3399
|
+
source: "clawhub",
|
|
3400
|
+
spec: preferredClawHubSpec,
|
|
3401
|
+
installPath: clawhubResult.targetDir,
|
|
3402
|
+
version: clawhubResult.version,
|
|
3403
|
+
integrity: clawhubResult.clawhub.integrity,
|
|
3404
|
+
resolvedAt: clawhubResult.clawhub.resolvedAt,
|
|
3405
|
+
clawhubUrl: clawhubResult.clawhub.clawhubUrl,
|
|
3406
|
+
clawhubPackage: clawhubResult.clawhub.clawhubPackage,
|
|
3407
|
+
clawhubFamily: clawhubResult.clawhub.clawhubFamily,
|
|
3408
|
+
clawhubChannel: clawhubResult.clawhub.clawhubChannel
|
|
3409
|
+
}
|
|
3410
|
+
});
|
|
3411
|
+
return {
|
|
3412
|
+
ok: true,
|
|
3413
|
+
pluginId: clawhubResult.pluginId
|
|
3414
|
+
};
|
|
3415
|
+
}
|
|
3416
|
+
if (decidePreferredClawHubFallback(clawhubResult) !== "fallback_to_npm") return {
|
|
3417
|
+
ok: false,
|
|
3418
|
+
error: clawhubResult.error
|
|
3419
|
+
};
|
|
3420
|
+
}
|
|
3421
|
+
const result = await installPluginFromNpmSpec({
|
|
3422
|
+
spec: params.raw,
|
|
3423
|
+
logger: createPluginInstallLogger()
|
|
3424
|
+
});
|
|
3425
|
+
if (!result.ok) return {
|
|
3426
|
+
ok: false,
|
|
3427
|
+
error: result.error
|
|
3428
|
+
};
|
|
3429
|
+
clearPluginManifestRegistryCache();
|
|
3430
|
+
const installRecord = buildNpmInstallRecordFields({
|
|
3431
|
+
spec: params.raw,
|
|
3432
|
+
installPath: result.targetDir,
|
|
3433
|
+
version: result.version,
|
|
3434
|
+
resolution: result.npmResolution
|
|
3435
|
+
});
|
|
3436
|
+
await persistPluginInstall({
|
|
3437
|
+
config: params.config,
|
|
3438
|
+
pluginId: result.pluginId,
|
|
3439
|
+
install: installRecord
|
|
3440
|
+
});
|
|
3441
|
+
return {
|
|
3442
|
+
ok: true,
|
|
3443
|
+
pluginId: result.pluginId
|
|
3444
|
+
};
|
|
3445
|
+
}
|
|
3446
|
+
async function loadPluginCommandState(workspaceDir, options) {
|
|
3447
|
+
const snapshot = await readConfigFileSnapshot();
|
|
3448
|
+
if (!snapshot.valid) return {
|
|
3449
|
+
ok: false,
|
|
3450
|
+
path: snapshot.path,
|
|
3451
|
+
error: "Config file is invalid; fix it before using /plugins."
|
|
3452
|
+
};
|
|
3453
|
+
const config = structuredClone(snapshot.resolved);
|
|
3454
|
+
return {
|
|
3455
|
+
ok: true,
|
|
3456
|
+
path: snapshot.path,
|
|
3457
|
+
config,
|
|
3458
|
+
report: options?.loadModules === true ? buildPluginDiagnosticsReport({
|
|
3459
|
+
config,
|
|
3460
|
+
workspaceDir
|
|
3461
|
+
}) : buildPluginSnapshotReport({
|
|
3462
|
+
config,
|
|
3463
|
+
workspaceDir
|
|
3464
|
+
})
|
|
3465
|
+
};
|
|
3466
|
+
}
|
|
3467
|
+
async function loadPluginCommandConfig() {
|
|
3468
|
+
const snapshot = await readConfigFileSnapshot();
|
|
3469
|
+
if (!snapshot.valid) return {
|
|
3470
|
+
ok: false,
|
|
3471
|
+
path: snapshot.path,
|
|
3472
|
+
error: "Config file is invalid; fix it before using /plugins."
|
|
3473
|
+
};
|
|
3474
|
+
return {
|
|
3475
|
+
ok: true,
|
|
3476
|
+
path: snapshot.path,
|
|
3477
|
+
config: structuredClone(snapshot.resolved)
|
|
3478
|
+
};
|
|
3479
|
+
}
|
|
3480
|
+
const handlePluginsCommand = async (params, allowTextCommands) => {
|
|
3481
|
+
if (!allowTextCommands) return null;
|
|
3482
|
+
const pluginsCommand = parsePluginsCommand(params.command.commandBodyNormalized);
|
|
3483
|
+
if (!pluginsCommand) return null;
|
|
3484
|
+
const unauthorized = rejectUnauthorizedCommand(params, "/plugins");
|
|
3485
|
+
if (unauthorized) return unauthorized;
|
|
3486
|
+
const nonOwner = (pluginsCommand.action === "list" || pluginsCommand.action === "inspect") && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/plugins");
|
|
3487
|
+
if (nonOwner) return nonOwner;
|
|
3488
|
+
const disabled = requireCommandFlagEnabled(params.cfg, {
|
|
3489
|
+
label: "/plugins",
|
|
3490
|
+
configKey: "plugins"
|
|
3491
|
+
});
|
|
3492
|
+
if (disabled) return disabled;
|
|
3493
|
+
if (pluginsCommand.action === "error") return {
|
|
3494
|
+
shouldContinue: false,
|
|
3495
|
+
reply: { text: `ā ļø ${pluginsCommand.message}` }
|
|
3496
|
+
};
|
|
3497
|
+
const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
|
|
3498
|
+
label: "/plugins write",
|
|
3499
|
+
allowedScopes: ["operator.admin"],
|
|
3500
|
+
missingText: "ā /plugins install|enable|disable requires operator.admin for gateway clients."
|
|
3501
|
+
});
|
|
3502
|
+
if (missingAdminScope) return missingAdminScope;
|
|
3503
|
+
if (pluginsCommand.action === "install") {
|
|
3504
|
+
const loadedConfig = await loadPluginCommandConfig();
|
|
3505
|
+
if (!loadedConfig.ok) return {
|
|
3506
|
+
shouldContinue: false,
|
|
3507
|
+
reply: { text: `ā ļø ${loadedConfig.error}` }
|
|
3508
|
+
};
|
|
3509
|
+
const installed = await installPluginFromPluginsCommand({
|
|
3510
|
+
raw: pluginsCommand.spec,
|
|
3511
|
+
config: loadedConfig.config
|
|
3512
|
+
});
|
|
3513
|
+
if (!installed.ok) return {
|
|
3514
|
+
shouldContinue: false,
|
|
3515
|
+
reply: { text: `ā ļø ${installed.error}` }
|
|
3516
|
+
};
|
|
3517
|
+
return {
|
|
3518
|
+
shouldContinue: false,
|
|
3519
|
+
reply: { text: `š Installed plugin "${installed.pluginId}". Restart the gateway to load plugins.` }
|
|
3520
|
+
};
|
|
3521
|
+
}
|
|
3522
|
+
const loaded = await loadPluginCommandState(params.workspaceDir, { loadModules: pluginsCommand.action !== "list" });
|
|
3523
|
+
if (!loaded.ok) return {
|
|
3524
|
+
shouldContinue: false,
|
|
3525
|
+
reply: { text: `ā ļø ${loaded.error}` }
|
|
3526
|
+
};
|
|
3527
|
+
if (pluginsCommand.action === "list") return {
|
|
3528
|
+
shouldContinue: false,
|
|
3529
|
+
reply: { text: formatPluginsList(loaded.report) }
|
|
3530
|
+
};
|
|
3531
|
+
if (pluginsCommand.action === "inspect") {
|
|
3532
|
+
if (!pluginsCommand.name) return {
|
|
3533
|
+
shouldContinue: false,
|
|
3534
|
+
reply: { text: formatPluginsList(loaded.report) }
|
|
3535
|
+
};
|
|
3536
|
+
if (normalizeOptionalLowercaseString(pluginsCommand.name) === "all") return {
|
|
3537
|
+
shouldContinue: false,
|
|
3538
|
+
reply: { text: renderJsonBlock("š Plugins", buildAllPluginInspectJson(loaded)) }
|
|
3539
|
+
};
|
|
3540
|
+
const payload = buildPluginInspectJson({
|
|
3541
|
+
id: pluginsCommand.name,
|
|
3542
|
+
config: loaded.config,
|
|
3543
|
+
report: loaded.report
|
|
3544
|
+
});
|
|
3545
|
+
if (!payload) return {
|
|
3546
|
+
shouldContinue: false,
|
|
3547
|
+
reply: { text: `š No plugin named "${pluginsCommand.name}" found.` }
|
|
3548
|
+
};
|
|
3549
|
+
return {
|
|
3550
|
+
shouldContinue: false,
|
|
3551
|
+
reply: { text: renderJsonBlock(`š Plugin "${payload.inspect.plugin.id}"`, {
|
|
3552
|
+
...payload.inspect,
|
|
3553
|
+
compatibilityWarnings: payload.compatibilityWarnings,
|
|
3554
|
+
install: payload.install
|
|
3555
|
+
}) }
|
|
3556
|
+
};
|
|
3557
|
+
}
|
|
3558
|
+
const plugin = findPlugin(loaded.report, pluginsCommand.name);
|
|
3559
|
+
if (!plugin) return {
|
|
3560
|
+
shouldContinue: false,
|
|
3561
|
+
reply: { text: `š No plugin named "${pluginsCommand.name}" found.` }
|
|
3562
|
+
};
|
|
3563
|
+
const validated = validateConfigObjectWithPlugins(setPluginEnabledInConfig(structuredClone(loaded.config), plugin.id, pluginsCommand.action === "enable"));
|
|
3564
|
+
if (!validated.ok) {
|
|
3565
|
+
const issue = validated.issues[0];
|
|
3566
|
+
return {
|
|
3567
|
+
shouldContinue: false,
|
|
3568
|
+
reply: { text: `ā ļø Config invalid after /plugins ${pluginsCommand.action} (${issue.path}: ${issue.message}).` }
|
|
3569
|
+
};
|
|
3570
|
+
}
|
|
3571
|
+
await writeConfigFile(validated.config);
|
|
3572
|
+
return {
|
|
3573
|
+
shouldContinue: false,
|
|
3574
|
+
reply: { text: `š Plugin "${plugin.id}" ${pluginsCommand.action}d in ${loaded.path}. Restart the gateway to apply.` }
|
|
3575
|
+
};
|
|
3576
|
+
};
|
|
3577
|
+
//#endregion
|
|
3578
|
+
//#region src/auto-reply/send-policy.ts
|
|
3579
|
+
function normalizeSendPolicyOverride(raw) {
|
|
3580
|
+
const value = normalizeOptionalLowercaseString(raw);
|
|
3581
|
+
if (!value) return;
|
|
3582
|
+
if (value === "allow" || value === "on") return "allow";
|
|
3583
|
+
if (value === "deny" || value === "off") return "deny";
|
|
3584
|
+
}
|
|
3585
|
+
function parseSendPolicyCommand(raw) {
|
|
3586
|
+
if (!raw) return { hasCommand: false };
|
|
3587
|
+
const trimmed = raw.trim();
|
|
3588
|
+
if (!trimmed) return { hasCommand: false };
|
|
3589
|
+
const match = normalizeCommandBody(stripInboundMetadata(trimmed)).match(/^\/send(?:\s+([a-zA-Z]+))?\s*$/i);
|
|
3590
|
+
if (!match) return { hasCommand: false };
|
|
3591
|
+
const token = normalizeOptionalLowercaseString(match[1]);
|
|
3592
|
+
if (!token) return { hasCommand: true };
|
|
3593
|
+
if (token === "inherit" || token === "default" || token === "reset") return {
|
|
3594
|
+
hasCommand: true,
|
|
3595
|
+
mode: "inherit"
|
|
3596
|
+
};
|
|
3597
|
+
return {
|
|
3598
|
+
hasCommand: true,
|
|
3599
|
+
mode: normalizeSendPolicyOverride(token)
|
|
3600
|
+
};
|
|
3601
|
+
}
|
|
3602
|
+
//#endregion
|
|
3603
|
+
//#region src/auto-reply/reply/commands-session-store.ts
|
|
3604
|
+
async function persistSessionEntry(params) {
|
|
3605
|
+
if (!params.sessionEntry || !params.sessionStore || !params.sessionKey) return false;
|
|
3606
|
+
params.sessionEntry.updatedAt = Date.now();
|
|
3607
|
+
params.sessionStore[params.sessionKey] = params.sessionEntry;
|
|
3608
|
+
if (params.storePath) await updateSessionStore(params.storePath, (store) => {
|
|
3609
|
+
store[params.sessionKey] = params.sessionEntry;
|
|
3610
|
+
});
|
|
3611
|
+
return true;
|
|
3612
|
+
}
|
|
3613
|
+
async function persistAbortTargetEntry(params) {
|
|
3614
|
+
const { entry, key, sessionStore, storePath, abortCutoff } = params;
|
|
3615
|
+
if (!entry || !key || !sessionStore) return false;
|
|
3616
|
+
entry.abortedLastRun = true;
|
|
3617
|
+
applyAbortCutoffToSessionEntry(entry, abortCutoff);
|
|
3618
|
+
entry.updatedAt = Date.now();
|
|
3619
|
+
sessionStore[key] = entry;
|
|
3620
|
+
if (storePath) await updateSessionStore(storePath, (store) => {
|
|
3621
|
+
const nextEntry = store[key] ?? entry;
|
|
3622
|
+
if (!nextEntry) return;
|
|
3623
|
+
nextEntry.abortedLastRun = true;
|
|
3624
|
+
applyAbortCutoffToSessionEntry(nextEntry, abortCutoff);
|
|
3625
|
+
nextEntry.updatedAt = Date.now();
|
|
3626
|
+
store[key] = nextEntry;
|
|
3627
|
+
});
|
|
3628
|
+
return true;
|
|
3629
|
+
}
|
|
3630
|
+
//#endregion
|
|
3631
|
+
//#region src/auto-reply/reply/commands-session-abort.ts
|
|
3632
|
+
async function abortEmbeddedPiRunForSession(sessionId) {
|
|
3633
|
+
const { abortEmbeddedPiRun } = await import("./runs-DWfNTYtm.js");
|
|
3634
|
+
abortEmbeddedPiRun(sessionId);
|
|
3635
|
+
}
|
|
3636
|
+
function resolveAbortTarget(params) {
|
|
3637
|
+
const targetSessionKey = normalizeOptionalString(params.ctx.CommandTargetSessionKey) || params.sessionKey;
|
|
3638
|
+
const { entry, key } = resolveSessionEntryForKey(params.sessionStore, targetSessionKey);
|
|
3639
|
+
if (entry && key) return {
|
|
3640
|
+
entry,
|
|
3641
|
+
key,
|
|
3642
|
+
sessionId: replyRunRegistry.resolveSessionId(key) ?? entry.sessionId
|
|
3643
|
+
};
|
|
3644
|
+
if (params.sessionEntry && params.sessionKey && (!targetSessionKey || targetSessionKey === params.sessionKey)) return {
|
|
3645
|
+
entry: params.sessionEntry,
|
|
3646
|
+
key: params.sessionKey,
|
|
3647
|
+
sessionId: replyRunRegistry.resolveSessionId(params.sessionKey) ?? params.sessionEntry.sessionId
|
|
3648
|
+
};
|
|
3649
|
+
return {
|
|
3650
|
+
entry: void 0,
|
|
3651
|
+
key: targetSessionKey,
|
|
3652
|
+
sessionId: targetSessionKey ? replyRunRegistry.resolveSessionId(targetSessionKey) : void 0
|
|
3653
|
+
};
|
|
3654
|
+
}
|
|
3655
|
+
function resolveAbortCutoffForTarget(params) {
|
|
3656
|
+
if (!shouldPersistAbortCutoff({
|
|
3657
|
+
commandSessionKey: params.commandSessionKey,
|
|
3658
|
+
targetSessionKey: params.targetSessionKey
|
|
3659
|
+
})) return;
|
|
3660
|
+
return resolveAbortCutoffFromContext(params.ctx);
|
|
3661
|
+
}
|
|
3662
|
+
async function applyAbortTarget(params) {
|
|
3663
|
+
const { abortTarget } = params;
|
|
3664
|
+
if (abortTarget.key) replyRunRegistry.abort(abortTarget.key);
|
|
3665
|
+
if (abortTarget.sessionId) await abortEmbeddedPiRunForSession(abortTarget.sessionId);
|
|
3666
|
+
if (!await persistAbortTargetEntry({
|
|
3667
|
+
entry: abortTarget.entry,
|
|
3668
|
+
key: abortTarget.key,
|
|
3669
|
+
sessionStore: params.sessionStore,
|
|
3670
|
+
storePath: params.storePath,
|
|
3671
|
+
abortCutoff: params.abortCutoff
|
|
3672
|
+
}) && params.abortKey) setAbortMemory(params.abortKey, true);
|
|
3673
|
+
}
|
|
3674
|
+
function buildAbortTargetApplyParams(params, abortTarget) {
|
|
3675
|
+
return {
|
|
3676
|
+
abortTarget,
|
|
3677
|
+
sessionStore: params.sessionStore,
|
|
3678
|
+
storePath: params.storePath,
|
|
3679
|
+
abortKey: params.command.abortKey,
|
|
3680
|
+
abortCutoff: resolveAbortCutoffForTarget({
|
|
3681
|
+
ctx: params.ctx,
|
|
3682
|
+
commandSessionKey: params.sessionKey,
|
|
3683
|
+
targetSessionKey: abortTarget.key
|
|
3684
|
+
})
|
|
3685
|
+
};
|
|
3686
|
+
}
|
|
3687
|
+
const handleStopCommand = async (params, allowTextCommands) => {
|
|
3688
|
+
if (!allowTextCommands) return null;
|
|
3689
|
+
if (params.command.commandBodyNormalized !== "/stop") return null;
|
|
3690
|
+
const unauthorizedStop = rejectUnauthorizedCommand(params, "/stop");
|
|
3691
|
+
if (unauthorizedStop) return unauthorizedStop;
|
|
3692
|
+
const abortTarget = resolveAbortTarget({
|
|
3693
|
+
ctx: params.ctx,
|
|
3694
|
+
sessionKey: params.sessionKey,
|
|
3695
|
+
sessionEntry: params.sessionEntry,
|
|
3696
|
+
sessionStore: params.sessionStore
|
|
3697
|
+
});
|
|
3698
|
+
const cleared = clearSessionQueues([abortTarget.key, abortTarget.sessionId]);
|
|
3699
|
+
if (cleared.followupCleared > 0 || cleared.laneCleared > 0) logVerbose(`stop: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`);
|
|
3700
|
+
await applyAbortTarget(buildAbortTargetApplyParams(params, abortTarget));
|
|
3701
|
+
await triggerInternalHook(createInternalHookEvent("command", "stop", abortTarget.key ?? params.sessionKey ?? "", {
|
|
3702
|
+
sessionEntry: abortTarget.entry,
|
|
3703
|
+
sessionId: abortTarget.sessionId,
|
|
3704
|
+
commandSource: params.command.surface,
|
|
3705
|
+
senderId: params.command.senderId
|
|
3706
|
+
}));
|
|
3707
|
+
const { stopped } = stopSubagentsForRequester({
|
|
3708
|
+
cfg: params.cfg,
|
|
3709
|
+
requesterSessionKey: abortTarget.key ?? params.sessionKey
|
|
3710
|
+
});
|
|
3711
|
+
return {
|
|
3712
|
+
shouldContinue: false,
|
|
3713
|
+
reply: { text: formatAbortReplyText(stopped) }
|
|
3714
|
+
};
|
|
3715
|
+
};
|
|
3716
|
+
const handleAbortTrigger = async (params, allowTextCommands) => {
|
|
3717
|
+
if (!allowTextCommands) return null;
|
|
3718
|
+
if (!isAbortTrigger(params.command.rawBodyNormalized)) return null;
|
|
3719
|
+
const unauthorizedAbortTrigger = rejectUnauthorizedCommand(params, "abort trigger");
|
|
3720
|
+
if (unauthorizedAbortTrigger) return unauthorizedAbortTrigger;
|
|
3721
|
+
await applyAbortTarget(buildAbortTargetApplyParams(params, resolveAbortTarget({
|
|
3722
|
+
ctx: params.ctx,
|
|
3723
|
+
sessionKey: params.sessionKey,
|
|
3724
|
+
sessionEntry: params.sessionEntry,
|
|
3725
|
+
sessionStore: params.sessionStore
|
|
3726
|
+
})));
|
|
3727
|
+
return {
|
|
3728
|
+
shouldContinue: false,
|
|
3729
|
+
reply: { text: "āļø Agent was aborted." }
|
|
3730
|
+
};
|
|
3731
|
+
};
|
|
3732
|
+
//#endregion
|
|
3733
|
+
//#region src/auto-reply/reply/commands-session.ts
|
|
3734
|
+
const SESSION_DURATION_OFF_VALUES = new Set([
|
|
3735
|
+
"off",
|
|
3736
|
+
"disable",
|
|
3737
|
+
"disabled",
|
|
3738
|
+
"none",
|
|
3739
|
+
"0"
|
|
3740
|
+
]);
|
|
3741
|
+
const SESSION_ACTION_IDLE = "idle";
|
|
3742
|
+
const SESSION_ACTION_MAX_AGE = "max-age";
|
|
3743
|
+
function buildRestartCommandSentinel(params) {
|
|
3744
|
+
const sessionKey = normalizeOptionalString(params.sessionKey);
|
|
3745
|
+
if (!sessionKey) return null;
|
|
3746
|
+
const { deliveryContext, threadId } = extractDeliveryInfo(sessionKey);
|
|
3747
|
+
return {
|
|
3748
|
+
kind: "restart",
|
|
3749
|
+
status: "ok",
|
|
3750
|
+
ts: Date.now(),
|
|
3751
|
+
sessionKey,
|
|
3752
|
+
deliveryContext,
|
|
3753
|
+
threadId,
|
|
3754
|
+
message: "/restart",
|
|
3755
|
+
continuation: buildRestartSuccessContinuation({ sessionKey }),
|
|
3756
|
+
doctorHint: formatDoctorNonInteractiveHint(),
|
|
3757
|
+
stats: {
|
|
3758
|
+
mode: "gateway.restart",
|
|
3759
|
+
reason: "/restart"
|
|
3760
|
+
}
|
|
3761
|
+
};
|
|
3762
|
+
}
|
|
3763
|
+
function resolveSessionCommandUsage() {
|
|
3764
|
+
return "Usage: /session idle <duration|off> | /session max-age <duration|off> (example: /session idle 24h)";
|
|
3765
|
+
}
|
|
3766
|
+
function parseSessionDurationMs(raw) {
|
|
3767
|
+
const normalized = normalizeOptionalLowercaseString(raw);
|
|
3768
|
+
if (!normalized) throw new Error("missing duration");
|
|
3769
|
+
if (SESSION_DURATION_OFF_VALUES.has(normalized)) return 0;
|
|
3770
|
+
if (/^\d+(?:\.\d+)?$/.test(normalized)) {
|
|
3771
|
+
const hours = Number(normalized);
|
|
3772
|
+
if (!Number.isFinite(hours) || hours < 0) throw new Error("invalid duration");
|
|
3773
|
+
return Math.round(hours * 60 * 60 * 1e3);
|
|
3774
|
+
}
|
|
3775
|
+
return parseDurationMs(normalized, { defaultUnit: "h" });
|
|
3776
|
+
}
|
|
3777
|
+
function formatSessionExpiry(expiresAt) {
|
|
3778
|
+
return new Date(expiresAt).toISOString();
|
|
3779
|
+
}
|
|
3780
|
+
function resolveSessionBindingDurationMs(binding, key, fallbackMs) {
|
|
3781
|
+
const raw = binding.metadata?.[key];
|
|
3782
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) return fallbackMs;
|
|
3783
|
+
return Math.max(0, Math.floor(raw));
|
|
3784
|
+
}
|
|
3785
|
+
function resolveSessionBindingLastActivityAt(binding) {
|
|
3786
|
+
const raw = binding.metadata?.lastActivityAt;
|
|
3787
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) return binding.boundAt;
|
|
3788
|
+
return Math.max(Math.floor(raw), binding.boundAt);
|
|
3789
|
+
}
|
|
3790
|
+
function resolveSessionBindingBoundBy(binding) {
|
|
3791
|
+
const raw = binding.metadata?.boundBy;
|
|
3792
|
+
return normalizeOptionalString(raw) ?? "";
|
|
3793
|
+
}
|
|
3794
|
+
function isSessionBindingRecord(binding) {
|
|
3795
|
+
return "bindingId" in binding;
|
|
3796
|
+
}
|
|
3797
|
+
function resolveUpdatedLifecycleDurationMs(binding, key) {
|
|
3798
|
+
if (!isSessionBindingRecord(binding)) {
|
|
3799
|
+
const raw = binding[key];
|
|
3800
|
+
if (typeof raw === "number" && Number.isFinite(raw)) return Math.max(0, Math.floor(raw));
|
|
3801
|
+
}
|
|
3802
|
+
if (!isSessionBindingRecord(binding)) return;
|
|
3803
|
+
const raw = binding.metadata?.[key];
|
|
3804
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) return;
|
|
3805
|
+
return Math.max(0, Math.floor(raw));
|
|
3806
|
+
}
|
|
3807
|
+
function toUpdatedLifecycleBinding(binding) {
|
|
3808
|
+
const lastActivityAt = isSessionBindingRecord(binding) ? resolveSessionBindingLastActivityAt(binding) : Math.max(Math.floor(binding.lastActivityAt), binding.boundAt);
|
|
3809
|
+
return {
|
|
3810
|
+
boundAt: binding.boundAt,
|
|
3811
|
+
lastActivityAt,
|
|
3812
|
+
idleTimeoutMs: resolveUpdatedLifecycleDurationMs(binding, "idleTimeoutMs"),
|
|
3813
|
+
maxAgeMs: resolveUpdatedLifecycleDurationMs(binding, "maxAgeMs")
|
|
3814
|
+
};
|
|
3815
|
+
}
|
|
3816
|
+
function resolveUpdatedBindingExpiry(params) {
|
|
3817
|
+
const expiries = params.bindings.map((binding) => {
|
|
3818
|
+
if (params.action === SESSION_ACTION_IDLE) {
|
|
3819
|
+
const idleTimeoutMs = typeof binding.idleTimeoutMs === "number" && Number.isFinite(binding.idleTimeoutMs) ? Math.max(0, Math.floor(binding.idleTimeoutMs)) : 0;
|
|
3820
|
+
if (idleTimeoutMs <= 0) return;
|
|
3821
|
+
return Math.max(binding.lastActivityAt, binding.boundAt) + idleTimeoutMs;
|
|
3822
|
+
}
|
|
3823
|
+
const maxAgeMs = typeof binding.maxAgeMs === "number" && Number.isFinite(binding.maxAgeMs) ? Math.max(0, Math.floor(binding.maxAgeMs)) : 0;
|
|
3824
|
+
if (maxAgeMs <= 0) return;
|
|
3825
|
+
return binding.boundAt + maxAgeMs;
|
|
3826
|
+
}).filter((expiresAt) => typeof expiresAt === "number");
|
|
3827
|
+
if (expiries.length === 0) return;
|
|
3828
|
+
return Math.min(...expiries);
|
|
3829
|
+
}
|
|
3830
|
+
const handleActivationCommand = async (params, allowTextCommands) => {
|
|
3831
|
+
if (!allowTextCommands) return null;
|
|
3832
|
+
const activationCommand = parseActivationCommand(params.command.commandBodyNormalized);
|
|
3833
|
+
if (!activationCommand.hasCommand) return null;
|
|
3834
|
+
if (!params.isGroup) return {
|
|
3835
|
+
shouldContinue: false,
|
|
3836
|
+
reply: { text: "āļø Group activation only applies to group chats." }
|
|
3837
|
+
};
|
|
3838
|
+
if (!params.command.isAuthorizedSender) {
|
|
3839
|
+
logVerbose(`Ignoring /activation from unauthorized sender in group: ${params.command.senderId || "<unknown>"}`);
|
|
3840
|
+
return { shouldContinue: false };
|
|
3841
|
+
}
|
|
3842
|
+
if (!activationCommand.mode) return {
|
|
3843
|
+
shouldContinue: false,
|
|
3844
|
+
reply: { text: "āļø Usage: /activation mention|always" }
|
|
3845
|
+
};
|
|
3846
|
+
if (params.sessionEntry && params.sessionStore && params.sessionKey) {
|
|
3847
|
+
params.sessionEntry.groupActivation = activationCommand.mode;
|
|
3848
|
+
params.sessionEntry.groupActivationNeedsSystemIntro = true;
|
|
3849
|
+
await persistSessionEntry(params);
|
|
3850
|
+
}
|
|
3851
|
+
return {
|
|
3852
|
+
shouldContinue: false,
|
|
3853
|
+
reply: { text: `āļø Group activation set to ${activationCommand.mode}.` }
|
|
3854
|
+
};
|
|
3855
|
+
};
|
|
3856
|
+
const handleSendPolicyCommand = async (params, allowTextCommands) => {
|
|
3857
|
+
if (!allowTextCommands) return null;
|
|
3858
|
+
const sendPolicyCommand = parseSendPolicyCommand(params.command.commandBodyNormalized);
|
|
3859
|
+
if (!sendPolicyCommand.hasCommand) return null;
|
|
3860
|
+
const unauthorizedResult = rejectUnauthorizedCommand(params, "/send");
|
|
3861
|
+
if (unauthorizedResult) return unauthorizedResult;
|
|
3862
|
+
const nonOwnerResult = rejectNonOwnerCommand(params, "/send");
|
|
3863
|
+
if (nonOwnerResult) return nonOwnerResult;
|
|
3864
|
+
if (!sendPolicyCommand.mode) return {
|
|
3865
|
+
shouldContinue: false,
|
|
3866
|
+
reply: { text: "āļø Usage: /send on|off|inherit" }
|
|
3867
|
+
};
|
|
3868
|
+
if (params.sessionEntry && params.sessionStore && params.sessionKey) {
|
|
3869
|
+
if (sendPolicyCommand.mode === "inherit") delete params.sessionEntry.sendPolicy;
|
|
3870
|
+
else params.sessionEntry.sendPolicy = sendPolicyCommand.mode;
|
|
3871
|
+
await persistSessionEntry(params);
|
|
3872
|
+
}
|
|
3873
|
+
return {
|
|
3874
|
+
shouldContinue: false,
|
|
3875
|
+
reply: { text: `āļø Send policy set to ${sendPolicyCommand.mode === "inherit" ? "inherit" : sendPolicyCommand.mode === "allow" ? "on" : "off"}.` }
|
|
3876
|
+
};
|
|
3877
|
+
};
|
|
3878
|
+
const handleUsageCommand = async (params, allowTextCommands) => {
|
|
3879
|
+
if (!allowTextCommands) return null;
|
|
3880
|
+
const normalized = params.command.commandBodyNormalized;
|
|
3881
|
+
if (normalized !== "/usage" && !normalized.startsWith("/usage ")) return null;
|
|
3882
|
+
if (!params.command.isAuthorizedSender) {
|
|
3883
|
+
logVerbose(`Ignoring /usage from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
3884
|
+
return { shouldContinue: false };
|
|
3885
|
+
}
|
|
3886
|
+
const rawArgs = normalized === "/usage" ? "" : normalized.slice(6).trim();
|
|
3887
|
+
const requested = rawArgs ? normalizeUsageDisplay(rawArgs) : void 0;
|
|
3888
|
+
if (normalizeLowercaseStringOrEmpty(rawArgs).startsWith("cost")) {
|
|
3889
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
3890
|
+
const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
|
|
3891
|
+
sessionKey: params.sessionKey,
|
|
3892
|
+
config: params.cfg
|
|
3893
|
+
}) : params.agentId;
|
|
3894
|
+
const sessionSummary = await loadSessionCostSummary({
|
|
3895
|
+
sessionId: targetSessionEntry?.sessionId,
|
|
3896
|
+
sessionEntry: targetSessionEntry,
|
|
3897
|
+
sessionFile: targetSessionEntry?.sessionFile,
|
|
3898
|
+
config: params.cfg,
|
|
3899
|
+
agentId: sessionAgentId
|
|
3900
|
+
});
|
|
3901
|
+
const summary = await loadCostUsageSummary({
|
|
3902
|
+
days: 30,
|
|
3903
|
+
config: params.cfg
|
|
3904
|
+
});
|
|
3905
|
+
const sessionCost = formatUsd(sessionSummary?.totalCost);
|
|
3906
|
+
const sessionTokens = sessionSummary?.totalTokens ? formatTokenCount(sessionSummary.totalTokens) : void 0;
|
|
3907
|
+
const sessionSuffix = (sessionSummary?.missingCostEntries ?? 0) > 0 ? " (partial)" : "";
|
|
3908
|
+
const sessionLine = sessionCost || sessionTokens ? `Session ${sessionCost ?? "n/a"}${sessionSuffix}${sessionTokens ? ` Ā· ${sessionTokens} tokens` : ""}` : "Session n/a";
|
|
3909
|
+
const todayKey = (/* @__PURE__ */ new Date()).toLocaleDateString("en-CA");
|
|
3910
|
+
const todayEntry = summary.daily.find((entry) => entry.date === todayKey);
|
|
3911
|
+
const todayCost = formatUsd(todayEntry?.totalCost);
|
|
3912
|
+
const todaySuffix = (todayEntry?.missingCostEntries ?? 0) > 0 ? " (partial)" : "";
|
|
3913
|
+
const todayLine = `Today ${todayCost ?? "n/a"}${todaySuffix}`;
|
|
3914
|
+
const last30Cost = formatUsd(summary.totals.totalCost);
|
|
3915
|
+
const last30Suffix = summary.totals.missingCostEntries > 0 ? " (partial)" : "";
|
|
3916
|
+
return {
|
|
3917
|
+
shouldContinue: false,
|
|
3918
|
+
reply: { text: `šø Usage cost\n${sessionLine}\n${todayLine}\n${`Last 30d ${last30Cost ?? "n/a"}${last30Suffix}`}` }
|
|
3919
|
+
};
|
|
3920
|
+
}
|
|
3921
|
+
if (rawArgs && !requested) return {
|
|
3922
|
+
shouldContinue: false,
|
|
3923
|
+
reply: { text: "āļø Usage: /usage off|tokens|full|cost" }
|
|
3924
|
+
};
|
|
3925
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
3926
|
+
const currentRaw = targetSessionEntry?.responseUsage;
|
|
3927
|
+
const current = resolveResponseUsageMode(currentRaw);
|
|
3928
|
+
const next = requested ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
|
|
3929
|
+
if (targetSessionEntry && params.sessionStore && params.sessionKey) {
|
|
3930
|
+
if (next === "off") delete targetSessionEntry.responseUsage;
|
|
3931
|
+
else targetSessionEntry.responseUsage = next;
|
|
3932
|
+
params.sessionStore[params.sessionKey] = targetSessionEntry;
|
|
3933
|
+
await persistSessionEntry({
|
|
3934
|
+
...params,
|
|
3935
|
+
sessionEntry: targetSessionEntry
|
|
3936
|
+
});
|
|
3937
|
+
}
|
|
3938
|
+
return {
|
|
3939
|
+
shouldContinue: false,
|
|
3940
|
+
reply: { text: `āļø Usage footer: ${next}.` }
|
|
3941
|
+
};
|
|
3942
|
+
};
|
|
3943
|
+
const handleFastCommand = async (params, allowTextCommands) => {
|
|
3944
|
+
if (!allowTextCommands) return null;
|
|
3945
|
+
const normalized = params.command.commandBodyNormalized;
|
|
3946
|
+
if (normalized !== "/fast" && !normalized.startsWith("/fast ")) return null;
|
|
3947
|
+
if (!params.command.isAuthorizedSender) {
|
|
3948
|
+
logVerbose(`Ignoring /fast from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
3949
|
+
return { shouldContinue: false };
|
|
3950
|
+
}
|
|
3951
|
+
const rawMode = normalizeLowercaseStringOrEmpty(normalized === "/fast" ? "" : normalized.slice(5).trim());
|
|
3952
|
+
if (!rawMode || rawMode === "status") {
|
|
3953
|
+
const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
|
|
3954
|
+
const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
|
|
3955
|
+
sessionKey: params.sessionKey,
|
|
3956
|
+
config: params.cfg
|
|
3957
|
+
}) : params.agentId;
|
|
3958
|
+
const state = resolveFastModeState({
|
|
3959
|
+
cfg: params.cfg,
|
|
3960
|
+
provider: params.provider,
|
|
3961
|
+
model: params.model,
|
|
3962
|
+
agentId: sessionAgentId,
|
|
3963
|
+
sessionEntry: targetSessionEntry
|
|
3964
|
+
});
|
|
3965
|
+
const suffix = state.source === "agent" ? " (agent)" : state.source === "config" ? " (config)" : state.source === "default" ? " (default)" : "";
|
|
3966
|
+
return {
|
|
3967
|
+
shouldContinue: false,
|
|
3968
|
+
reply: { text: `āļø Current fast mode: ${state.enabled ? "on" : "off"}${suffix}.` }
|
|
3969
|
+
};
|
|
3970
|
+
}
|
|
3971
|
+
const nextMode = normalizeFastMode(rawMode);
|
|
3972
|
+
if (nextMode === void 0) return {
|
|
3973
|
+
shouldContinue: false,
|
|
3974
|
+
reply: { text: "āļø Usage: /fast status|on|off" }
|
|
3975
|
+
};
|
|
3976
|
+
if (params.sessionEntry && params.sessionStore && params.sessionKey) {
|
|
3977
|
+
params.sessionEntry.fastMode = nextMode;
|
|
3978
|
+
await persistSessionEntry(params);
|
|
3979
|
+
}
|
|
3980
|
+
return {
|
|
3981
|
+
shouldContinue: false,
|
|
3982
|
+
reply: { text: `āļø Fast mode ${nextMode ? "enabled" : "disabled"}.` }
|
|
3983
|
+
};
|
|
3984
|
+
};
|
|
3985
|
+
const handleSessionCommand = async (params, allowTextCommands) => {
|
|
3986
|
+
if (!allowTextCommands) return null;
|
|
3987
|
+
const normalized = params.command.commandBodyNormalized;
|
|
3988
|
+
if (!/^\/session(?:\s|$)/.test(normalized)) return null;
|
|
3989
|
+
if (!params.command.isAuthorizedSender) {
|
|
3990
|
+
logVerbose(`Ignoring /session from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
3991
|
+
return { shouldContinue: false };
|
|
3992
|
+
}
|
|
3993
|
+
const tokens = normalized.slice(8).trim().split(/\s+/).filter(Boolean);
|
|
3994
|
+
const action = normalizeOptionalLowercaseString(tokens[0]);
|
|
3995
|
+
if (action !== SESSION_ACTION_IDLE && action !== SESSION_ACTION_MAX_AGE) return {
|
|
3996
|
+
shouldContinue: false,
|
|
3997
|
+
reply: { text: resolveSessionCommandUsage() }
|
|
3998
|
+
};
|
|
3999
|
+
const channelId = params.command.channelId ?? normalizeChannelId$1(resolveCommandSurfaceChannel(params)) ?? void 0;
|
|
4000
|
+
const commandConversationBindings = channelId ? getChannelPlugin(channelId)?.conversationBindings : void 0;
|
|
4001
|
+
const commandSupportsCurrentConversationBinding = Boolean(commandConversationBindings?.supportsCurrentConversationBinding);
|
|
4002
|
+
const commandSupportsLifecycleUpdate = action === SESSION_ACTION_IDLE ? typeof commandConversationBindings?.setIdleTimeoutBySessionKey === "function" : typeof commandConversationBindings?.setMaxAgeBySessionKey === "function";
|
|
4003
|
+
const bindingContext = resolveConversationBindingContextFromAcpCommand(params);
|
|
4004
|
+
if (!bindingContext) {
|
|
4005
|
+
if (!channelId || !commandSupportsCurrentConversationBinding || !commandSupportsLifecycleUpdate) return {
|
|
4006
|
+
shouldContinue: false,
|
|
4007
|
+
reply: { text: "ā ļø /session idle and /session max-age are currently available only on channels that support focused conversation bindings." }
|
|
4008
|
+
};
|
|
4009
|
+
return {
|
|
4010
|
+
shouldContinue: false,
|
|
4011
|
+
reply: { text: "ā ļø /session idle and /session max-age must be run inside a focused conversation." }
|
|
4012
|
+
};
|
|
4013
|
+
}
|
|
4014
|
+
const resolvedChannelId = bindingContext.channel || channelId;
|
|
4015
|
+
const conversationBindings = resolvedChannelId ? getChannelPlugin(resolvedChannelId)?.conversationBindings : void 0;
|
|
4016
|
+
const supportsCurrentConversationBinding = Boolean(conversationBindings?.supportsCurrentConversationBinding);
|
|
4017
|
+
const supportsLifecycleUpdate = action === SESSION_ACTION_IDLE ? typeof conversationBindings?.setIdleTimeoutBySessionKey === "function" : typeof conversationBindings?.setMaxAgeBySessionKey === "function";
|
|
4018
|
+
if (!resolvedChannelId || !supportsCurrentConversationBinding || !supportsLifecycleUpdate) return {
|
|
4019
|
+
shouldContinue: false,
|
|
4020
|
+
reply: { text: "ā ļø /session idle and /session max-age are currently available only on channels that support focused conversation bindings." }
|
|
4021
|
+
};
|
|
4022
|
+
const activeBinding = getSessionBindingService().resolveByConversation(bindingContext);
|
|
4023
|
+
if (!activeBinding) return {
|
|
4024
|
+
shouldContinue: false,
|
|
4025
|
+
reply: { text: "ā¹ļø This conversation is not currently focused." }
|
|
4026
|
+
};
|
|
4027
|
+
const idleTimeoutMs = resolveSessionBindingDurationMs(activeBinding, "idleTimeoutMs", 1440 * 60 * 1e3);
|
|
4028
|
+
const idleExpiresAt = idleTimeoutMs > 0 ? resolveSessionBindingLastActivityAt(activeBinding) + idleTimeoutMs : void 0;
|
|
4029
|
+
const maxAgeMs = resolveSessionBindingDurationMs(activeBinding, "maxAgeMs", 0);
|
|
4030
|
+
const maxAgeExpiresAt = maxAgeMs > 0 ? activeBinding.boundAt + maxAgeMs : void 0;
|
|
4031
|
+
const durationArgRaw = tokens.slice(1).join("");
|
|
4032
|
+
if (!durationArgRaw) {
|
|
4033
|
+
if (action === SESSION_ACTION_IDLE) {
|
|
4034
|
+
if (typeof idleExpiresAt === "number" && Number.isFinite(idleExpiresAt) && idleExpiresAt > Date.now()) return {
|
|
4035
|
+
shouldContinue: false,
|
|
4036
|
+
reply: { text: `ā¹ļø Idle timeout active (${formatThreadBindingDurationLabel(idleTimeoutMs)}, next auto-unfocus at ${formatSessionExpiry(idleExpiresAt)}).` }
|
|
4037
|
+
};
|
|
4038
|
+
return {
|
|
4039
|
+
shouldContinue: false,
|
|
4040
|
+
reply: { text: "ā¹ļø Idle timeout is currently disabled for this focused session." }
|
|
4041
|
+
};
|
|
4042
|
+
}
|
|
4043
|
+
if (typeof maxAgeExpiresAt === "number" && Number.isFinite(maxAgeExpiresAt) && maxAgeExpiresAt > Date.now()) return {
|
|
4044
|
+
shouldContinue: false,
|
|
4045
|
+
reply: { text: `ā¹ļø Max age active (${formatThreadBindingDurationLabel(maxAgeMs)}, hard auto-unfocus at ${formatSessionExpiry(maxAgeExpiresAt)}).` }
|
|
4046
|
+
};
|
|
4047
|
+
return {
|
|
4048
|
+
shouldContinue: false,
|
|
4049
|
+
reply: { text: "ā¹ļø Max age is currently disabled for this focused session." }
|
|
4050
|
+
};
|
|
4051
|
+
}
|
|
4052
|
+
const senderId = normalizeOptionalString(params.command.senderId) ?? "";
|
|
4053
|
+
const boundBy = resolveSessionBindingBoundBy(activeBinding);
|
|
4054
|
+
if (boundBy && boundBy !== "system" && senderId && senderId !== boundBy) return {
|
|
4055
|
+
shouldContinue: false,
|
|
4056
|
+
reply: { text: `ā ļø Only ${boundBy} can update session lifecycle settings for this conversation.` }
|
|
4057
|
+
};
|
|
4058
|
+
let durationMs;
|
|
4059
|
+
try {
|
|
4060
|
+
durationMs = parseSessionDurationMs(durationArgRaw);
|
|
4061
|
+
} catch {
|
|
4062
|
+
return {
|
|
4063
|
+
shouldContinue: false,
|
|
4064
|
+
reply: { text: resolveSessionCommandUsage() }
|
|
4065
|
+
};
|
|
4066
|
+
}
|
|
4067
|
+
const updatedBindings = action === SESSION_ACTION_IDLE ? setChannelConversationBindingIdleTimeoutBySessionKey({
|
|
4068
|
+
channelId: bindingContext.channel,
|
|
4069
|
+
targetSessionKey: activeBinding.targetSessionKey,
|
|
4070
|
+
accountId: bindingContext.accountId,
|
|
4071
|
+
idleTimeoutMs: durationMs
|
|
4072
|
+
}) : setChannelConversationBindingMaxAgeBySessionKey({
|
|
4073
|
+
channelId: bindingContext.channel,
|
|
4074
|
+
targetSessionKey: activeBinding.targetSessionKey,
|
|
4075
|
+
accountId: bindingContext.accountId,
|
|
4076
|
+
maxAgeMs: durationMs
|
|
4077
|
+
});
|
|
4078
|
+
if (updatedBindings.length === 0) return {
|
|
4079
|
+
shouldContinue: false,
|
|
4080
|
+
reply: { text: action === SESSION_ACTION_IDLE ? "ā ļø Failed to update idle timeout for the current binding." : "ā ļø Failed to update max age for the current binding." }
|
|
4081
|
+
};
|
|
4082
|
+
if (durationMs <= 0) return {
|
|
4083
|
+
shouldContinue: false,
|
|
4084
|
+
reply: { text: action === SESSION_ACTION_IDLE ? `ā
Idle timeout disabled for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"}.` : `ā
Max age disabled for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"}.` }
|
|
4085
|
+
};
|
|
4086
|
+
const nextExpiry = resolveUpdatedBindingExpiry({
|
|
4087
|
+
action,
|
|
4088
|
+
bindings: updatedBindings.map((binding) => toUpdatedLifecycleBinding(binding))
|
|
4089
|
+
});
|
|
4090
|
+
const expiryLabel = typeof nextExpiry === "number" && Number.isFinite(nextExpiry) ? formatSessionExpiry(nextExpiry) : "n/a";
|
|
4091
|
+
return {
|
|
4092
|
+
shouldContinue: false,
|
|
4093
|
+
reply: { text: action === SESSION_ACTION_IDLE ? `ā
Idle timeout set to ${formatThreadBindingDurationLabel(durationMs)} for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"} (next auto-unfocus at ${expiryLabel}).` : `ā
Max age set to ${formatThreadBindingDurationLabel(durationMs)} for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"} (hard auto-unfocus at ${expiryLabel}).` }
|
|
4094
|
+
};
|
|
4095
|
+
};
|
|
4096
|
+
const handleRestartCommand = async (params, allowTextCommands) => {
|
|
4097
|
+
if (!allowTextCommands) return null;
|
|
4098
|
+
if (params.command.commandBodyNormalized !== "/restart") return null;
|
|
4099
|
+
if (!params.command.isAuthorizedSender) {
|
|
4100
|
+
logVerbose(`Ignoring /restart from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
4101
|
+
return { shouldContinue: false };
|
|
4102
|
+
}
|
|
4103
|
+
const nonOwner = rejectNonOwnerCommand(params, "/restart");
|
|
4104
|
+
if (nonOwner) return nonOwner;
|
|
4105
|
+
if (!isRestartEnabled(params.cfg)) return {
|
|
4106
|
+
shouldContinue: false,
|
|
4107
|
+
reply: { text: "ā ļø /restart is disabled (commands.restart=false)." }
|
|
4108
|
+
};
|
|
4109
|
+
const hasSigusr1Listener = process.listenerCount("SIGUSR1") > 0;
|
|
4110
|
+
const sentinelPayload = buildRestartCommandSentinel(params);
|
|
4111
|
+
if (hasSigusr1Listener) {
|
|
4112
|
+
let sentinelPath = null;
|
|
4113
|
+
scheduleGatewaySigusr1Restart({
|
|
4114
|
+
reason: "/restart",
|
|
4115
|
+
emitHooks: sentinelPayload ? {
|
|
4116
|
+
beforeEmit: async () => {
|
|
4117
|
+
sentinelPath = await writeRestartSentinel(sentinelPayload);
|
|
4118
|
+
},
|
|
4119
|
+
afterEmitRejected: async () => {
|
|
4120
|
+
await removeRestartSentinelFile(sentinelPath);
|
|
4121
|
+
}
|
|
4122
|
+
} : void 0
|
|
4123
|
+
});
|
|
4124
|
+
return {
|
|
4125
|
+
shouldContinue: false,
|
|
4126
|
+
reply: { text: "āļø Restarting Genesis in-process (SIGUSR1); back in a few seconds." }
|
|
4127
|
+
};
|
|
4128
|
+
}
|
|
4129
|
+
let sentinelPath = null;
|
|
4130
|
+
try {
|
|
4131
|
+
if (sentinelPayload) sentinelPath = await writeRestartSentinel(sentinelPayload);
|
|
4132
|
+
} catch (err) {
|
|
4133
|
+
logVerbose(`failed to write /restart sentinel: ${String(err)}`);
|
|
4134
|
+
return {
|
|
4135
|
+
shouldContinue: false,
|
|
4136
|
+
reply: { text: "ā ļø Restart failed: could not persist the post-restart acknowledgement." }
|
|
4137
|
+
};
|
|
4138
|
+
}
|
|
4139
|
+
const restartMethod = triggerGenesisRestart();
|
|
4140
|
+
if (!restartMethod.ok) {
|
|
4141
|
+
await removeRestartSentinelFile(sentinelPath);
|
|
4142
|
+
const detail = restartMethod.detail ? ` Details: ${restartMethod.detail}` : "";
|
|
4143
|
+
return {
|
|
4144
|
+
shouldContinue: false,
|
|
4145
|
+
reply: { text: `ā ļø Restart failed (${restartMethod.method}).${detail}` }
|
|
4146
|
+
};
|
|
4147
|
+
}
|
|
4148
|
+
return {
|
|
4149
|
+
shouldContinue: false,
|
|
4150
|
+
reply: { text: `āļø Restarting Genesis via ${restartMethod.method}; give me a few seconds to come back online.` }
|
|
4151
|
+
};
|
|
4152
|
+
};
|
|
4153
|
+
//#endregion
|
|
4154
|
+
//#region src/auto-reply/reply/commands-subagents.ts
|
|
4155
|
+
let actionAgentsPromise = null;
|
|
4156
|
+
let actionFocusPromise = null;
|
|
4157
|
+
let actionHelpPromise = null;
|
|
4158
|
+
let actionInfoPromise = null;
|
|
4159
|
+
let actionKillPromise = null;
|
|
4160
|
+
let actionListPromise = null;
|
|
4161
|
+
let actionLogPromise = null;
|
|
4162
|
+
let actionSendPromise = null;
|
|
4163
|
+
let actionSpawnPromise = null;
|
|
4164
|
+
let actionUnfocusPromise = null;
|
|
4165
|
+
let controlRuntimePromise = null;
|
|
4166
|
+
function loadAgentsAction() {
|
|
4167
|
+
actionAgentsPromise ??= import("./action-agents-fjIM4rpc.js");
|
|
4168
|
+
return actionAgentsPromise;
|
|
4169
|
+
}
|
|
4170
|
+
function loadFocusAction() {
|
|
4171
|
+
actionFocusPromise ??= import("./action-focus-cx1pm1ym.js");
|
|
4172
|
+
return actionFocusPromise;
|
|
4173
|
+
}
|
|
4174
|
+
function loadHelpAction() {
|
|
4175
|
+
actionHelpPromise ??= import("./action-help-DtyAnULB.js");
|
|
4176
|
+
return actionHelpPromise;
|
|
4177
|
+
}
|
|
4178
|
+
function loadInfoAction() {
|
|
4179
|
+
actionInfoPromise ??= import("./action-info-DF30-xZl.js");
|
|
4180
|
+
return actionInfoPromise;
|
|
4181
|
+
}
|
|
4182
|
+
function loadKillAction() {
|
|
4183
|
+
actionKillPromise ??= import("./action-kill-rsSdXzvX.js");
|
|
4184
|
+
return actionKillPromise;
|
|
4185
|
+
}
|
|
4186
|
+
function loadListAction() {
|
|
4187
|
+
actionListPromise ??= import("./action-list-4VN835m2.js");
|
|
4188
|
+
return actionListPromise;
|
|
4189
|
+
}
|
|
4190
|
+
function loadLogAction() {
|
|
4191
|
+
actionLogPromise ??= import("./action-log-L032mq5B.js");
|
|
4192
|
+
return actionLogPromise;
|
|
4193
|
+
}
|
|
4194
|
+
function loadSendAction() {
|
|
4195
|
+
actionSendPromise ??= import("./action-send-Dm62UP-n.js");
|
|
4196
|
+
return actionSendPromise;
|
|
4197
|
+
}
|
|
4198
|
+
function loadSpawnAction() {
|
|
4199
|
+
actionSpawnPromise ??= import("./action-spawn-BuZHKlpL.js");
|
|
4200
|
+
return actionSpawnPromise;
|
|
4201
|
+
}
|
|
4202
|
+
function loadUnfocusAction() {
|
|
4203
|
+
actionUnfocusPromise ??= import("./action-unfocus-CTIWf8WX.js");
|
|
4204
|
+
return actionUnfocusPromise;
|
|
4205
|
+
}
|
|
4206
|
+
function loadControlRuntime() {
|
|
4207
|
+
controlRuntimePromise ??= import("./commands-subagents-control.runtime-DUeSQ5j4.js");
|
|
4208
|
+
return controlRuntimePromise;
|
|
4209
|
+
}
|
|
4210
|
+
const handleSubagentsCommand = async (params, allowTextCommands) => {
|
|
4211
|
+
if (!allowTextCommands) return null;
|
|
4212
|
+
const normalized = params.command.commandBodyNormalized;
|
|
4213
|
+
const handledPrefix = resolveHandledPrefix(normalized);
|
|
4214
|
+
if (!handledPrefix) return null;
|
|
4215
|
+
if (!params.command.isAuthorizedSender) {
|
|
4216
|
+
logVerbose(`Ignoring ${handledPrefix} from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
4217
|
+
return { shouldContinue: false };
|
|
4218
|
+
}
|
|
4219
|
+
const restTokens = normalized.slice(handledPrefix.length).trim().split(/\s+/).filter(Boolean);
|
|
4220
|
+
const action = resolveSubagentsAction({
|
|
4221
|
+
handledPrefix,
|
|
4222
|
+
restTokens
|
|
4223
|
+
});
|
|
4224
|
+
if (!action) return (await loadHelpAction()).handleSubagentsHelpAction();
|
|
4225
|
+
const requesterKey = action === "spawn" ? resolveRequesterSessionKey(params, { preferCommandTarget: true }) : resolveRequesterSessionKey(params);
|
|
4226
|
+
if (!requesterKey) return stopWithText("ā ļø Missing session key.");
|
|
4227
|
+
const ctx = {
|
|
4228
|
+
params,
|
|
4229
|
+
handledPrefix,
|
|
4230
|
+
requesterKey,
|
|
4231
|
+
runs: (await loadControlRuntime()).listControlledSubagentRuns(requesterKey),
|
|
4232
|
+
restTokens
|
|
4233
|
+
};
|
|
4234
|
+
switch (action) {
|
|
4235
|
+
case "help": return (await loadHelpAction()).handleSubagentsHelpAction();
|
|
4236
|
+
case "agents": return (await loadAgentsAction()).handleSubagentsAgentsAction(ctx);
|
|
4237
|
+
case "focus": return await (await loadFocusAction()).handleSubagentsFocusAction(ctx);
|
|
4238
|
+
case "unfocus": return await (await loadUnfocusAction()).handleSubagentsUnfocusAction(ctx);
|
|
4239
|
+
case "list": return (await loadListAction()).handleSubagentsListAction(ctx);
|
|
4240
|
+
case "kill": return await (await loadKillAction()).handleSubagentsKillAction(ctx);
|
|
4241
|
+
case "info": return (await loadInfoAction()).handleSubagentsInfoAction(ctx);
|
|
4242
|
+
case "log": return await (await loadLogAction()).handleSubagentsLogAction(ctx);
|
|
4243
|
+
case "send": return await (await loadSendAction()).handleSubagentsSendAction(ctx, false);
|
|
4244
|
+
case "steer": return await (await loadSendAction()).handleSubagentsSendAction(ctx, true);
|
|
4245
|
+
case "spawn": return await (await loadSpawnAction()).handleSubagentsSpawnAction(ctx);
|
|
4246
|
+
default: return (await loadHelpAction()).handleSubagentsHelpAction();
|
|
4247
|
+
}
|
|
4248
|
+
};
|
|
4249
|
+
//#endregion
|
|
4250
|
+
//#region src/auto-reply/reply/commands-tasks.ts
|
|
4251
|
+
const MAX_VISIBLE_TASKS = 5;
|
|
4252
|
+
const TASK_STATUS_ICONS = {
|
|
4253
|
+
queued: "š”",
|
|
4254
|
+
running: "š¢",
|
|
4255
|
+
succeeded: "ā
",
|
|
4256
|
+
failed: "š“",
|
|
4257
|
+
timed_out: "ā±ļø",
|
|
4258
|
+
cancelled: "āŖļø",
|
|
4259
|
+
lost: "ā ļø"
|
|
4260
|
+
};
|
|
4261
|
+
const TASK_RUNTIME_LABELS = {
|
|
4262
|
+
subagent: "Subagent",
|
|
4263
|
+
acp: "ACP",
|
|
4264
|
+
cli: "CLI",
|
|
4265
|
+
cron: "Cron"
|
|
4266
|
+
};
|
|
4267
|
+
function formatTaskHeadline(snapshot) {
|
|
4268
|
+
if (snapshot.totalCount === 0) return "All clear - nothing linked to this session right now.";
|
|
4269
|
+
return `Current session: ${snapshot.activeCount} active Ā· ${snapshot.totalCount} total`;
|
|
4270
|
+
}
|
|
4271
|
+
function formatAgentFallbackLine(agentId) {
|
|
4272
|
+
const snapshot = buildTaskStatusSnapshot(listTasksForAgentIdForStatus(agentId));
|
|
4273
|
+
if (snapshot.totalCount === 0) return;
|
|
4274
|
+
return `Agent-local: ${snapshot.activeCount} active Ā· ${snapshot.totalCount} total`;
|
|
4275
|
+
}
|
|
4276
|
+
function formatTaskTiming(task) {
|
|
4277
|
+
if (task.status === "running") {
|
|
4278
|
+
const startedAt = task.startedAt ?? task.createdAt;
|
|
4279
|
+
return `elapsed ${formatDurationCompact(Date.now() - startedAt, { spaced: true }) ?? "0s"}`;
|
|
4280
|
+
}
|
|
4281
|
+
if (task.status === "queued") return `queued ${formatTimeAgo(Date.now() - task.createdAt)}`;
|
|
4282
|
+
const endedAt = task.endedAt ?? task.lastEventAt ?? task.createdAt;
|
|
4283
|
+
return `finished ${formatTimeAgo(Date.now() - endedAt)}`;
|
|
4284
|
+
}
|
|
4285
|
+
function formatTaskDetail(task) {
|
|
4286
|
+
return formatTaskStatusDetail(task);
|
|
4287
|
+
}
|
|
4288
|
+
function formatVisibleTask(task, index) {
|
|
4289
|
+
const title = formatTaskStatusTitle(task);
|
|
4290
|
+
const status = task.status.replaceAll("_", " ");
|
|
4291
|
+
const timing = formatTaskTiming(task);
|
|
4292
|
+
const detail = formatTaskDetail(task);
|
|
4293
|
+
const meta = [
|
|
4294
|
+
TASK_RUNTIME_LABELS[task.runtime],
|
|
4295
|
+
status,
|
|
4296
|
+
timing
|
|
4297
|
+
].filter(Boolean).join(" Ā· ");
|
|
4298
|
+
const lines = [`${index + 1}. ${TASK_STATUS_ICONS[task.status]} ${title}`, ` ${meta}`];
|
|
4299
|
+
if (detail) lines.push(` ${detail}`);
|
|
4300
|
+
return lines.join("\n");
|
|
4301
|
+
}
|
|
4302
|
+
function buildTasksText(params) {
|
|
4303
|
+
const sessionSnapshot = buildTaskStatusSnapshot(listTasksForSessionKeyForStatus(params.sessionKey));
|
|
4304
|
+
const lines = ["š Tasks", formatTaskHeadline(sessionSnapshot)];
|
|
4305
|
+
if (sessionSnapshot.totalCount > 0) {
|
|
4306
|
+
const visible = sessionSnapshot.visible.slice(0, MAX_VISIBLE_TASKS);
|
|
4307
|
+
lines.push("");
|
|
4308
|
+
for (const [index, task] of visible.entries()) {
|
|
4309
|
+
lines.push(formatVisibleTask(task, index));
|
|
4310
|
+
if (index < visible.length - 1) lines.push("");
|
|
4311
|
+
}
|
|
4312
|
+
const hiddenCount = sessionSnapshot.visible.length - visible.length;
|
|
4313
|
+
if (hiddenCount > 0) lines.push("", `+${hiddenCount} more recent task${hiddenCount === 1 ? "" : "s"}`);
|
|
4314
|
+
return lines.join("\n");
|
|
4315
|
+
}
|
|
4316
|
+
const agentFallback = formatAgentFallbackLine(params.agentId);
|
|
4317
|
+
if (agentFallback) lines.push(agentFallback);
|
|
4318
|
+
return lines.join("\n");
|
|
4319
|
+
}
|
|
4320
|
+
async function buildTasksReply(params) {
|
|
4321
|
+
const agentId = resolveSessionAgentId({
|
|
4322
|
+
sessionKey: params.sessionKey,
|
|
4323
|
+
config: params.cfg
|
|
4324
|
+
});
|
|
4325
|
+
return { text: buildTasksText({
|
|
4326
|
+
sessionKey: params.sessionKey,
|
|
4327
|
+
agentId
|
|
4328
|
+
}) };
|
|
4329
|
+
}
|
|
4330
|
+
const handleTasksCommand = async (params, allowTextCommands) => {
|
|
4331
|
+
if (!allowTextCommands) return null;
|
|
4332
|
+
const normalized = params.command.commandBodyNormalized;
|
|
4333
|
+
if (normalized !== "/tasks" && !normalized.startsWith("/tasks ")) return null;
|
|
4334
|
+
if (!params.command.isAuthorizedSender) {
|
|
4335
|
+
logVerbose(`Ignoring /tasks from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
4336
|
+
return { shouldContinue: false };
|
|
4337
|
+
}
|
|
4338
|
+
if (normalized !== "/tasks") return {
|
|
4339
|
+
shouldContinue: false,
|
|
4340
|
+
reply: { text: "Usage: /tasks" }
|
|
4341
|
+
};
|
|
4342
|
+
return {
|
|
4343
|
+
shouldContinue: false,
|
|
4344
|
+
reply: await buildTasksReply(params)
|
|
4345
|
+
};
|
|
4346
|
+
};
|
|
4347
|
+
//#endregion
|
|
4348
|
+
//#region src/auto-reply/reply/commands-tts.ts
|
|
4349
|
+
function parseTtsCommand(normalized) {
|
|
4350
|
+
if (normalized === "/tts") return {
|
|
4351
|
+
action: "status",
|
|
4352
|
+
args: ""
|
|
4353
|
+
};
|
|
4354
|
+
if (!normalized.startsWith("/tts ")) return null;
|
|
4355
|
+
const rest = normalized.slice(5).trim();
|
|
4356
|
+
if (!rest) return {
|
|
4357
|
+
action: "status",
|
|
4358
|
+
args: ""
|
|
4359
|
+
};
|
|
4360
|
+
const [action, ...tail] = rest.split(/\s+/);
|
|
4361
|
+
return {
|
|
4362
|
+
action: normalizeOptionalLowercaseString(action) ?? "",
|
|
4363
|
+
args: normalizeOptionalString(tail.join(" ")) ?? ""
|
|
4364
|
+
};
|
|
4365
|
+
}
|
|
4366
|
+
function formatAttemptDetails(attempts) {
|
|
4367
|
+
if (!attempts || attempts.length === 0) return;
|
|
4368
|
+
return attempts.map((attempt) => {
|
|
4369
|
+
const reason = attempt.reasonCode === "success" ? "ok" : attempt.reasonCode;
|
|
4370
|
+
const latency = Number.isFinite(attempt.latencyMs) ? ` ${attempt.latencyMs}ms` : "";
|
|
4371
|
+
return `${attempt.provider}:${attempt.outcome}(${reason})${latency}`;
|
|
4372
|
+
}).join(", ");
|
|
4373
|
+
}
|
|
4374
|
+
function ttsUsage() {
|
|
4375
|
+
return { text: "š **TTS (Text-to-Speech) Help**\n\n**Commands:**\n⢠/tts on ā Enable automatic TTS for replies\n⢠/tts off ā Disable TTS\n⢠/tts status ā Show current settings\n⢠/tts provider [name] ā View/change provider\n⢠/tts limit [number] ā View/change text limit\n⢠/tts summary [on|off] ā View/change auto-summary\n⢠/tts audio <text> ā Generate audio from text\n\n**Providers:**\nUse /tts provider to list the registered speech providers and their status.\n\n**Text Limit (default: 1500, max: 4096):**\nWhen text exceeds the limit:\n⢠Summary ON: AI summarizes, then generates audio\n⢠Summary OFF: Truncates text, then generates audio\n\n**Examples:**\n/tts provider <id>\n/tts limit 2000\n/tts audio Hello, this is a test!" };
|
|
4376
|
+
}
|
|
4377
|
+
const handleTtsCommands = async (params, allowTextCommands) => {
|
|
4378
|
+
if (!allowTextCommands) return null;
|
|
4379
|
+
const parsed = parseTtsCommand(params.command.commandBodyNormalized);
|
|
4380
|
+
if (!parsed) return null;
|
|
4381
|
+
if (!params.command.isAuthorizedSender) {
|
|
4382
|
+
logVerbose(`Ignoring TTS command from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
|
|
4383
|
+
return { shouldContinue: false };
|
|
4384
|
+
}
|
|
4385
|
+
const config = resolveTtsConfig(params.cfg);
|
|
4386
|
+
const prefsPath = resolveTtsPrefsPath(config);
|
|
4387
|
+
const action = parsed.action;
|
|
4388
|
+
const args = parsed.args;
|
|
4389
|
+
if (action === "help") return {
|
|
4390
|
+
shouldContinue: false,
|
|
4391
|
+
reply: ttsUsage()
|
|
4392
|
+
};
|
|
4393
|
+
if (action === "on") {
|
|
4394
|
+
setTtsEnabled(prefsPath, true);
|
|
4395
|
+
return {
|
|
4396
|
+
shouldContinue: false,
|
|
4397
|
+
reply: { text: "š TTS enabled." }
|
|
4398
|
+
};
|
|
4399
|
+
}
|
|
4400
|
+
if (action === "off") {
|
|
4401
|
+
setTtsEnabled(prefsPath, false);
|
|
4402
|
+
return {
|
|
4403
|
+
shouldContinue: false,
|
|
4404
|
+
reply: { text: "š TTS disabled." }
|
|
4405
|
+
};
|
|
4406
|
+
}
|
|
4407
|
+
if (action === "audio") {
|
|
4408
|
+
if (!args.trim()) return {
|
|
4409
|
+
shouldContinue: false,
|
|
4410
|
+
reply: { text: "š¤ Generate audio from text.\n\nUsage: /tts audio <text>\nExample: /tts audio Hello, this is a test!" }
|
|
4411
|
+
};
|
|
4412
|
+
const start = Date.now();
|
|
4413
|
+
const result = await textToSpeech({
|
|
4414
|
+
text: args,
|
|
4415
|
+
cfg: params.cfg,
|
|
4416
|
+
channel: params.command.channel,
|
|
4417
|
+
prefsPath
|
|
4418
|
+
});
|
|
4419
|
+
if (result.success && result.audioPath) {
|
|
4420
|
+
setLastTtsAttempt({
|
|
4421
|
+
timestamp: Date.now(),
|
|
4422
|
+
success: true,
|
|
4423
|
+
textLength: args.length,
|
|
4424
|
+
summarized: false,
|
|
4425
|
+
provider: result.provider,
|
|
4426
|
+
fallbackFrom: result.fallbackFrom,
|
|
4427
|
+
attemptedProviders: result.attemptedProviders,
|
|
4428
|
+
attempts: result.attempts,
|
|
4429
|
+
latencyMs: result.latencyMs
|
|
4430
|
+
});
|
|
4431
|
+
return {
|
|
4432
|
+
shouldContinue: false,
|
|
4433
|
+
reply: {
|
|
4434
|
+
mediaUrl: result.audioPath,
|
|
4435
|
+
audioAsVoice: result.voiceCompatible === true,
|
|
4436
|
+
trustedLocalMedia: true,
|
|
4437
|
+
spokenText: args
|
|
4438
|
+
}
|
|
4439
|
+
};
|
|
4440
|
+
}
|
|
4441
|
+
setLastTtsAttempt({
|
|
4442
|
+
timestamp: Date.now(),
|
|
4443
|
+
success: false,
|
|
4444
|
+
textLength: args.length,
|
|
4445
|
+
summarized: false,
|
|
4446
|
+
attemptedProviders: result.attemptedProviders,
|
|
4447
|
+
attempts: result.attempts,
|
|
4448
|
+
error: result.error,
|
|
4449
|
+
latencyMs: Date.now() - start
|
|
4450
|
+
});
|
|
4451
|
+
return {
|
|
4452
|
+
shouldContinue: false,
|
|
4453
|
+
reply: { text: `ā Error generating audio: ${result.error ?? "unknown error"}` }
|
|
4454
|
+
};
|
|
4455
|
+
}
|
|
4456
|
+
if (action === "provider") {
|
|
4457
|
+
const currentProvider = getTtsProvider(config, prefsPath);
|
|
4458
|
+
if (!args.trim()) {
|
|
4459
|
+
const providers = listSpeechProviders(params.cfg);
|
|
4460
|
+
return {
|
|
4461
|
+
shouldContinue: false,
|
|
4462
|
+
reply: { text: `šļø TTS provider\nPrimary: ${currentProvider}\n` + providers.map((provider) => `${provider.label}: ${provider.isConfigured({
|
|
4463
|
+
cfg: params.cfg,
|
|
4464
|
+
providerConfig: getResolvedSpeechProviderConfig(config, provider.id, params.cfg),
|
|
4465
|
+
timeoutMs: config.timeoutMs
|
|
4466
|
+
}) ? "ā
" : "ā"}`).join("\n") + `\nUsage: /tts provider <id>` }
|
|
4467
|
+
};
|
|
4468
|
+
}
|
|
4469
|
+
const requested = normalizeOptionalLowercaseString(args) ?? "";
|
|
4470
|
+
const resolvedProvider = getSpeechProvider(requested, params.cfg);
|
|
4471
|
+
if (!resolvedProvider) return {
|
|
4472
|
+
shouldContinue: false,
|
|
4473
|
+
reply: ttsUsage()
|
|
4474
|
+
};
|
|
4475
|
+
const nextProvider = canonicalizeSpeechProviderId(requested, params.cfg) ?? resolvedProvider.id;
|
|
4476
|
+
setTtsProvider(prefsPath, nextProvider);
|
|
4477
|
+
return {
|
|
4478
|
+
shouldContinue: false,
|
|
4479
|
+
reply: { text: `ā
TTS provider set to ${nextProvider}.` }
|
|
4480
|
+
};
|
|
4481
|
+
}
|
|
4482
|
+
if (action === "limit") {
|
|
4483
|
+
if (!args.trim()) return {
|
|
4484
|
+
shouldContinue: false,
|
|
4485
|
+
reply: { text: `š TTS limit: ${getTtsMaxLength(prefsPath)} characters.\n\nText longer than this triggers summary (if enabled).\nRange: 100-4096 chars (Telegram max).\n\nTo change: /tts limit <number>\nExample: /tts limit 2000` }
|
|
4486
|
+
};
|
|
4487
|
+
const next = Number.parseInt(args.trim(), 10);
|
|
4488
|
+
if (!Number.isFinite(next) || next < 100 || next > 4096) return {
|
|
4489
|
+
shouldContinue: false,
|
|
4490
|
+
reply: { text: "ā Limit must be between 100 and 4096 characters." }
|
|
4491
|
+
};
|
|
4492
|
+
setTtsMaxLength(prefsPath, next);
|
|
4493
|
+
return {
|
|
4494
|
+
shouldContinue: false,
|
|
4495
|
+
reply: { text: `ā
TTS limit set to ${next} characters.` }
|
|
4496
|
+
};
|
|
4497
|
+
}
|
|
4498
|
+
if (action === "summary") {
|
|
4499
|
+
if (!args.trim()) {
|
|
4500
|
+
const enabled = isSummarizationEnabled(prefsPath);
|
|
4501
|
+
const maxLen = getTtsMaxLength(prefsPath);
|
|
4502
|
+
return {
|
|
4503
|
+
shouldContinue: false,
|
|
4504
|
+
reply: { text: `š TTS auto-summary: ${enabled ? "on" : "off"}.\n\nWhen text exceeds ${maxLen} chars:\n⢠ON: summarizes text, then generates audio\n⢠OFF: truncates text, then generates audio\n\nTo change: /tts summary on | off` }
|
|
4505
|
+
};
|
|
4506
|
+
}
|
|
4507
|
+
const requested = normalizeOptionalLowercaseString(args) ?? "";
|
|
4508
|
+
if (requested !== "on" && requested !== "off") return {
|
|
4509
|
+
shouldContinue: false,
|
|
4510
|
+
reply: ttsUsage()
|
|
4511
|
+
};
|
|
4512
|
+
setSummarizationEnabled(prefsPath, requested === "on");
|
|
4513
|
+
return {
|
|
4514
|
+
shouldContinue: false,
|
|
4515
|
+
reply: { text: requested === "on" ? "ā
TTS auto-summary enabled." : "ā TTS auto-summary disabled." }
|
|
4516
|
+
};
|
|
4517
|
+
}
|
|
4518
|
+
if (action === "status") {
|
|
4519
|
+
const enabled = isTtsEnabled(config, prefsPath);
|
|
4520
|
+
const provider = getTtsProvider(config, prefsPath);
|
|
4521
|
+
const hasKey = isTtsProviderConfigured(config, provider, params.cfg);
|
|
4522
|
+
const maxLength = getTtsMaxLength(prefsPath);
|
|
4523
|
+
const summarize = isSummarizationEnabled(prefsPath);
|
|
4524
|
+
const last = getLastTtsAttempt();
|
|
4525
|
+
const lines = [
|
|
4526
|
+
"š TTS status",
|
|
4527
|
+
`State: ${enabled ? "ā
enabled" : "ā disabled"}`,
|
|
4528
|
+
`Provider: ${provider} (${hasKey ? "ā
configured" : "ā not configured"})`,
|
|
4529
|
+
`Text limit: ${maxLength} chars`,
|
|
4530
|
+
`Auto-summary: ${summarize ? "on" : "off"}`
|
|
4531
|
+
];
|
|
4532
|
+
if (last) {
|
|
4533
|
+
const timeAgo = Math.round((Date.now() - last.timestamp) / 1e3);
|
|
4534
|
+
lines.push("");
|
|
4535
|
+
lines.push(`Last attempt (${timeAgo}s ago): ${last.success ? "ā
" : "ā"}`);
|
|
4536
|
+
lines.push(`Text: ${last.textLength} chars${last.summarized ? " (summarized)" : ""}`);
|
|
4537
|
+
if (last.success) {
|
|
4538
|
+
lines.push(`Provider: ${last.provider ?? "unknown"}`);
|
|
4539
|
+
if (last.fallbackFrom && last.provider && last.fallbackFrom !== last.provider) lines.push(`Fallback: ${last.fallbackFrom} -> ${last.provider}`);
|
|
4540
|
+
if (last.attemptedProviders && last.attemptedProviders.length > 1) lines.push(`Attempts: ${last.attemptedProviders.join(" -> ")}`);
|
|
4541
|
+
const details = formatAttemptDetails(last.attempts);
|
|
4542
|
+
if (details) lines.push(`Attempt details: ${details}`);
|
|
4543
|
+
lines.push(`Latency: ${last.latencyMs ?? 0}ms`);
|
|
4544
|
+
} else if (last.error) {
|
|
4545
|
+
lines.push(`Error: ${last.error}`);
|
|
4546
|
+
if (last.attemptedProviders && last.attemptedProviders.length > 0) lines.push(`Attempts: ${last.attemptedProviders.join(" -> ")}`);
|
|
4547
|
+
const details = formatAttemptDetails(last.attempts);
|
|
4548
|
+
if (details) lines.push(`Attempt details: ${details}`);
|
|
4549
|
+
}
|
|
4550
|
+
}
|
|
4551
|
+
return {
|
|
4552
|
+
shouldContinue: false,
|
|
4553
|
+
reply: { text: lines.join("\n") }
|
|
4554
|
+
};
|
|
4555
|
+
}
|
|
4556
|
+
return {
|
|
4557
|
+
shouldContinue: false,
|
|
4558
|
+
reply: ttsUsage()
|
|
4559
|
+
};
|
|
4560
|
+
};
|
|
4561
|
+
//#endregion
|
|
4562
|
+
//#region src/auto-reply/reply/commands-handlers.runtime.ts
|
|
4563
|
+
function loadCommandHandlers() {
|
|
4564
|
+
return [
|
|
4565
|
+
handlePluginCommand,
|
|
4566
|
+
handleBtwCommand,
|
|
4567
|
+
handleBashCommand,
|
|
4568
|
+
handleActivationCommand,
|
|
4569
|
+
handleSendPolicyCommand,
|
|
4570
|
+
handleFastCommand,
|
|
4571
|
+
handleUsageCommand,
|
|
4572
|
+
handleSessionCommand,
|
|
4573
|
+
handleRestartCommand,
|
|
4574
|
+
handleTtsCommands,
|
|
4575
|
+
handleHelpCommand,
|
|
4576
|
+
handleCommandsListCommand,
|
|
4577
|
+
handleToolsCommand,
|
|
4578
|
+
handleStatusCommand,
|
|
4579
|
+
handleTasksCommand,
|
|
4580
|
+
handleAllowlistCommand,
|
|
4581
|
+
handleApproveCommand,
|
|
4582
|
+
handleContextCommand,
|
|
4583
|
+
handleExportSessionCommand,
|
|
4584
|
+
handleExportTrajectoryCommand,
|
|
4585
|
+
handleWhoamiCommand,
|
|
4586
|
+
handleSubagentsCommand,
|
|
4587
|
+
handleAcpCommand,
|
|
4588
|
+
handleMcpCommand,
|
|
4589
|
+
handlePluginsCommand,
|
|
4590
|
+
handleConfigCommand,
|
|
4591
|
+
handleDebugCommand,
|
|
4592
|
+
handleModelsCommand,
|
|
4593
|
+
handleStopCommand,
|
|
4594
|
+
handleCompactCommand,
|
|
4595
|
+
handleAbortTrigger
|
|
4596
|
+
];
|
|
4597
|
+
}
|
|
4598
|
+
//#endregion
|
|
4599
|
+
export { loadCommandHandlers };
|