@code-yeongyu/senpi 2026.11.2-3 → 2026.11.3-2
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 +55 -0
- package/dist/bundle/chunks/anthropic-messages-LJAKRKMX.js +11 -0
- package/dist/bundle/chunks/{args-AOI4NEA6.js → args-GQTXDYS3.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-YLBBQXI7.js → azure-openai-responses-HDEKTPMZ.js} +1 -1
- package/dist/bundle/chunks/chatgpt-subscription.js +10 -2
- package/dist/bundle/chunks/{chunk-ED7VJGL4.js → chunk-2PGSRQBF.js} +1 -1
- package/dist/bundle/chunks/{chunk-LMIETUPG.js → chunk-3LDASCJN.js} +1 -1
- package/dist/bundle/chunks/{chunk-PIAY636U.js → chunk-3QPE75AR.js} +1 -1
- package/dist/bundle/chunks/{chunk-FQZZGSYH.js → chunk-4ZGQUOBV.js} +1 -1
- package/dist/bundle/chunks/{chunk-S2M5D5GS.js → chunk-5BMIET5O.js} +2 -2
- package/dist/bundle/chunks/{chunk-XLLQJALL.js → chunk-67M7HKXO.js} +1 -1
- package/dist/bundle/chunks/chunk-6ISOXWH2.js +2 -0
- package/dist/bundle/chunks/{chunk-IWM5QRAE.js → chunk-6NPK2O3C.js} +2 -2
- package/dist/bundle/chunks/{chunk-FO56LSUK.js → chunk-7C4W5HMU.js} +1 -1
- package/dist/bundle/chunks/chunk-7KIHKE2T.js +2 -0
- package/dist/bundle/chunks/{chunk-BW4YXS7X.js → chunk-A4KOQUHT.js} +1 -1
- package/dist/bundle/chunks/{chunk-FJSJUVQQ.js → chunk-A5PZGQCP.js} +3 -3
- package/dist/bundle/chunks/{chunk-TBARMJ75.js → chunk-AVP6DDBF.js} +1 -1
- package/dist/bundle/chunks/{chunk-KVPRQ5KN.js → chunk-B3GTID4P.js} +1 -1
- package/dist/bundle/chunks/{chunk-2XBKE2BZ.js → chunk-BIWFWGUA.js} +1 -1
- package/dist/bundle/chunks/{chunk-6LDUM5CL.js → chunk-DCI4QOUX.js} +1 -1
- package/dist/bundle/chunks/{chunk-2YFPDNNP.js → chunk-DNZKKG4V.js} +1 -1
- package/dist/bundle/chunks/{chunk-W2V7RIBF.js → chunk-E7SA75PP.js} +1 -1
- package/dist/bundle/chunks/{chunk-YWD54RHU.js → chunk-EBZ6IP4V.js} +1 -1
- package/dist/bundle/chunks/{chunk-N4TSAHRL.js → chunk-EVTTLPIY.js} +1 -1
- package/dist/bundle/chunks/{chunk-J2OBN7TI.js → chunk-G5XUGK4B.js} +1 -1
- package/dist/bundle/chunks/{chunk-IHOQR7TU.js → chunk-GKP34H3C.js} +2 -2
- package/dist/bundle/chunks/{chunk-PP52OWBB.js → chunk-GLTOBXZY.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSVWKOAJ.js → chunk-IJGXAACA.js} +263 -237
- package/dist/bundle/chunks/{chunk-LGO25HPL.js → chunk-JCTODLUP.js} +1 -1
- package/dist/bundle/chunks/{chunk-3ESZE3DG.js → chunk-KHBCZ6TR.js} +1 -1
- package/dist/bundle/chunks/chunk-KJR3XXMI.js +2 -0
- package/dist/bundle/chunks/{chunk-TVMW2SUP.js → chunk-KY4V3TSO.js} +2 -2
- package/dist/bundle/chunks/{chunk-T5ZJ2Q4O.js → chunk-MCXOJHN2.js} +1 -1
- package/dist/bundle/chunks/{chunk-GIY7PGOH.js → chunk-NKI7L5UM.js} +3 -3
- package/dist/bundle/chunks/{chunk-L3V65XW7.js → chunk-OD7RT7G7.js} +1 -1
- package/dist/bundle/chunks/{chunk-NYXXKS6D.js → chunk-OOU3BRUY.js} +3 -2
- package/dist/bundle/chunks/{chunk-LPHUMR6R.js → chunk-OT6ALXSJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-XGBRBCIQ.js → chunk-Q5CKFBQT.js} +1 -1
- package/dist/bundle/chunks/{chunk-F7GBSQRV.js → chunk-QPYDQ4QK.js} +1 -1
- package/dist/bundle/chunks/{chunk-7FUO655J.js → chunk-QSMT5KVJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-SAZ6E74O.js → chunk-RUOTFZQR.js} +1 -1
- package/dist/bundle/chunks/chunk-RWF6IJQL.js +448 -0
- package/dist/bundle/chunks/{chunk-P4AT7SBE.js → chunk-S5Y7NEHB.js} +1 -1
- package/dist/bundle/chunks/{chunk-QLTQ3UUI.js → chunk-SCBTASM4.js} +1 -1
- package/dist/bundle/chunks/chunk-SJWTZ3Z2.js +2 -0
- package/dist/bundle/chunks/{chunk-ISZ4EWIS.js → chunk-SODMQEHO.js} +1 -1
- package/dist/bundle/chunks/{chunk-WEGTCUO3.js → chunk-SQAQEITV.js} +1 -1
- package/dist/bundle/chunks/{chunk-UFVZTQKN.js → chunk-TQQG5L4D.js} +1 -1
- package/dist/bundle/chunks/{chunk-662SCMTH.js → chunk-U6A4X3FV.js} +1 -1
- package/dist/bundle/chunks/{chunk-ACIFXWJ6.js → chunk-UHUM55TR.js} +1 -1
- package/dist/bundle/chunks/{chunk-L5OFGHDA.js → chunk-USKWGPA6.js} +1 -1
- package/dist/bundle/chunks/{chunk-7ORS33CE.js → chunk-VDDJADPV.js} +1 -1
- package/dist/bundle/chunks/{chunk-R65P6LAT.js → chunk-VIHXG53S.js} +1 -1
- package/dist/bundle/chunks/{chunk-SGS76663.js → chunk-VPVD5G32.js} +1 -1
- package/dist/bundle/chunks/chunk-WO6I5PRF.js +3 -0
- package/dist/bundle/chunks/{chunk-ETCYVVVO.js → chunk-WVEIJ437.js} +1 -1
- package/dist/bundle/chunks/{chunk-VRWJJMHO.js → chunk-XKFG4N3Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-57MRFI6E.js → chunk-XMWPCJU6.js} +1 -1
- package/dist/bundle/chunks/{chunk-GDPWQJDQ.js → chunk-XPSXUKSD.js} +1 -1
- package/dist/bundle/chunks/{chunk-FNBEICAA.js → chunk-YI6KRJDC.js} +1 -1
- package/dist/bundle/chunks/{chunk-UURGXV5B.js → chunk-YP47G4YP.js} +1 -1
- package/dist/bundle/chunks/{chunk-TXOR5BQL.js → chunk-YRYDCKUI.js} +1 -1
- package/dist/bundle/chunks/{chunk-QAM6AXA2.js → chunk-YTKZSGMQ.js} +12 -9
- package/dist/bundle/chunks/{chunk-V36CXIIB.js → chunk-YXL3PNTL.js} +1 -1
- package/dist/bundle/chunks/chunk-Z7HTHT6K.js +2 -0
- package/dist/bundle/chunks/{chunk-27XEDYQA.js → chunk-ZTPG27EJ.js} +1 -1
- package/dist/bundle/chunks/{cli-main-534A3WSC.js → cli-main-RN7YB427.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-FC7QLRU2.js → cloudflare-workers-ai-system-one-N5KFNKK4.js} +1 -1
- package/dist/bundle/chunks/credential-accounts-BJX55MTT.js +2 -0
- package/dist/bundle/chunks/devin.js +10 -2
- package/dist/bundle/chunks/{dispatch-UY6LBJJE.js → dispatch-M7UAPGVY.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-7PQ4QRHJ.js → google-generative-ai-2TZSCSIS.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-DY7EO4EJ.js → google-vertex-7NJJOI7V.js} +1 -1
- package/dist/bundle/chunks/{health-write-EB4CPHXN.js → health-write-YUSPVH7U.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-U2PSNNWO.js → help-fast-path-DWCA77QP.js} +1 -1
- package/dist/bundle/chunks/host-command-KJXUTSQ7.js +2 -0
- package/dist/bundle/chunks/{host-lifecycle-TGG7KGQH.js → host-lifecycle-QHIJ4G2K.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +1 -1
- package/dist/bundle/chunks/{host-session-command-PWVPQ2OV.js → host-session-command-IPH3WXSG.js} +1 -1
- package/dist/bundle/chunks/{host-socket-request-F2R5P34M.js → host-socket-request-XPXJV3CS.js} +1 -1
- package/dist/bundle/chunks/interactive-mode-XUXMDYLA.js +2 -0
- package/dist/bundle/chunks/{list-tips-3D3A6GFK.js → list-tips-XJY7EL5S.js} +1 -1
- package/dist/bundle/chunks/{login-health-7G2DZVOV.js → login-health-226NO44U.js} +1 -1
- package/dist/bundle/chunks/main-P7PKMJUG.js +2 -0
- package/dist/bundle/chunks/{mistral-conversations-6F2RAIB2.js → mistral-conversations-QMHMHSUF.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-7E26R5JF.js → multi-session-host-ZQY4AN46.js} +4 -4
- package/dist/bundle/chunks/{native-loader-NMDTMHMA.js → native-loader-A6DNMGCK.js} +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +11 -3
- package/dist/bundle/chunks/{openai-codex-responses-VNBMMIL3.js → openai-codex-responses-GUAHKQE2.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-JLR32APM.js → openai-completions-UPRTFM54.js} +1 -1
- package/dist/bundle/chunks/{openai-images-LEBNERSM.js → openai-images-IKWNS6VB.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-JCDUNMHA.js → openai-responses-AXN5NUHH.js} +1 -1
- package/dist/bundle/chunks/openrouter.js +10 -2
- package/dist/bundle/chunks/{package-manager-cli-CBSDV36M.js → package-manager-cli-PP7L2Q5M.js} +1 -1
- package/dist/bundle/chunks/radius.js +10 -2
- package/dist/bundle/chunks/{rg-engine-JDUYBM6L.js → rg-engine-VRSXT6HG.js} +1 -1
- package/dist/bundle/chunks/{role-LP6LVNCY.js → role-L5J7ZPCF.js} +1 -1
- package/dist/bundle/chunks/rotation-stream-6INZXQFC.js +2 -0
- package/dist/bundle/chunks/rpc-mode-W4UATRAT.js +2 -0
- package/dist/bundle/chunks/{rpc-monitor-source-5TUR27NY.js → rpc-monitor-source-RMMUPBMS.js} +1 -1
- package/dist/bundle/chunks/{run-attached-tui-PVLUHHJX.js → run-attached-tui-RLXFGCEP.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-W45NYTTK.js → schedule-command-ZNFEJNTT.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-LFLUNALC.js → session-control-endpoint-TWTONJWF.js} +1 -1
- package/dist/bundle/chunks/{session-picker-OZUINLD7.js → session-picker-KRUVCHOV.js} +1 -1
- package/dist/bundle/chunks/session-slot-NJOZCOHQ.js +2 -0
- package/dist/bundle/chunks/session-worker.js +492 -461
- package/dist/bundle/chunks/{state-store-SZARKD36.js → state-store-ZAFZ4JOM.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-5JYDJK6S.js → typesafe-system-one-CICIRAYN.js} +1 -1
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/agent-session.d.ts +8 -0
- package/dist/core/agent-session.js +73 -63
- package/dist/core/auth-storage.d.ts +19 -0
- package/dist/core/auth-storage.js +99 -24
- package/dist/core/auth-store-load-error.d.ts +29 -0
- package/dist/core/auth-store-load-error.js +74 -0
- package/dist/core/brand.d.ts +2 -0
- package/dist/core/brand.js +1 -0
- package/dist/core/credential-pool/classify.d.ts +3 -2
- package/dist/core/credential-pool/classify.js +10 -3
- package/dist/core/credential-pool/failover.d.ts +8 -0
- package/dist/core/credential-pool/failover.js +18 -5
- package/dist/core/credential-pool/rotation-stream.d.ts +1 -1
- package/dist/core/credential-pool/rotation-stream.js +2 -7
- package/dist/core/credential-pool/session-slot.d.ts +20 -0
- package/dist/core/credential-pool/session-slot.js +26 -0
- package/dist/core/credential-recovery-revision.d.ts +10 -0
- package/dist/core/credential-recovery-revision.js +19 -0
- package/dist/core/dynamic-prompt/build.d.ts +2 -1
- package/dist/core/dynamic-prompt/build.js +1 -2
- package/dist/core/dynamic-prompt/handoff.d.ts +1 -1
- package/dist/core/dynamic-prompt/handoff.js +9 -9
- package/dist/core/dynamic-prompt/identity.js +1 -1
- package/dist/core/dynamic-prompt/intent-gate.d.ts +1 -1
- package/dist/core/dynamic-prompt/intent-gate.js +8 -8
- package/dist/core/dynamic-prompt/policies.d.ts +1 -1
- package/dist/core/dynamic-prompt/policies.js +5 -7
- package/dist/core/dynamic-prompt/style.js +5 -5
- package/dist/core/dynamic-prompt/tool-section.d.ts +5 -0
- package/dist/core/dynamic-prompt/tool-section.js +8 -6
- package/dist/core/dynamic-prompt/verification.d.ts +6 -6
- package/dist/core/dynamic-prompt/verification.js +12 -12
- package/dist/core/dynamic-prompt/working-task.d.ts +1 -1
- package/dist/core/dynamic-prompt/working-task.js +3 -3
- package/dist/core/dynamic-prompt/workstation.js +1 -1
- package/dist/core/execution/executor-body.d.ts +22 -0
- package/dist/core/execution/executor-body.js +73 -0
- package/dist/core/execution/executor-freeze.d.ts +17 -0
- package/dist/core/execution/executor-freeze.js +53 -0
- package/dist/core/execution/executor-pipeline.d.ts +9 -0
- package/dist/core/execution/executor-pipeline.js +25 -0
- package/dist/core/execution/executor-types.d.ts +82 -0
- package/dist/core/execution/executor-types.js +2 -0
- package/dist/core/execution/executor.d.ts +8 -0
- package/dist/core/execution/executor.js +216 -0
- package/dist/core/extensions/builtin/anthropic-subscription/account-block-log.d.ts +15 -0
- package/dist/core/extensions/builtin/anthropic-subscription/account-block-log.js +18 -0
- package/dist/core/extensions/builtin/anthropic-subscription/affinity.d.ts +9 -1
- package/dist/core/extensions/builtin/anthropic-subscription/affinity.js +15 -4
- package/dist/core/extensions/builtin/anthropic-subscription/failover.d.ts +7 -1
- package/dist/core/extensions/builtin/anthropic-subscription/failover.js +19 -2
- package/dist/core/extensions/builtin/anthropic-subscription/guidance.d.ts +8 -2
- package/dist/core/extensions/builtin/anthropic-subscription/guidance.js +25 -1
- package/dist/core/extensions/builtin/anthropic-subscription/provider-diagnostic.d.ts +9 -0
- package/dist/core/extensions/builtin/anthropic-subscription/provider-diagnostic.js +59 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.d.ts +13 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.js +64 -2
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-wiring.js +7 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-stream.js +5 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.d.ts +7 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-attempt.js +28 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-types.d.ts +2 -0
- package/dist/core/extensions/builtin/anthropic-subscription/stream-guidance.js +5 -3
- package/dist/core/extensions/builtin/anthropic-subscription/stream.js +4 -0
- package/dist/core/extensions/builtin/bash-timeout/index.d.ts +1 -1
- package/dist/core/extensions/builtin/bash-timeout/index.js +3 -28
- package/dist/core/extensions/builtin/bash-timeout/timeout.d.ts +0 -11
- package/dist/core/extensions/builtin/bash-timeout/timeout.js +0 -11
- package/dist/core/extensions/builtin/btw/index.js +3 -1
- package/dist/core/extensions/builtin/cache-keepalive/index.js +3 -1
- package/dist/core/extensions/builtin/compaction/index.js +1 -1
- package/dist/core/extensions/builtin/compaction/openai-remote.d.ts +3 -1
- package/dist/core/extensions/builtin/compaction/openai-remote.js +1 -1
- package/dist/core/extensions/builtin/compaction/speculative.js +3 -2
- package/dist/core/extensions/builtin/cursor-cli-oauth/account-command.js +3 -1
- package/dist/core/extensions/builtin/cursor-cli-oauth/native-bootstrap.js +3 -1
- package/dist/core/extensions/builtin/imagegen/index.d.ts +0 -1
- package/dist/core/extensions/builtin/imagegen/index.js +0 -11
- package/dist/core/extensions/builtin/look-at/runner.js +3 -1
- package/dist/core/extensions/builtin/mcp/auth/callback.js +3 -4
- package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +2 -1
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.d.ts +5 -5
- package/dist/core/extensions/builtin/prompt-preset/execution-tooling.js +5 -5
- package/dist/core/extensions/builtin/prompt-preset/glm-5.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/glm-5.js +1 -1
- package/dist/core/extensions/builtin/terminal/extension.js +8 -1
- package/dist/core/extensions/builtin/terminal/notify.js +9 -3
- package/dist/core/extensions/builtin/terminal/prompt.d.ts +7 -1
- package/dist/core/extensions/builtin/terminal/prompt.js +27 -60
- package/dist/core/extensions/builtin/terminal/tools/bash.js +10 -2
- package/dist/core/extensions/builtin/todotools/normalize.d.ts +20 -3
- package/dist/core/extensions/builtin/todotools/normalize.js +251 -5
- package/dist/core/extensions/builtin/todotools/prompt.d.ts +2 -2
- package/dist/core/extensions/builtin/todotools/prompt.js +5 -5
- package/dist/core/extensions/builtin/todotools/tools/todo.js +9 -8
- package/dist/core/extensions/builtin/webfetch/webfetch/tool.js +0 -5
- package/dist/core/extensions/builtin/websearch/index.js +9 -4
- package/dist/core/extensions/builtin/websearch/websearch/tool.d.ts +2 -0
- package/dist/core/extensions/builtin/websearch/websearch/tool.js +3 -1
- package/dist/core/model-registry.d.ts +10 -2
- package/dist/core/model-registry.js +12 -4
- package/dist/core/model-runtime.d.ts +8 -0
- package/dist/core/model-runtime.js +39 -1
- package/dist/core/provider-failure.d.ts +6 -0
- package/dist/core/provider-failure.js +6 -2
- package/dist/core/retry-fallback/controller-types.d.ts +7 -0
- package/dist/core/retry-fallback/controller.d.ts +2 -0
- package/dist/core/retry-fallback/controller.js +13 -4
- package/dist/core/retry-fallback/credential-recovery.d.ts +18 -0
- package/dist/core/retry-fallback/credential-recovery.js +32 -0
- package/dist/core/retry-fallback/exhaustion.d.ts +18 -0
- package/dist/core/retry-fallback/exhaustion.js +20 -0
- package/dist/core/retry-fallback/settings.d.ts +8 -1
- package/dist/core/retry-fallback/settings.js +12 -6
- package/dist/core/session-log.js +1 -1
- package/dist/core/settings-manager.js +4 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/tools/bash.d.ts +3 -1
- package/dist/core/tools/bash.js +14 -4
- package/dist/core/tools/edit.d.ts +1 -1
- package/dist/core/tools/edit.js +1 -6
- package/dist/core/tools/grep/index.js +2 -3
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.js +1 -1
- package/dist/core/tools/read.d.ts +1 -1
- package/dist/core/tools/read.js +1 -1
- package/dist/core/tools/write.d.ts +1 -1
- package/dist/core/tools/write.js +1 -1
- package/dist/engine-trust/shell-trust.d.ts +36 -0
- package/dist/engine-trust/shell-trust.js +44 -0
- package/dist/engine-trust/transport-failure.d.ts +12 -0
- package/dist/engine-trust/transport-failure.js +48 -0
- package/dist/modes/interactive/interactive-mode.js +9 -3
- package/dist/modes/print-mode.js +2 -1
- package/dist/modes/rpc/compact-catalog-families.d.ts +5 -2
- package/dist/modes/rpc/compact-catalog-families.js +5 -2
- package/dist/modes/rpc/compact-catalog-registry.d.ts +9 -1
- package/dist/modes/rpc/compact-catalog-registry.js +9 -2
- package/dist/modes/rpc/compact-recovery-manifest-kinds.d.ts +17 -0
- package/dist/modes/rpc/compact-recovery-manifest-kinds.js +21 -0
- package/dist/modes/rpc/compact-recovery-manifest-shape.d.ts +7 -0
- package/dist/modes/rpc/compact-recovery-manifest.js +11 -3
- package/dist/modes/rpc/compact-socket-commands.js +6 -0
- package/dist/modes/rpc/connection-handler.js +24 -6
- package/dist/modes/rpc/connection-question-bridge.d.ts +3 -1
- package/dist/modes/rpc/connection-question-bridge.js +4 -1
- package/dist/modes/rpc/connection-roles.d.ts +8 -0
- package/dist/modes/rpc/connection-roles.js +18 -0
- package/dist/modes/rpc/effect-commands.d.ts +1 -0
- package/dist/modes/rpc/loopless-execute-grant.d.ts +20 -0
- package/dist/modes/rpc/loopless-execute-grant.js +26 -0
- package/dist/modes/rpc/loopless-runtime-settings.d.ts +30 -0
- package/dist/modes/rpc/loopless-runtime-settings.js +69 -0
- package/dist/modes/rpc/loopless-tool-call.d.ts +12 -0
- package/dist/modes/rpc/loopless-tool-call.js +22 -0
- package/dist/modes/rpc/method-classes-schema-session.d.ts +4 -0
- package/dist/modes/rpc/method-classes-schema-session.js +1 -0
- package/dist/modes/rpc/method-classes-schema.d.ts +4 -0
- package/dist/modes/rpc/protocol-identity.js +2 -0
- package/dist/modes/rpc/remote-origin.d.ts +31 -0
- package/dist/modes/rpc/remote-origin.js +58 -0
- package/dist/modes/rpc/rpc-protocol-info-types.d.ts +8 -0
- package/dist/modes/rpc/rpc-question-types.d.ts +7 -0
- package/dist/modes/rpc/rpc-question-types.js +0 -3
- package/dist/modes/rpc/rpc-read-response-types.d.ts +2 -1
- package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
- package/dist/modes/rpc/rpc-session-state-types.d.ts +10 -0
- package/dist/modes/rpc/rpc-types.d.ts +1 -1
- package/dist/modes/rpc/runtime-factory-loopless.d.ts +57 -0
- package/dist/modes/rpc/runtime-factory-loopless.js +131 -0
- package/dist/modes/rpc/session-registry.js +12 -3
- package/dist/modes/rpc/session-worker-client.js +2 -0
- package/dist/modes/rpc/session-worker-protocol.d.ts +3 -0
- package/dist/modes/rpc/session-worker.js +2 -0
- package/docs/development.md +1 -1
- package/docs/engine-socket/fixtures/admission-routes/c-baseline.json +3 -3
- package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
- package/docs/engine-socket/fixtures/admission-routes/i-reset-stream.json +3 -3
- package/docs/engine-socket/fixtures/recovery-manifest/index.json +32 -0
- package/docs/engine-socket/fixtures/recovery-manifest/one-partial-family.json +118 -0
- package/docs/rpc.md +95 -3
- package/package.json +6 -6
- package/dist/bundle/chunks/anthropic-messages-WUPLDYD6.js +0 -10
- package/dist/bundle/chunks/chunk-7UC4W2T2.js +0 -2
- package/dist/bundle/chunks/chunk-O4GRBX4R.js +0 -3
- package/dist/bundle/chunks/chunk-R23WXN4L.js +0 -448
- package/dist/bundle/chunks/chunk-W5NLCRB3.js +0 -2
- package/dist/bundle/chunks/credential-accounts-OAK2E5O2.js +0 -2
- package/dist/bundle/chunks/host-command-WJIMRBGN.js +0 -2
- package/dist/bundle/chunks/interactive-mode-NPHFDPGH.js +0 -2
- package/dist/bundle/chunks/main-I6FJAFUP.js +0 -2
- package/dist/bundle/chunks/rotation-stream-ZDCNHIBE.js +0 -2
- package/dist/bundle/chunks/rpc-mode-GBBTN2WP.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{APP_NAME,CONFIG_DIR_NAME,agentDirLabel}from"./chunk-ISZ4EWIS.js";var CLI_TIPS=[{id:"print-mode",bindings:[],render:()=>`${APP_NAME} -p "question" answers without the TUI, and piped stdin is merged into the prompt.`},{id:"tool-flags",bindings:[],render:()=>"Limit a run's tools with -t read,bash, or drop a few with -xt write,edit."}];function stopChord(){return process.platform==="darwin"?"Control+Option+Command+Escape":"Ctrl+Alt+Shift+Escape"}var COMPUTER_TIPS=[{id:"computer.what-it-is",bindings:[],requiresCommand:"computer",render:()=>"Experimental: your agent can use native apps too: screenshots, windows, clicks and typing. Run /computer to see whether this machine is ready."},{id:"computer.stop-chord",bindings:[],requiresCommand:"computer",render:()=>`Press ${stopChord()} at any moment to stop computer input. It stays stopped until you run /computer resume; the agent cannot resume it.`},{id:"computer.background-input",bindings:[],requiresCommand:"computer",render:()=>"Computer use clicks and types into the target app in the background, so your frontmost app, keyboard focus and cursor stay where you left them."},{id:"computer.look-dont-touch",bindings:[],requiresCommand:"computer",render:()=>"Want the agent to look but not touch? Start with --permission computer:exec=deny: screenshots and accessibility reads still work, clicks and typing are refused."},{id:"computer.permissions",bindings:[],requiresCommand:"computer",render:()=>"On macOS, computer use needs Screen Recording and Accessibility for the app you launch from. /computer status shows which one is missing."}];var DAG_TIPS=[{id:"dag.one-keyword-mastery",bindings:[],requiresCommand:"dag",render:()=>'One keyword makes you a master of graph engineering: say "mass-ulw" and your work becomes a dependency graph that schedules itself.'},{id:"dag.what-it-is",bindings:[],requiresCommand:"dag",render:()=>'Trigger "mass-ulw" when some tasks must wait for others - describe the work, get a graph that runs in the right order.'},{id:"dag.parallel-waves",bindings:[],requiresCommand:"dag",render:()=>"A graph run executes in waves: everything with no pending dependency starts at once, the rest starts the moment it is unblocked."},{id:"dag.depends-on",bindings:[],requiresCommand:"dag",render:()=>"Say what needs what - review after implementation, docs after both - and the ordering is enforced for you."},{id:"dag.categories",bindings:[],requiresCommand:"dag",render:()=>"Each node in the graph picks its own worker category, so cheap steps stay cheap and hard steps get the strong model."},{id:"dag.status-view",bindings:[],requiresCommand:"dag",render:()=>"Use /dag to watch a run: which nodes finished, which are running, and which one failed."},{id:"dag.resume",bindings:[],requiresCommand:"dag",render:()=>"Graph runs are journaled - if the session dies mid-run it resumes later and never redoes the nodes that already finished."},{id:"dag.vs-parallel",bindings:[],requiresCommand:"dag",render:()=>"Fully independent jobs just need parallel subagents; reach for a graph when the ordering between them is the whole point."},{id:"dag.scale",bindings:[],requiresCommand:"dag",render:()=>"Stop hand-running steps in sequence. Describe the dependencies once and let a dozen agents fan out and rejoin on their own."}];var ETHOS_TIPS=[{id:"ethos.tools-transparent",bindings:[],render:()=>"Don't study our tools. A tool that needs studying is a tool that failed. We just ride shotgun while you keep doing your actual job."},{id:"ethos.spend-tokens",bindings:[],render:()=>"Stop hoarding tokens. Spend them like they buy your hours back, because they do."},{id:"ethos.deep-work",bindings:[],render:()=>"Using our tools means your work is already the deep, valuable kind. Keep your eyes on the essence of your craft. The rest is our problem now, and we're great at problems."},{id:"ethos.ulw-plan-sage",bindings:[],requiresCommand:"tasks",render:()=>"Try ulw-plan on fable-5.1 xhigh. A patient sage obsessed with the essence does the agonizing for you and fills in every blank you were pretending not to see."},{id:"ethos.ulw-loop-shallow",bindings:[],requiresCommand:"tasks",render:()=>"For days when deep thought sounds awful, run the ulw loop with gpt-6-sol fast/medium. Fair warning: shallow thinking sends invoices."},{id:"ethos.monitor-subscribe",bindings:[],render:()=>"Subscribe to a command's stdout and forget it. CI finishes, server boots, log line lands... you're mid-edit and the news finds *you*. No sleep loops, no polling, no re-reading context like a chump."},{id:"ethos.cache-budget",bindings:[],render:()=>"My harness knows the prompt cache's expiry to the second and never blocks past it. Cold re-read tax? *Refused on your behalf.* Other agents eat that cost, mine declines it."},{id:"ethos.cache-hit-rate",bindings:[],render:()=>"Live cache-hit rate in the footer, plus a running tab of misses, idle gaps, and model swaps. I can point at the exact moment cache broke and why. Watching tokens you never re-pay stack up? Smug doesn't cover it."},{id:"ethos.multimodal-vision",bindings:[],render:()=>`Drop a screenshot, a PDF, a crusty whiteboard photo... ${APP_NAME} actually sees it, reads it, reasons about it. Your agent has eyes now. *Yes, really.*`},{id:"ethos.oauth-multi-account",bindings:[],render:()=>`Hit a rate limit, switch accounts. Wrong org, switch again. ${APP_NAME} treats your Claude logins like a roster, not a single lifeline. *Env vars could never.*`},{id:"ethos.agent-sdk-foundation",bindings:[],render:()=>'Built on the official agent SDK, speaking the protocol natively. No reverse-engineered wrapper, no ToS gray zone, no "will I get banned for this" anxiety. *Sleep easy, ship loud.*'},{id:"ethos.tool-call-repair",bindings:[],render:()=>`${APP_NAME} catches malformed tool calls on the wire, fixes them, and salvages the turn - claude's sloppy invokes, kimi k3's leaked XTML channels, all of it. Other harnesses retry the whole thing and bill you for the privilege. *table stakes, honestly*`}];var INPUT_TIPS=[{id:"click-pending-question",bindings:[],render:()=>"Click a pending question's option to answer. Use the displayed selection-bypass modifier to select terminal text, or disable terminal.mouse in /settings."},{id:"queue-follow-up",bindings:["app.message.followUp"],render:keys=>`While the agent is working, use ${keys("app.message.followUp")} to queue a follow-up for after it finishes.`},{id:"steering-message",bindings:["tui.input.submit","app.message.followUp"],render:keys=>`Press ${keys("tui.input.submit")} while the agent works to steer it after the current tool batch; ${keys("app.message.followUp")} waits until all work is done.`},{id:"edit-queued-message",bindings:["app.message.dequeue"],render:keys=>`Use ${keys("app.message.dequeue")} to bring queued messages back for editing.`},{id:"interrupt-restores-queue",bindings:["app.interrupt"],render:keys=>`Press ${keys("app.interrupt")} to abort the current turn and restore queued messages to the editor.`},{id:"file-reference",bindings:[],render:()=>"Type @ in the editor to fuzzy-search project files and insert their paths."},{id:"path-completion",bindings:["tui.input.tab"],render:keys=>`Press ${keys("tui.input.tab")} to complete file paths while typing.`},{id:"shortcut-overlay",bindings:[],render:()=>"Type ? in an empty editor to pop up the full shortcut grid."},{id:"prompt-history",bindings:["app.history.search"],requiresCommand:"history",render:keys=>`Search prompt history across sessions with ${keys("app.history.search")}.`},{id:"external-editor",bindings:["app.editor.external"],render:keys=>`Open the current prompt in your external editor with ${keys("app.editor.external")}.`},{id:"expand-tool-output",bindings:["app.tools.expand"],render:keys=>`Collapse or expand tool output with ${keys("app.tools.expand")}.`},{id:"thinking-blocks",bindings:["app.thinking.toggle"],render:keys=>`Collapse or expand thinking blocks with ${keys("app.thinking.toggle")}.`},{id:"paste-image",bindings:["app.clipboard.pasteImage"],render:keys=>`Paste an image from the clipboard with ${keys("app.clipboard.pasteImage")}.`},{id:"copy-message",bindings:["app.message.copy"],render:keys=>`Copy the latest assistant message with ${keys("app.message.copy")}.`},{id:"input-newline",bindings:["tui.input.newLine"],render:keys=>`Insert a newline without sending with ${keys("tui.input.newLine")}.`},{id:"bash-prefixes",bindings:[],render:()=>"Prefix a prompt with ! to run bash, or !! to run bash without adding its output to model context."},{id:"drag-drop-files",bindings:[],render:()=>"Drag and drop files into the terminal to add their paths to your prompt."},{id:"answer-agent-question",bindings:[],render:()=>"When the agent asks you a question, pick options with digits or arrows, press Enter to advance, and use the final Submit tab for a comment or partial answers; anything unanswered is reported back as unanswered."},{id:"open-pending-question",bindings:["app.question.answer","app.question.next"],render:keys=>`Pending questions queue above the editor. An empty-composer digit selects an option; ${keys("app.question.answer")} opens the shown request and ${keys("app.question.next")} cycles requests. /answer lists them.`}];var MEMORY_TIPS=[{id:"memory.persistent",bindings:[],requiresCommand:"memory",render:()=>`${APP_NAME} remembers across sessions. Close the terminal, come back tomorrow, and the context is still there.`},{id:"memory.remember-command",bindings:[],requiresCommand:"remember",render:()=>"Use /remember to save something you want kept - a preference, a decision, a fact worth reusing."},{id:"memory.just-tell-it",bindings:[],requiresCommand:"remember",render:()=>'You can also just say it: "remember that we deploy on Fridays" is enough. No syntax, no file to open.'},{id:"memory.search-command",bindings:[],requiresCommand:"search",render:()=>"Use /search to look through everything remembered so far, in plain words."},{id:"memory.memory-command",bindings:[],requiresCommand:"memory",render:()=>"Use /memory to see what is currently remembered about you and this project."},{id:"memory.init-command",bindings:[],requiresCommand:"init",render:()=>"Use /init to start memory for a new project, so it learns this codebase from the first session."},{id:"memory.people-command",bindings:[],requiresCommand:"people",render:()=>"Use /people to keep notes on teammates - who owns what, who to ask, what they prefer."},{id:"memory.reflect-command",bindings:[],requiresCommand:"reflect",render:()=>"Use /reflect to have the session reviewed now and the parts worth keeping written down."},{id:"memory.dream-command",bindings:[],requiresCommand:"dream",render:()=>"Memory tidies itself in the background between turns - /dream shows that work and lets you start it yourself."},{id:"memory.sleeptime-command",bindings:[],requiresCommand:"sleeptime",render:()=>"Use /sleeptime to decide how often memory reorganizes itself while you are not looking."},{id:"memory.memfs-command",bindings:[],requiresCommand:"memfs",render:()=>"Memory is plain files you own - browse them with /memfs and edit anything that looks wrong."},{id:"memory.repository-command",bindings:[],requiresCommand:"memory-repository",render:()=>"Every memory change is a git commit - use /memory-repository to see the history and undo a bad one."},{id:"memory.doctor-command",bindings:[],requiresCommand:"doctor",render:()=>"Use /doctor when memory feels off; it checks the setup and tells you what to fix."},{id:"memory.facts-command",bindings:[],requiresCommand:"facts",render:()=>"Use /facts to see the individual things learned about you, and drop the ones that no longer hold."},{id:"memory.recompile-command",bindings:[],requiresCommand:"recompile",render:()=>"Edited memory files by hand? Run /recompile so this session picks the changes up right away."},{id:"memory.aha-moment",bindings:[],requiresCommand:"memory",render:()=>"Memory speaks up on its own: when something remembered would change the next step, an Aha moment! line surfaces it mid-task. Silence means nothing relevant was found."},{id:"memory.stop-repeating",bindings:[],requiresCommand:"memory",render:()=>"Explain your setup once. Memory means you stop re-explaining it at the start of every session."}];var MODEL_TIPS=[{id:"thinking-level",bindings:["app.thinking.cycle"],render:keys=>`Use /thinking <level> to set the thinking level, /thinking to pick one, or ${keys("app.thinking.cycle")} to cycle through them.`},{id:"efforts-command",bindings:[],requiresCommand:"efforts",render:()=>"Use /efforts <level> to set the reasoning effort for the current model; /efforts alone lists the levels it supports."},{id:"favorite-model-rotation",bindings:["app.model.cycleForward","app.model.cycleBackward"],render:keys=>`Rotate through favorite models with ${keys("app.model.cycleForward")}; go backward with ${keys("app.model.cycleBackward")}.`},{id:"model-selector-favorites",bindings:["app.model.select","app.models.toggleFavorite"],render:keys=>`Open the model selector with ${keys("app.model.select")}, then use ${keys("app.models.toggleFavorite")} to toggle the highlighted favorite.`},{id:"model-command-search",bindings:[],render:()=>"Use /model to open the selector, or /model <pattern> to jump straight to a matching model."},{id:"model-cycling-scope",bindings:["app.model.cycleForward"],render:keys=>`Start ${APP_NAME} with --models "anthropic/*,gpt-5*" to limit which models ${keys("app.model.cycleForward")} cycles through.`},{id:"thinking-budgets",bindings:[],render:()=>"Set thinkingBudgets in settings.json to choose the token budget behind each thinking level."},{id:"prompt-preset",bindings:[],render:()=>"Set promptPreset in settings.json when a model does not auto-detect the system prompt you want."},{id:"provider-login",bindings:[],render:()=>"Use /login to add a subscription or API-key provider, and /logout to remove stored credentials."},{id:"fallback-chains-setting",bindings:[],render:()=>"retry.fallbackChains in settings.json maps a model to ordered fallbacks, so a failed turn retries on the next one."},{id:"fallback-command",bindings:[],requiresCommand:"fallback",render:()=>"Use /fallback to inspect and manage the retry fallback chain for the current model."}];var SESSION_TIPS=[{id:"favorite-models-command",bindings:[],render:()=>"Use /favorite-models to choose and reorder the models in your rotation."},{id:"tree-command",bindings:[],render:()=>"Use /tree to revisit earlier points and switch between session branches."},{id:"fork-command",bindings:[],render:()=>"Use /fork to create a separate session from an earlier user message."},{id:"clone-session",bindings:[],render:()=>"Use /clone to duplicate the current branch into its own session before trying something risky."},{id:"continue-session",bindings:[],render:()=>`Use /resume or /sessions to reopen a past session; from the shell, ${APP_NAME} -r opens the same picker and ${APP_NAME} -c continues the most recent one.`},{id:"session-name",bindings:[],render:()=>"Use /rename [name] to label a session so it is easy to spot in the footer and in /resume."},{id:"session-info",bindings:[],render:()=>"Use /session to see the session file, id, message count, tokens, and cost."},{id:"export-share",bindings:[],render:()=>"Use /export to write the session to HTML or JSONL, or /share to upload it as a private gist link."},{id:"compact-command",bindings:[],render:()=>"Use /compact to compact context now, or /compact <prompt> to tell the summarizer what to keep."},{id:"auto-compaction",bindings:[],render:()=>"Auto-compaction is on by default - the (auto) marker in the footer shows it; tune it with compaction.* in settings.json."}];var SETTINGS_TIPS=[{id:"settings-locations",bindings:[],render:()=>`Use /settings for common options; the rest live in settings.json, with ${CONFIG_DIR_NAME}/settings.json overriding per project.`},{id:"permission-preset",bindings:[],render:()=>'Set permissionPreset to "workspace", "read-only", or "ask" to decide which tool calls need your approval.'},{id:"packages-setting",bindings:[],render:()=>"The packages setting loads skills, extensions, prompts, and themes from an npm or git package."},{id:"custom-themes",bindings:[],render:()=>`Switch themes from /settings, and drop custom theme files in ${agentDirLabel()}/themes.`},{id:"reload-resources",bindings:[],render:()=>"Use /reload to re-read keybindings, extensions, skills, prompts, themes, and context files without restarting."},{id:"project-trust",bindings:[],render:()=>"Use /trust to save a trust decision so this project's settings, skills, and extensions load next time."},{id:"tips-toggle",bindings:[],render:()=>'Set "tips": false in settings.json to stop showing these tips.'}];var SUBAGENT_TIPS=[{id:"workflow-skills.plan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw plan" to get an explored, decision-complete plan under .omo/plans/.'},{id:"workflow-skills.start-work",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "$start-work <plan-name>" to execute a plan end-to-end in a fresh session.'},{id:"workflow-skills.ultrawork",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw" or "ulw loop" for a long, evidence-driven autonomous run in ultrawork mode.'},{id:"workflow-skills.research",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw-research" for a saturating, citation-backed investigation across the codebase, docs, and the web.'},{id:"workflow-skills.hyperplan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "hyperplan" to have adversarial reviewers attack a plan before you commit to it.'},{id:"workflow-skills.review",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "review work" to run parallel goal, quality, security, and hands-on QA reviews.'},{id:"workflow-skills.init-deep",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "/init-deep" to map a project and generate a hierarchical AGENTS.md knowledge base.'},{id:"workflow-skills.debugging",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "debug this" for parallel hypotheses, a failing regression test, a minimal fix, and real-surface QA.'},{id:"workflow-skills.refactor",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "refactor" for codebase-aware cleanup that pins behavior before changing structure.'},{id:"workflow-skills.remove-ai-slops",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "remove AI slop" to lock behavior first, then strip generated-code smells without drive-by rewrites.'},{id:"workflow-skills.visual-qa",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "visual QA" to capture browser or xterm evidence and review web or terminal interfaces.'},{id:"workflow-skills.report-bug",bindings:[],requiresCommand:"tasks",render:()=>'Hit a bug? Say "report a bug" - the report-bug skill finds the session, records the exact provider and model, routes it to the right repository, and files an evidence-backed issue only after you confirm.'},{id:"subagent-categories",bindings:[],requiresCommand:"tasks",render:()=>"Delegate by category - quick, deep, ultrabrain, architect, artistry, git, writing - each runs on its own model."},{id:"subagent-commands",bindings:[],requiresCommand:"tasks",render:()=>"Use /tasks to see this session's background subagents, and /task-kill to stop one."},{id:"subagent-config",bindings:[],requiresCommand:"tasks",render:()=>"~/.omo/omo.jsonc maps every subagent category to its model, reasoning effort, and fallback chain."},{id:"subagent-team",bindings:[],requiresCommand:"tasks",render:()=>"Ask for a team when one task needs several agents at once: members share a tasklist and report back to you."}];var WORKSPACE_TIPS=[{id:"help-command",bindings:[],requiresCommand:"help",render:()=>"Use /help to see available commands and guidance."},{id:"keybindings-command",bindings:[],render:()=>"Use /keybindings to review and customize keyboard shortcuts."},{id:"agents-md-context",bindings:[],render:()=>`${APP_NAME} loads AGENTS.md from your home directory, every parent folder, and the current folder as project instructions.`},{id:"skills-and-prompts",bindings:[],render:()=>`Skills run as /skill:name, and prompt templates in ${agentDirLabel()}/prompts expand as /templatename.`},{id:"files-command",bindings:[],requiresCommand:"files",render:()=>"Use /files to list every file this session read, wrote, or edited."},{id:"diff-command",bindings:[],requiresCommand:"diff",render:()=>"Use /diff to review this session's git changes and open them in a diff view."},{id:"todo-command",bindings:[],requiresCommand:"todo",render:()=>"Use /todo to show or edit the todo list without leaving the session."},{id:"goal-command",bindings:[],requiresCommand:"goal",render:()=>`Use /goal to set a persistent goal ${APP_NAME} keeps pursuing, then pause, resume, or clear it.`},{id:"btw-command",bindings:[],requiresCommand:"btw",render:()=>"Use /btw to ask a side question in a parallel session without disturbing this one."},{id:"lookat-command",bindings:[],requiresCommand:"lookat",render:()=>"Use /lookat to manage the vision-model chain the look_at tool uses for images and screenshots."},{id:"mcp-command",bindings:[],requiresCommand:"mcp",render:()=>"Use /mcp to inspect and manage the MCP servers wired into this session."},{id:"rules-command",bindings:[],requiresCommand:"rules",render:()=>"Use /rules to see which rules are loaded, and /reload-rules to re-read them mid-session."},{id:"hooks-command",bindings:[],requiresCommand:"hooks",render:()=>"Use /hooks to list loaded hook sources and their diagnostics."},{id:"websearch-command",bindings:[],requiresCommand:"websearch",render:()=>"Use /websearch to check which web-search provider is currently active."}];var TIP_DEFINITIONS=[...MODEL_TIPS,...INPUT_TIPS,...SESSION_TIPS,...WORKSPACE_TIPS,...SETTINGS_TIPS,...CLI_TIPS,...SUBAGENT_TIPS,...MEMORY_TIPS,...DAG_TIPS,...COMPUTER_TIPS,...ETHOS_TIPS];export{TIP_DEFINITIONS};
|
|
2
|
+
import{APP_NAME,CONFIG_DIR_NAME,agentDirLabel}from"./chunk-SODMQEHO.js";var CLI_TIPS=[{id:"print-mode",bindings:[],render:()=>`${APP_NAME} -p "question" answers without the TUI, and piped stdin is merged into the prompt.`},{id:"tool-flags",bindings:[],render:()=>"Limit a run's tools with -t read,bash, or drop a few with -xt write,edit."}];function stopChord(){return process.platform==="darwin"?"Control+Option+Command+Escape":"Ctrl+Alt+Shift+Escape"}var COMPUTER_TIPS=[{id:"computer.what-it-is",bindings:[],requiresCommand:"computer",render:()=>"Experimental: your agent can use native apps too: screenshots, windows, clicks and typing. Run /computer to see whether this machine is ready."},{id:"computer.stop-chord",bindings:[],requiresCommand:"computer",render:()=>`Press ${stopChord()} at any moment to stop computer input. It stays stopped until you run /computer resume; the agent cannot resume it.`},{id:"computer.background-input",bindings:[],requiresCommand:"computer",render:()=>"Computer use clicks and types into the target app in the background, so your frontmost app, keyboard focus and cursor stay where you left them."},{id:"computer.look-dont-touch",bindings:[],requiresCommand:"computer",render:()=>"Want the agent to look but not touch? Start with --permission computer:exec=deny: screenshots and accessibility reads still work, clicks and typing are refused."},{id:"computer.permissions",bindings:[],requiresCommand:"computer",render:()=>"On macOS, computer use needs Screen Recording and Accessibility for the app you launch from. /computer status shows which one is missing."}];var DAG_TIPS=[{id:"dag.one-keyword-mastery",bindings:[],requiresCommand:"dag",render:()=>'One keyword makes you a master of graph engineering: say "mass-ulw" and your work becomes a dependency graph that schedules itself.'},{id:"dag.what-it-is",bindings:[],requiresCommand:"dag",render:()=>'Trigger "mass-ulw" when some tasks must wait for others - describe the work, get a graph that runs in the right order.'},{id:"dag.parallel-waves",bindings:[],requiresCommand:"dag",render:()=>"A graph run executes in waves: everything with no pending dependency starts at once, the rest starts the moment it is unblocked."},{id:"dag.depends-on",bindings:[],requiresCommand:"dag",render:()=>"Say what needs what - review after implementation, docs after both - and the ordering is enforced for you."},{id:"dag.categories",bindings:[],requiresCommand:"dag",render:()=>"Each node in the graph picks its own worker category, so cheap steps stay cheap and hard steps get the strong model."},{id:"dag.status-view",bindings:[],requiresCommand:"dag",render:()=>"Use /dag to watch a run: which nodes finished, which are running, and which one failed."},{id:"dag.resume",bindings:[],requiresCommand:"dag",render:()=>"Graph runs are journaled - if the session dies mid-run it resumes later and never redoes the nodes that already finished."},{id:"dag.vs-parallel",bindings:[],requiresCommand:"dag",render:()=>"Fully independent jobs just need parallel subagents; reach for a graph when the ordering between them is the whole point."},{id:"dag.scale",bindings:[],requiresCommand:"dag",render:()=>"Stop hand-running steps in sequence. Describe the dependencies once and let a dozen agents fan out and rejoin on their own."}];var ETHOS_TIPS=[{id:"ethos.tools-transparent",bindings:[],render:()=>"Don't study our tools. A tool that needs studying is a tool that failed. We just ride shotgun while you keep doing your actual job."},{id:"ethos.spend-tokens",bindings:[],render:()=>"Stop hoarding tokens. Spend them like they buy your hours back, because they do."},{id:"ethos.deep-work",bindings:[],render:()=>"Using our tools means your work is already the deep, valuable kind. Keep your eyes on the essence of your craft. The rest is our problem now, and we're great at problems."},{id:"ethos.ulw-plan-sage",bindings:[],requiresCommand:"tasks",render:()=>"Try ulw-plan on fable-5.1 xhigh. A patient sage obsessed with the essence does the agonizing for you and fills in every blank you were pretending not to see."},{id:"ethos.ulw-loop-shallow",bindings:[],requiresCommand:"tasks",render:()=>"For days when deep thought sounds awful, run the ulw loop with gpt-6-sol fast/medium. Fair warning: shallow thinking sends invoices."},{id:"ethos.monitor-subscribe",bindings:[],render:()=>"Subscribe to a command's stdout and forget it. CI finishes, server boots, log line lands... you're mid-edit and the news finds *you*. No sleep loops, no polling, no re-reading context like a chump."},{id:"ethos.cache-budget",bindings:[],render:()=>"My harness knows the prompt cache's expiry to the second and never blocks past it. Cold re-read tax? *Refused on your behalf.* Other agents eat that cost, mine declines it."},{id:"ethos.cache-hit-rate",bindings:[],render:()=>"Live cache-hit rate in the footer, plus a running tab of misses, idle gaps, and model swaps. I can point at the exact moment cache broke and why. Watching tokens you never re-pay stack up? Smug doesn't cover it."},{id:"ethos.multimodal-vision",bindings:[],render:()=>`Drop a screenshot, a PDF, a crusty whiteboard photo... ${APP_NAME} actually sees it, reads it, reasons about it. Your agent has eyes now. *Yes, really.*`},{id:"ethos.oauth-multi-account",bindings:[],render:()=>`Hit a rate limit, switch accounts. Wrong org, switch again. ${APP_NAME} treats your Claude logins like a roster, not a single lifeline. *Env vars could never.*`},{id:"ethos.agent-sdk-foundation",bindings:[],render:()=>'Built on the official agent SDK, speaking the protocol natively. No reverse-engineered wrapper, no ToS gray zone, no "will I get banned for this" anxiety. *Sleep easy, ship loud.*'},{id:"ethos.tool-call-repair",bindings:[],render:()=>`${APP_NAME} catches malformed tool calls on the wire, fixes them, and salvages the turn - claude's sloppy invokes, kimi k3's leaked XTML channels, all of it. Other harnesses retry the whole thing and bill you for the privilege. *table stakes, honestly*`}];var INPUT_TIPS=[{id:"click-pending-question",bindings:[],render:()=>"Click a pending question's option to answer. Use the displayed selection-bypass modifier to select terminal text, or disable terminal.mouse in /settings."},{id:"queue-follow-up",bindings:["app.message.followUp"],render:keys=>`While the agent is working, use ${keys("app.message.followUp")} to queue a follow-up for after it finishes.`},{id:"steering-message",bindings:["tui.input.submit","app.message.followUp"],render:keys=>`Press ${keys("tui.input.submit")} while the agent works to steer it after the current tool batch; ${keys("app.message.followUp")} waits until all work is done.`},{id:"edit-queued-message",bindings:["app.message.dequeue"],render:keys=>`Use ${keys("app.message.dequeue")} to bring queued messages back for editing.`},{id:"interrupt-restores-queue",bindings:["app.interrupt"],render:keys=>`Press ${keys("app.interrupt")} to abort the current turn and restore queued messages to the editor.`},{id:"file-reference",bindings:[],render:()=>"Type @ in the editor to fuzzy-search project files and insert their paths."},{id:"path-completion",bindings:["tui.input.tab"],render:keys=>`Press ${keys("tui.input.tab")} to complete file paths while typing.`},{id:"shortcut-overlay",bindings:[],render:()=>"Type ? in an empty editor to pop up the full shortcut grid."},{id:"prompt-history",bindings:["app.history.search"],requiresCommand:"history",render:keys=>`Search prompt history across sessions with ${keys("app.history.search")}.`},{id:"external-editor",bindings:["app.editor.external"],render:keys=>`Open the current prompt in your external editor with ${keys("app.editor.external")}.`},{id:"expand-tool-output",bindings:["app.tools.expand"],render:keys=>`Collapse or expand tool output with ${keys("app.tools.expand")}.`},{id:"thinking-blocks",bindings:["app.thinking.toggle"],render:keys=>`Collapse or expand thinking blocks with ${keys("app.thinking.toggle")}.`},{id:"paste-image",bindings:["app.clipboard.pasteImage"],render:keys=>`Paste an image from the clipboard with ${keys("app.clipboard.pasteImage")}.`},{id:"copy-message",bindings:["app.message.copy"],render:keys=>`Copy the latest assistant message with ${keys("app.message.copy")}.`},{id:"input-newline",bindings:["tui.input.newLine"],render:keys=>`Insert a newline without sending with ${keys("tui.input.newLine")}.`},{id:"bash-prefixes",bindings:[],render:()=>"Prefix a prompt with ! to run bash, or !! to run bash without adding its output to model context."},{id:"drag-drop-files",bindings:[],render:()=>"Drag and drop files into the terminal to add their paths to your prompt."},{id:"answer-agent-question",bindings:[],render:()=>"When the agent asks you a question, pick options with digits or arrows, press Enter to advance, and use the final Submit tab for a comment or partial answers; anything unanswered is reported back as unanswered."},{id:"open-pending-question",bindings:["app.question.answer","app.question.next"],render:keys=>`Pending questions queue above the editor. An empty-composer digit selects an option; ${keys("app.question.answer")} opens the shown request and ${keys("app.question.next")} cycles requests. /answer lists them.`}];var MEMORY_TIPS=[{id:"memory.persistent",bindings:[],requiresCommand:"memory",render:()=>`${APP_NAME} remembers across sessions. Close the terminal, come back tomorrow, and the context is still there.`},{id:"memory.remember-command",bindings:[],requiresCommand:"remember",render:()=>"Use /remember to save something you want kept - a preference, a decision, a fact worth reusing."},{id:"memory.just-tell-it",bindings:[],requiresCommand:"remember",render:()=>'You can also just say it: "remember that we deploy on Fridays" is enough. No syntax, no file to open.'},{id:"memory.search-command",bindings:[],requiresCommand:"search",render:()=>"Use /search to look through everything remembered so far, in plain words."},{id:"memory.memory-command",bindings:[],requiresCommand:"memory",render:()=>"Use /memory to see what is currently remembered about you and this project."},{id:"memory.init-command",bindings:[],requiresCommand:"init",render:()=>"Use /init to start memory for a new project, so it learns this codebase from the first session."},{id:"memory.people-command",bindings:[],requiresCommand:"people",render:()=>"Use /people to keep notes on teammates - who owns what, who to ask, what they prefer."},{id:"memory.reflect-command",bindings:[],requiresCommand:"reflect",render:()=>"Use /reflect to have the session reviewed now and the parts worth keeping written down."},{id:"memory.dream-command",bindings:[],requiresCommand:"dream",render:()=>"Memory tidies itself in the background between turns - /dream shows that work and lets you start it yourself."},{id:"memory.sleeptime-command",bindings:[],requiresCommand:"sleeptime",render:()=>"Use /sleeptime to decide how often memory reorganizes itself while you are not looking."},{id:"memory.memfs-command",bindings:[],requiresCommand:"memfs",render:()=>"Memory is plain files you own - browse them with /memfs and edit anything that looks wrong."},{id:"memory.repository-command",bindings:[],requiresCommand:"memory-repository",render:()=>"Every memory change is a git commit - use /memory-repository to see the history and undo a bad one."},{id:"memory.doctor-command",bindings:[],requiresCommand:"doctor",render:()=>"Use /doctor when memory feels off; it checks the setup and tells you what to fix."},{id:"memory.facts-command",bindings:[],requiresCommand:"facts",render:()=>"Use /facts to see the individual things learned about you, and drop the ones that no longer hold."},{id:"memory.recompile-command",bindings:[],requiresCommand:"recompile",render:()=>"Edited memory files by hand? Run /recompile so this session picks the changes up right away."},{id:"memory.aha-moment",bindings:[],requiresCommand:"memory",render:()=>"Memory speaks up on its own: when something remembered would change the next step, an Aha moment! line surfaces it mid-task. Silence means nothing relevant was found."},{id:"memory.stop-repeating",bindings:[],requiresCommand:"memory",render:()=>"Explain your setup once. Memory means you stop re-explaining it at the start of every session."}];var MODEL_TIPS=[{id:"thinking-level",bindings:["app.thinking.cycle"],render:keys=>`Use /thinking <level> to set the thinking level, /thinking to pick one, or ${keys("app.thinking.cycle")} to cycle through them.`},{id:"efforts-command",bindings:[],requiresCommand:"efforts",render:()=>"Use /efforts <level> to set the reasoning effort for the current model; /efforts alone lists the levels it supports."},{id:"favorite-model-rotation",bindings:["app.model.cycleForward","app.model.cycleBackward"],render:keys=>`Rotate through favorite models with ${keys("app.model.cycleForward")}; go backward with ${keys("app.model.cycleBackward")}.`},{id:"model-selector-favorites",bindings:["app.model.select","app.models.toggleFavorite"],render:keys=>`Open the model selector with ${keys("app.model.select")}, then use ${keys("app.models.toggleFavorite")} to toggle the highlighted favorite.`},{id:"model-command-search",bindings:[],render:()=>"Use /model to open the selector, or /model <pattern> to jump straight to a matching model."},{id:"model-cycling-scope",bindings:["app.model.cycleForward"],render:keys=>`Start ${APP_NAME} with --models "anthropic/*,gpt-5*" to limit which models ${keys("app.model.cycleForward")} cycles through.`},{id:"thinking-budgets",bindings:[],render:()=>"Set thinkingBudgets in settings.json to choose the token budget behind each thinking level."},{id:"prompt-preset",bindings:[],render:()=>"Set promptPreset in settings.json when a model does not auto-detect the system prompt you want."},{id:"provider-login",bindings:[],render:()=>"Use /login to add a subscription or API-key provider, and /logout to remove stored credentials."},{id:"fallback-chains-setting",bindings:[],render:()=>"retry.fallbackChains in settings.json maps a model to ordered fallbacks, so a failed turn retries on the next one."},{id:"fallback-command",bindings:[],requiresCommand:"fallback",render:()=>"Use /fallback to inspect and manage the retry fallback chain for the current model."}];var SESSION_TIPS=[{id:"favorite-models-command",bindings:[],render:()=>"Use /favorite-models to choose and reorder the models in your rotation."},{id:"tree-command",bindings:[],render:()=>"Use /tree to revisit earlier points and switch between session branches."},{id:"fork-command",bindings:[],render:()=>"Use /fork to create a separate session from an earlier user message."},{id:"clone-session",bindings:[],render:()=>"Use /clone to duplicate the current branch into its own session before trying something risky."},{id:"continue-session",bindings:[],render:()=>`Use /resume or /sessions to reopen a past session; from the shell, ${APP_NAME} -r opens the same picker and ${APP_NAME} -c continues the most recent one.`},{id:"session-name",bindings:[],render:()=>"Use /rename [name] to label a session so it is easy to spot in the footer and in /resume."},{id:"session-info",bindings:[],render:()=>"Use /session to see the session file, id, message count, tokens, and cost."},{id:"export-share",bindings:[],render:()=>"Use /export to write the session to HTML or JSONL, or /share to upload it as a private gist link."},{id:"compact-command",bindings:[],render:()=>"Use /compact to compact context now, or /compact <prompt> to tell the summarizer what to keep."},{id:"auto-compaction",bindings:[],render:()=>"Auto-compaction is on by default - the (auto) marker in the footer shows it; tune it with compaction.* in settings.json."}];var SETTINGS_TIPS=[{id:"settings-locations",bindings:[],render:()=>`Use /settings for common options; the rest live in settings.json, with ${CONFIG_DIR_NAME}/settings.json overriding per project.`},{id:"permission-preset",bindings:[],render:()=>'Set permissionPreset to "workspace", "read-only", or "ask" to decide which tool calls need your approval.'},{id:"packages-setting",bindings:[],render:()=>"The packages setting loads skills, extensions, prompts, and themes from an npm or git package."},{id:"custom-themes",bindings:[],render:()=>`Switch themes from /settings, and drop custom theme files in ${agentDirLabel()}/themes.`},{id:"reload-resources",bindings:[],render:()=>"Use /reload to re-read keybindings, extensions, skills, prompts, themes, and context files without restarting."},{id:"project-trust",bindings:[],render:()=>"Use /trust to save a trust decision so this project's settings, skills, and extensions load next time."},{id:"tips-toggle",bindings:[],render:()=>'Set "tips": false in settings.json to stop showing these tips.'}];var SUBAGENT_TIPS=[{id:"workflow-skills.plan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw plan" to get an explored, decision-complete plan under .omo/plans/.'},{id:"workflow-skills.start-work",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "$start-work <plan-name>" to execute a plan end-to-end in a fresh session.'},{id:"workflow-skills.ultrawork",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw" or "ulw loop" for a long, evidence-driven autonomous run in ultrawork mode.'},{id:"workflow-skills.research",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "ulw-research" for a saturating, citation-backed investigation across the codebase, docs, and the web.'},{id:"workflow-skills.hyperplan",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "hyperplan" to have adversarial reviewers attack a plan before you commit to it.'},{id:"workflow-skills.review",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "review work" to run parallel goal, quality, security, and hands-on QA reviews.'},{id:"workflow-skills.init-deep",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "/init-deep" to map a project and generate a hierarchical AGENTS.md knowledge base.'},{id:"workflow-skills.debugging",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "debug this" for parallel hypotheses, a failing regression test, a minimal fix, and real-surface QA.'},{id:"workflow-skills.refactor",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "refactor" for codebase-aware cleanup that pins behavior before changing structure.'},{id:"workflow-skills.remove-ai-slops",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "remove AI slop" to lock behavior first, then strip generated-code smells without drive-by rewrites.'},{id:"workflow-skills.visual-qa",bindings:[],requiresCommand:"tasks",render:()=>'Trigger "visual QA" to capture browser or xterm evidence and review web or terminal interfaces.'},{id:"workflow-skills.report-bug",bindings:[],requiresCommand:"tasks",render:()=>'Hit a bug? Say "report a bug" - the report-bug skill finds the session, records the exact provider and model, routes it to the right repository, and files an evidence-backed issue only after you confirm.'},{id:"subagent-categories",bindings:[],requiresCommand:"tasks",render:()=>"Delegate by category - quick, deep, ultrabrain, architect, artistry, git, writing - each runs on its own model."},{id:"subagent-commands",bindings:[],requiresCommand:"tasks",render:()=>"Use /tasks to see this session's background subagents, and /task-kill to stop one."},{id:"subagent-config",bindings:[],requiresCommand:"tasks",render:()=>"~/.omo/omo.jsonc maps every subagent category to its model, reasoning effort, and fallback chain."},{id:"subagent-team",bindings:[],requiresCommand:"tasks",render:()=>"Ask for a team when one task needs several agents at once: members share a tasklist and report back to you."}];var WORKSPACE_TIPS=[{id:"help-command",bindings:[],requiresCommand:"help",render:()=>"Use /help to see available commands and guidance."},{id:"keybindings-command",bindings:[],render:()=>"Use /keybindings to review and customize keyboard shortcuts."},{id:"agents-md-context",bindings:[],render:()=>`${APP_NAME} loads AGENTS.md from your home directory, every parent folder, and the current folder as project instructions.`},{id:"skills-and-prompts",bindings:[],render:()=>`Skills run as /skill:name, and prompt templates in ${agentDirLabel()}/prompts expand as /templatename.`},{id:"files-command",bindings:[],requiresCommand:"files",render:()=>"Use /files to list every file this session read, wrote, or edited."},{id:"diff-command",bindings:[],requiresCommand:"diff",render:()=>"Use /diff to review this session's git changes and open them in a diff view."},{id:"todo-command",bindings:[],requiresCommand:"todo",render:()=>"Use /todo to show or edit the todo list without leaving the session."},{id:"goal-command",bindings:[],requiresCommand:"goal",render:()=>`Use /goal to set a persistent goal ${APP_NAME} keeps pursuing, then pause, resume, or clear it.`},{id:"btw-command",bindings:[],requiresCommand:"btw",render:()=>"Use /btw to ask a side question in a parallel session without disturbing this one."},{id:"lookat-command",bindings:[],requiresCommand:"lookat",render:()=>"Use /lookat to manage the vision-model chain the look_at tool uses for images and screenshots."},{id:"mcp-command",bindings:[],requiresCommand:"mcp",render:()=>"Use /mcp to inspect and manage the MCP servers wired into this session."},{id:"rules-command",bindings:[],requiresCommand:"rules",render:()=>"Use /rules to see which rules are loaded, and /reload-rules to re-read them mid-session."},{id:"hooks-command",bindings:[],requiresCommand:"hooks",render:()=>"Use /hooks to list loaded hook sources and their diagnostics."},{id:"websearch-command",bindings:[],requiresCommand:"websearch",render:()=>"Use /websearch to check which web-search provider is currently active."}];var TIP_DEFINITIONS=[...MODEL_TIPS,...INPUT_TIPS,...SESSION_TIPS,...WORKSPACE_TIPS,...SETTINGS_TIPS,...CLI_TIPS,...SUBAGENT_TIPS,...MEMORY_TIPS,...DAG_TIPS,...COMPUTER_TIPS,...ETHOS_TIPS];export{TIP_DEFINITIONS};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{normalizeProviderError}from"./chunk-AC72EWI5.js";import{formatProviderRequestId}from"./chunk-
|
|
2
|
+
import{normalizeProviderError}from"./chunk-AC72EWI5.js";import{formatProviderRequestId}from"./chunk-AVP6DDBF.js";import{appendAssistantMessageDiagnostic}from"./chunk-5CSZPC55.js";var GITHUB_COPILOT_TOOL_LIMIT=128,GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC="github_copilot_tool_limit";function isRecord(value){return typeof value=="object"&&value!==null}function selectedToolName(toolChoice){if(isRecord(toolChoice)){if(toolChoice.type==="function")return isRecord(toolChoice.function)&&typeof toolChoice.function.name=="string"?toolChoice.function.name:typeof toolChoice.name=="string"?toolChoice.name:void 0;if(!(toolChoice.type!=="custom"&&toolChoice.type!=="tool"))return typeof toolChoice.name=="string"?toolChoice.name:void 0}}function toolName(tool){if(isRecord(tool))return tool.type==="function"&&isRecord(tool.function)&&typeof tool.function.name=="string"?tool.function.name:typeof tool.name=="string"?tool.name:void 0}function limitGitHubCopilotTools(provider,tools,toolChoice,priorityNames){if(provider!=="github-copilot"||tools===void 0||tools.length<=GITHUB_COPILOT_TOOL_LIMIT)return{tools,omittedCount:0};let forcedName=selectedToolName(toolChoice);if(priorityNames!==void 0)return limitByPriority(tools,forcedName,priorityNames);let forcedIndex=forcedName===void 0?-1:tools.findIndex(tool=>toolName(tool)===forcedName);if(forcedIndex>=GITHUB_COPILOT_TOOL_LIMIT){let forcedTool=tools[forcedIndex];if(forcedTool!==void 0)return{tools:[...tools.slice(0,GITHUB_COPILOT_TOOL_LIMIT-1),forcedTool],omittedCount:tools.length-GITHUB_COPILOT_TOOL_LIMIT}}return{tools:tools.slice(0,GITHUB_COPILOT_TOOL_LIMIT),omittedCount:tools.length-GITHUB_COPILOT_TOOL_LIMIT}}function limitByPriority(tools,forcedName,priorityNames){let rank=new Map(priorityNames.map((name,index)=>[name,index])),rankOf=(tool,index)=>{let name=toolName(tool);return name!==void 0&&name===forcedName?-1:rank.get(name??"")??priorityNames.length+index},kept=new Set(tools.map((tool,index)=>({index,rank:rankOf(tool,index)})).sort((a,b)=>a.rank-b.rank).slice(0,GITHUB_COPILOT_TOOL_LIMIT).map(entry=>entry.index));return{tools:tools.filter((_,index)=>kept.has(index)),omittedCount:tools.length-GITHUB_COPILOT_TOOL_LIMIT}}function recordGitHubCopilotToolLimit(message,omittedCount){omittedCount===0||message.diagnostics?.some(diagnostic=>diagnostic.type===GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC)||appendAssistantMessageDiagnostic(message,{type:GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC,timestamp:Date.now(),details:{limit:GITHUB_COPILOT_TOOL_LIMIT,omittedCount,message:`GitHub Copilot accepts at most ${GITHUB_COPILOT_TOOL_LIMIT} tools on endpoints without tool search; senpi omitted ${omittedCount} excess tool definition${omittedCount===1?"":"s"}.`}})}function formatGitHubCopilotToolLimitError(message,errorMessage){let toolLimitApplied=message.diagnostics?.some(diagnostic=>diagnostic.type===GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC);return message.provider!=="github-copilot"||!toolLimitApplied||message.providerDiagnostic?.httpStatus!==400||!/400 Bad Request$/i.test(errorMessage)?errorMessage:`GitHub Copilot rejected the request after senpi limited its tool list to ${GITHUB_COPILOT_TOOL_LIMIT}. The endpoint may enforce a lower limit or count additional hosted tools. (${errorMessage})`}var QUOTA_CODES=new Set(["quota_exceeded","free_quota_exceeded","overage_limit_reached","billing_not_configured","additional_spend_limit_reached"]);function headerValue(headers,name){if(headers instanceof Headers)return headers.get(name)??void 0;if(!(typeof headers!="object"||headers===null)){for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===name&&typeof value=="string")return value}}function errorCode(body){if(body!==void 0)try{let parsed=JSON.parse(body);if(typeof parsed!="object"||parsed===null)return;let nested=Reflect.get(parsed,"error"),code=Reflect.get(typeof nested=="object"&&nested!==null?nested:parsed,"code");return typeof code=="string"?code:void 0}catch{return}}function isQuotaFailure(status,body,limitKey){let code=errorCode(body);return code!==void 0&"A_CODES.has(code)||status===402?!0:status===429&&(limitKey?.includes("quota")===!0||/quota exceeded/i.test(body??""))}function describeGitHubCopilotFailure(error){if(!(error instanceof Error))return;let{status,body}=normalizeProviderError(error);if(status===void 0)return;let headers=Reflect.get(error,"headers"),requestId=headerValue(headers,"x-github-request-id"),reference=requestId===void 0?"":` ${formatProviderRequestId("GitHub",requestId)}.`;if(isQuotaFailure(status,body,headerValue(headers,"x-ratelimit-exceeded")))return`GitHub Copilot quota exceeded (HTTP ${status}): the plan's included usage or its additional-usage limit is used up, so premium models are refused until it resets or the limit is raised. Usage is shown at https://github.com/settings/copilot.${reference}`;if(status===421)return`GitHub Copilot sent this account to a different API host (HTTP 421 Misdirected Request): Business and Enterprise accounts are served from their own host, which senpi reads from the Copilot token. Run /login github-copilot so senpi stores the account's endpoint, and report it with the GitHub request id if it persists.${reference}`;if(status===403)return`GitHub Copilot refused the request (HTTP 403${body===void 0?" with an empty body":""}). Copilot checks access per model and per client; if a fresh /login github-copilot does not help, report it with the GitHub request id.${reference}`}function withGitHubCopilotFailureNote(message,provider,error){if(provider!=="github-copilot")return message;let note=describeGitHubCopilotFailure(error);return note===void 0?message:`${message}
|
|
3
3
|
${note}`}export{limitGitHubCopilotTools,recordGitHubCopilotToolLimit,formatGitHubCopilotToolLimitError,withGitHubCopilotFailureNote};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STALLED_STOP_MAX_MS_ENV,CHILD_STOP_TIMEOUT_MS,DEFAULT_HANDOFF_GRACE_MS,HANDOFF_GRACE_MS_ENV,IdleExitDecider,STOP_STALL_EVIDENCE_MAX_AGE_MS,childStalledStopMaxMs,clearStopProgress,consumeStopIntent,errorMessage,hostLoopStalled,layeredSupervisorIntent,parseIdleExitMs,readStopIntent,recentStall,releaseGeneration,resolveHostPolicy,supervisorLog,watchDrainRequest,writeDrainRequest,writeDrainWatch,writeHostReady,writeStderrLine,writeStopIntent,writeStopProgress}from"./chunk-
|
|
2
|
+
import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STALLED_STOP_MAX_MS_ENV,CHILD_STOP_TIMEOUT_MS,DEFAULT_HANDOFF_GRACE_MS,HANDOFF_GRACE_MS_ENV,IdleExitDecider,STOP_STALL_EVIDENCE_MAX_AGE_MS,childStalledStopMaxMs,clearStopProgress,consumeStopIntent,errorMessage,hostLoopStalled,layeredSupervisorIntent,parseIdleExitMs,readStopIntent,recentStall,releaseGeneration,resolveHostPolicy,supervisorLog,watchDrainRequest,writeDrainRequest,writeDrainWatch,writeHostReady,writeStderrLine,writeStopIntent,writeStopProgress}from"./chunk-DCI4QOUX.js";import{HOST_DAEMON_DIR_ENV,HostDaemonStateError,createGenerationDirectory,createHostDaemonPaths,generationPaths,hostOwnerGone,readHostOwner,sameHostOwner,writeJsonAtomic}from"./chunk-YI6KRJDC.js";import{OBSERVE_REQUEST_FIELD,RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RpcPublicEndpoint,authRecord,isObservingRequest,requestOriginHostInstance,rpcAuthProof,rpcProofMatches}from"./chunk-E6UCZ7E5.js";import{HOST_INSTANCE_ID_ENV,INTERNAL_KEY_STDIN_ENV}from"./chunk-UYO5Z35O.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-H52J72VA.js";import{require_signal_exit}from"./chunk-U3VOXCGP.js";import{spawnWithPrivateFds}from"./chunk-6WISUXVI.js";import{MAX_SOCKET_PATH_BYTES,PUBLIC_SOCKET_IDENTITY_FILE,adoptPublicSocket,classifyEndpointOwnership,shieldSocketDuringClose,socketEntryListenerState,statSocketIdentity,unlinkOwnedSocket,writeSocketIdentityFile}from"./chunk-OM7LH7AP.js";import{SOCKET_HANDSHAKE_TIMEOUT_MS,SOCKET_SECRET_FILE_ENV,acquireOwnershipSafeLock,authenticateSocket,createSocketSecret,ensureSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-QEESHRTS.js";import{DISPLAY_VERSION,VERSION,brandEnvNames,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-SODMQEHO.js";import{processStartTimeMs,readProcessIdentity,readProcessStartTime,sameProcessStartMs,waitForStartTime}from"./chunk-O5RYI3IW.js";import{__toESM}from"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{mkdir as mkdir3,rm as rm3}from"node:fs/promises";import{join as join6}from"node:path";var HostAdmission=class{constructor(info){this.stopped=!1,this.listeners=new Set,this.replies=Promise.resolve(),this.info=info}get stopping(){return this.stopped}protocol(){return{...this.info,lifecycle:this.stopped?"stopping":"ready"}}observe(info){this.info=info}stop(){this.stopped||(this.stopped=!0,this.replies=Promise.all([...this.listeners].map(listener=>listener())).then(()=>{}))}async flush(){let timer;try{await Promise.race([this.replies,new Promise(resolve2=>{timer=setTimeout(resolve2,2e3)})])}finally{clearTimeout(timer)}}onStop(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}};function hostStoppingResponse(id,command,admission){return{...typeof id=="string"?{id}:{},type:"response",command,success:!1,error:"host_stopping",errorCode:"host_stopping",errorData:{instanceId:admission.protocol().instanceId}}}var import_signal_exit=__toESM(require_signal_exit(),1);import{appendFileSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,statSync,utimesSync,writeFileSync}from"node:fs";import{join}from"node:path";var PROCESS_CRASH_RECORD_LIMIT=50,PROCESS_MARKER_HEARTBEAT_MS=6e4,FILE_MODE=384,DIR_MODE=448,MARKER_SUFFIX=".json";function processCrashPaths(agentDir){let dir=join(agentDir,"process-crashes");return{dir,liveDir:join(dir,"live"),recordsFile:join(dir,"crashes.jsonl")}}function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}function recordProcessLifetime(agentDir,kind,options){return sweepDeadProcessMarkers(agentDir,options),options.supervised?()=>{}:installProcessLifetimeMarker(agentDir,kind,options)}function installProcessLifetimeMarker(agentDir,kind,options={}){let pid=options.pid??process.pid,now=options.now??Date.now,file=join(processCrashPaths(agentDir).liveDir,`${pid}${MARKER_SUFFIX}`),marker={kind,pid,startedAt:now(),...crashingRuntimeVersions()};try{mkdirSync(processCrashPaths(agentDir).liveDir,{recursive:!0,mode:DIR_MODE}),writeFileSync(file,`${JSON.stringify(marker)}
|
|
3
3
|
`,{mode:FILE_MODE})}catch{return()=>{}}let heartbeat=setInterval(()=>{try{let at=new Date(now());utimesSync(file,at,at)}catch{}},options.heartbeatMs??PROCESS_MARKER_HEARTBEAT_MS);heartbeat.unref();let disposed=!1,dispose=()=>{disposed||(disposed=!0,clearInterval(heartbeat),process.off("exit",onProcessExit),removeSignalHook(),rmSync(file,{force:!0}))},onProcessExit=()=>{try{dispose()}catch{}};process.on("exit",onProcessExit);let removeSignalHook=(0,import_signal_exit.default)(onProcessExit);return dispose}function sweepDeadProcessMarkers(agentDir,options={}){let paths=processCrashPaths(agentDir),selfPid=options.pid??process.pid,isAlive=options.isAlive??isProcessAlive,names;try{names=readdirSync(paths.liveDir)}catch{return 0}let recorded=0;for(let name of names){if(!name.endsWith(MARKER_SUFFIX))continue;let pid=Number(name.slice(0,-MARKER_SUFFIX.length));if(!Number.isSafeInteger(pid)||pid<=0||pid===selfPid||isAlive(pid))continue;let claimed=join(paths.liveDir,`${name}.${selfPid}.sweep`);try{renameSync(join(paths.liveDir,name),claimed)}catch{continue}try{let record2=crashRecordFromMarker(readFileSync(claimed,"utf8"),statSync(claimed).mtimeMs);record2!==void 0&&(appendProcessCrashRecord(paths,record2),recorded+=1)}catch{}finally{rmSync(claimed,{force:!0})}}return recorded}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function crashRecordFromMarker(raw,lastHeartbeatMs){let value=JSON.parse(raw);if(typeof value!="object"||value===null)return;let kind=Reflect.get(value,"kind"),startedAt=Reflect.get(value,"startedAt"),senpiVersion=Reflect.get(value,"senpiVersion"),bunVersion=Reflect.get(value,"bunVersion"),productVersion=Reflect.get(value,"productVersion");if(!(typeof kind!="string"||typeof startedAt!="number"||typeof senpiVersion!="string"))return{at:new Date(lastHeartbeatMs).toISOString(),kind,detection:"unclean_exit",uptimeMs:Math.max(0,Math.round(lastHeartbeatMs-startedAt)),...typeof bunVersion=="string"?{bunVersion}:{},senpiVersion,...typeof productVersion=="string"?{productVersion}:{}}}function appendProcessCrashRecord(paths,record2){mkdirSync(paths.dir,{recursive:!0,mode:DIR_MODE}),appendFileSync(paths.recordsFile,`${JSON.stringify(record2)}
|
|
4
4
|
`,{mode:FILE_MODE});let records=readProcessCrashRecordsFrom(paths.recordsFile);if(records.length<=PROCESS_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-PROCESS_CRASH_RECORD_LIMIT);writeFileSync(paths.recordsFile,`${kept.join(`
|
|
5
5
|
`)}
|
|
@@ -10,7 +10,7 @@ import{CHILD_KILL_EXIT_TIMEOUT_MS,CHILD_STALLED_STOP_MAX_MS_ENV,CHILD_STOP_TIMEO
|
|
|
10
10
|
`)}
|
|
11
11
|
`,{mode:CRASH_RECORD_FILE_MODE})}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}async function noteChildExit(context){let now=context.now??Date.now(),intent=await consumeStopIntent(context.generation,now).catch(()=>{}),outcome=describeExit(context,intent);if(outcome===void 0)return;let stall=await recentStall(context.generation,now,STOP_STALL_EVIDENCE_MAX_AGE_MS).catch(()=>{});await recordTerminalHostRecord(context.daemonDir,{at:new Date(now).toISOString(),...context.signal===null?{code:context.code??void 0}:{signal:context.signal},uptimeMs:Math.max(0,now-context.childStartedAt),kind:"rpc-host",generation:context.instanceId,...outcome,...stall?{stall:{driftMs:stall.driftMs,at:stall.at,attributedSessionId:stall.sessionId}}:{},...crashingRuntimeVersions()}).catch(()=>{})}function describeExit(context,intent){return intent!==void 0?{detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:intent.reason,stopIntent:!0}:context.shutdown!==void 0?{detection:"engine_stop",sender:context.shutdown.supervisor,reason:context.shutdown.reason,stopIntent:!1}:classifyChildExit(context.code,context.signal).exitCode===0?void 0:{detection:context.signal===null||SELF_INFLICTED_SIGNALS.has(context.signal)?"supervisor":"external",stopIntent:!1}}var SELF_INFLICTED_SIGNALS=new Set(["SIGSEGV","SIGBUS","SIGABRT","SIGILL","SIGFPE","SIGTRAP","SIGSYS"]);async function noteEscalatedStop(daemonDir,instanceId,intent,now=Date.now()){await recordTerminalHostRecord(daemonDir,{at:new Date(now).toISOString(),signal:"SIGKILL",kind:"rpc-host",generation:instanceId,detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:`${intent.reason}; supervisor_escalated`,stopIntent:!0}).catch(()=>{})}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{existsSync,readFileSync as readFileSync3,realpathSync}from"node:fs";import{access,readFile}from"node:fs/promises";import{dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";function isCliModuleEntry(moduleUrl){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath(moduleUrl)===realpathSync(entry)}catch{return!1}}function resolveCliMainPath(modulePath=fileURLToPath(import.meta.url),bundled=isBundledNode){let declared=bundled?resolveDeclaredCliEntry(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname(modulePath),"..","..",`cli-main${extension}`);return existsSync(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(existsSync(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(existsSync(entry))return entry}}catch{}return}let parent=dirname(dir);if(parent===dir)return;dir=parent}}var existsAsync=path=>access(path).then(()=>!0,()=>!1);async function resolveCliMainPathAsync(modulePath=fileURLToPath(import.meta.url),bundled=isBundledNode){let declared=bundled?await resolveDeclaredCliEntryAsync(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname(modulePath),"..","..",`cli-main${extension}`);return await existsAsync(unbundled)?unbundled:await resolveDeclaredCliEntryAsync(modulePath)??unbundled}async function resolveDeclaredCliEntryAsync(modulePath){let dir=dirname(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(await existsAsync(manifestPath)){try{let declaredBin=JSON.parse(await readFile(manifestPath,"utf8")).bin,candidates=typeof declaredBin=="string"?[declaredBin]:Object.values(declaredBin??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(await existsAsync(entry))return entry}}catch{}return}let parent=dirname(dir);if(parent===dir)return;dir=parent}}import{watch}from"node:fs";import{createConnection,Socket}from"node:net";var MAX_CLASSIFIED_LINE_BYTES=64*1024,NEWLINE=10,ClientOccupancy=class{constructor(onAttach,ownInstance){this.clients=new Set,this.observers=new Set,this.attached=new Set,this.dependents=new Set,this.closed=!1,this.onAttach=onAttach,this.ownInstance=ownInstance}get attachedCount(){return this.attached.size}get unclassifiedCount(){return this.clients.size-this.observers.size-this.attached.size-this.dependents.size}admit(client){if(this.closed)return client.destroy(),!1;this.clients.add(client);let pending=Buffer.alloc(0),attach=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.attached.add(client),this.onAttach()},depend=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.dependents.add(client)},classify=chunk=>{pending=Buffer.concat([pending,chunk]);for(let newline=pending.indexOf(NEWLINE);newline!==-1;newline=pending.indexOf(NEWLINE)){let line=pending.subarray(0,newline).toString("utf8");if(pending=pending.subarray(newline+1),!isObservingRequest(line)){this.ownInstance!==void 0&&requestOriginHostInstance(line)===this.ownInstance?depend():attach();return}this.observers.add(client)}pending.length>MAX_CLASSIFIED_LINE_BYTES&&attach()};return client.on("data",classify),!0}release(client){let unclassified=this.clients.has(client)&&!this.observers.has(client)&&!this.attached.has(client)&&!this.dependents.has(client);return this.clients.delete(client),this.observers.delete(client),this.attached.delete(client),this.dependents.delete(client),unclassified}destroyAll(){this.closed=!0;for(let client of this.clients)client.destroy()}};var SessionRunActivity=class{#running=new Set;#settling=new Map;#settleHoldMs;#now;#onSettleHoldExpired;constructor(options={}){this.#settleHoldMs=options.settleHoldMs??Number.POSITIVE_INFINITY,this.#now=options.now??Date.now,this.#onSettleHoldExpired=options.onSettleHoldExpired}observe(line){let event=parseHostEvent(line);if(event===void 0)return!1;if(event.type==="agent_start")this.#running.add(event.sessionId),this.#settling.delete(event.sessionId);else if(event.type==="agent_settled"&&event.reason!=="session_closed")this.#running.delete(event.sessionId),this.#settling.set(event.sessionId,this.#now());else if(event.type==="agent_settled"||event.type==="agent_idle"||event.type==="session_closed")this.#running.delete(event.sessionId),this.#settling.delete(event.sessionId);else return!1;return!0}get busySessions(){return this.#running.size}get settlingSessions(){let now=this.#now();for(let[sessionId,settledAt]of this.#settling){let heldMs=now-settledAt;heldMs<this.#settleHoldMs||(this.#settling.delete(sessionId),this.#onSettleHoldExpired?.(sessionId,heldMs))}return this.#settling.size}};function holdIdleExitForSettling(decision,runs){return decision==="exit"&&runs.settlingSessions>0?"idle":decision}function parseHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId,reason}=event;return typeof sessionId=="string"?{type,sessionId,reason}:void 0}import{randomBytes}from"node:crypto";import{hkdfSync}from"node:crypto";import{Duplex}from"node:stream";import{createCipheriv,createDecipheriv}from"node:crypto";var INTERNAL_RECORD_MAX=64*1024,RECORD_LIMIT=1n<<32n,InternalRecordCipher=class{constructor(key,direction,counter=0n){this.key=key,this.direction=direction,this.counter=counter}parameters(){if(this.counter<0n||this.counter>=RECORD_LIMIT)throw new Error("internal_record_counter_exhausted");let count=Buffer.alloc(8);return count.writeBigUInt64BE(this.counter),{nonce:Buffer.concat([Buffer.alloc(4),count]),aad:Buffer.concat([Buffer.from(this.direction),count])}}seal(plaintext){if(plaintext.length<1||plaintext.length>INTERNAL_RECORD_MAX)throw new Error("internal_record_length");let{nonce:nonce2,aad}=this.parameters(),cipher=createCipheriv("aes-256-gcm",this.key,nonce2);cipher.setAAD(aad);let body=Buffer.concat([cipher.update(plaintext),cipher.final(),cipher.getAuthTag()]),length=Buffer.alloc(4);return length.writeUInt32BE(body.length),this.counter++,Buffer.concat([length,body])}open(body){if(body.length<17||body.length>INTERNAL_RECORD_MAX+16)throw new Error("internal_record_length");let{nonce:nonce2,aad}=this.parameters(),decipher=createDecipheriv("aes-256-gcm",this.key,nonce2);decipher.setAAD(aad),decipher.setAuthTag(body.subarray(-16));let plaintext=decipher.update(body.subarray(0,-16)),final=decipher.final();return this.counter++,Buffer.concat([plaintext,final])}};function createInternalRecordStream(wire,key,clientNonce,serverNonce,role){let salt=Buffer.concat([clientNonce,serverNonce]),cipher=direction=>new InternalRecordCipher(Buffer.from(hkdfSync("sha256",key,salt,`senpi-rpc-internal ${direction}`,32)),direction);return new InternalRecordStream(wire,cipher(role==="client"?"c2s":"s2c"),cipher(role==="client"?"s2c":"c2s"))}var InternalRecordStream=class extends Duplex{constructor(wire,sender,receiver){super(),this.header=Buffer.alloc(4),this.headerUsed=0,this.bodyUsed=0,this.offset=0,this.wireDone=!1,this.wireClosed=!1,this.ended=!1,this.wire=wire,this.sender=sender,this.receiver=receiver,this.once("error",error=>{error.message.startsWith("internal_record")&&process.stderr.write(`senpi rpc: internal hop closed: ${error.message}
|
|
12
12
|
`)}),this.on("error",()=>{}),wire.on("data",chunk=>{wire.pause(),this.pending=chunk,this.offset=0,this.consume()}),wire.once("end",()=>{this.wireDone=!0,this.pending===void 0&&this.finish()}),wire.once("error",error=>this.destroy(error)),wire.once("close",()=>{this.wireDone=!0,this.wireClosed=!0,this.ended&&this.readableEnded?this.destroy():this.pending===void 0&&this.finish()}),this.once("end",()=>{this.wireClosed&&this.destroy()})}finish(){this.ended||(this.ended=!0,this.headerUsed!==0||this.body!==void 0?this.destroy(new Error("internal_record_truncated")):this.push(null))}consume(){try{let chunk=this.pending;if(!chunk)return;for(;this.offset<chunk.length;){if(!this.body){let n2=Math.min(4-this.headerUsed,chunk.length-this.offset);if(chunk.copy(this.header,this.headerUsed,this.offset,this.offset+n2),this.headerUsed+=n2,this.offset+=n2,this.headerUsed!==4)break;let length=this.header.readUInt32BE();if(length<17||length>INTERNAL_RECORD_MAX+16)throw new Error("internal_record_length");this.headerUsed=0,this.body=Buffer.alloc(length)}let n=Math.min(this.body.length-this.bodyUsed,chunk.length-this.offset);if(chunk.copy(this.body,this.bodyUsed,this.offset,this.offset+n),this.bodyUsed+=n,this.offset+=n,this.bodyUsed===this.body.length){let plaintext=this.receiver.open(this.body);if(this.body=void 0,this.bodyUsed=0,!this.push(plaintext)){this.offset===chunk.length&&(this.pending=void 0,this.wireDone&&this.finish());return}}}this.pending=void 0,this.wireDone?this.finish():this.wire.resume()}catch(cause){this.destroy(cause instanceof Error&&cause.message.startsWith("internal_record")?cause:new Error("internal_record_unverified",{cause}))}}_read(){this.pending?this.consume():this.wire.resume()}_write(chunk,_encoding,callback){let offset=0,next=error=>{if(error){callback(error);return}if(this.destroyed){callback(new Error("internal_hop_lost"));return}if(offset===chunk.length){callback();return}try{let end=Math.min(chunk.length,offset+INTERNAL_RECORD_MAX),record2=this.sender.seal(chunk.subarray(offset,end));offset=end,this.wire.write(record2,next)}catch(cause){callback(cause instanceof Error?cause:new Error("internal_record_invalid"))}};next()}_final(callback){this.wire.end(callback)}_destroy(error,callback){this.wire.destroy(),callback(error)}};var INTERNAL_LAUNCH_ID="internal";function proof(key,label,first,second){return rpcAuthProof(key,label,INTERNAL_LAUNCH_ID,first,second)}function matches(actual,expected){return rpcProofMatches(expected,actual)}function object(value){if(!isObject(value))throw new Error("auth_failed");return value}function isObject(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function nonce(value){if(typeof value!="string"||!RPC_AUTH_HEX.test(value))throw new Error("auth_failed");return value}var HOST_PRE_AUTH_BUDGET={maxBytes:8192,timeoutMs:2e3};async function handshake(socket,budget,run){let readBytes=0,ended=!1,rejectPending,fail=error=>{ended=!0,rejectPending?.(error),socket.destroy()},timer=budget.timeoutMs===void 0?void 0:setTimeout(()=>fail(new Error("internal_auth_timeout")),budget.timeoutMs);timer?.unref();let onError=error=>fail(error),onClose=()=>fail(new Error("internal_hop_lost"));socket.on("error",onError),socket.once("close",onClose);let read=()=>new Promise((resolve2,reject)=>{if(ended)return reject(new Error("internal_hop_lost"));let buffer=Buffer.alloc(0);rejectPending=cause=>{socket.off("data",data),reject(cause)};let data=chunk=>{let newline=chunk.indexOf(10),used=newline===-1?chunk.length:newline+1;if(readBytes+=used,readBytes>budget.maxBytes)return fail(new Error("internal_auth_oversized"));if(buffer=Buffer.concat([buffer,chunk.subarray(0,used)]),newline!==-1){socket.pause(),socket.off("data",data),rejectPending=void 0,used<chunk.length&&socket.unshift(chunk.subarray(used));try{resolve2(object(JSON.parse(buffer.toString("utf8"))))}catch{reject(new Error("auth_failed"))}}};socket.on("data",data),socket.resume()});try{return await run(read,frame=>new Promise((resolve2,reject)=>{socket.write(`${JSON.stringify(frame)}
|
|
13
|
-
`,error=>error?reject(error):resolve2())}))}catch(cause){throw socket.destroy(),cause}finally{timer&&clearTimeout(timer),socket.off("error",onError),socket.off("close",onClose)}}function connectInternalConnection(socket,key,options={}){return handshake(socket,{maxBytes:MAX_RPC_LINE_CHARACTERS,timeoutMs:options.timeoutMs},async(read,send)=>{let clientNonce=randomBytes(32).toString("hex"),[response]=await Promise.all([read(),send({id:"internal-protocol",type:"get_protocol_info",observe:!0,auth:{client_nonce:clientNonce}})]),data=response.data;if(!isObject(data)||!isObject(data.auth))throw new Error("host_identity_unproven");let auth=data.auth,serverNonce=nonce(auth.server_nonce);if(response.id!=="internal-protocol"||response.success!==!0||auth.launch_id!==INTERNAL_LAUNCH_ID||!matches(auth.server_proof,proof(key,"server",clientNonce,serverNonce)))throw new Error("host_identity_unproven");let[result]=await Promise.all([read(),send({id:"internal-auth",type:"authenticate",client_proof:proof(key,"client",serverNonce,clientNonce)})]);if(result.id!=="internal-auth"||result.command!=="authenticate"||result.success!==!0)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"client")})}function acceptInternalConnection(socket,key,protocol={}){return handshake(socket,HOST_PRE_AUTH_BUDGET,async(read,send)=>{let refuse=async frame2=>{throw await send({id:frame2.id,type:"response",command:frame2.type,success:!1,error:"auth_required",errorCode:"auth_required"}),new Error("auth_required")},first=await read(),offered=isObject(first.auth)?first.auth.client_nonce:void 0;if(first.type!=="get_protocol_info"||typeof offered!="string"||!RPC_AUTH_HEX.test(offered))return refuse(first);let clientNonce=offered,serverNonce=randomBytes(32).toString("hex"),[frame]=await Promise.all([read(),send({id:first.id,type:"response",command:first.type,success:!0,data:{...protocol,capabilities:[...Array.isArray(protocol.capabilities)?protocol.capabilities:[],"socket_auth"],auth:{launch_id:INTERNAL_LAUNCH_ID,server_nonce:serverNonce,server_proof:proof(key,"server",clientNonce,serverNonce)}}})]);if(frame.type!=="authenticate")return refuse(frame);let valid=matches(frame.client_proof,proof(key,"client",serverNonce,clientNonce));if(await send({id:frame.id,type:"response",command:"authenticate",success:valid,...valid?{}:{error:"auth_failed",errorCode:"auth_failed"}}),!valid)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"server")})}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}var INTERNAL_OBSERVER_HANDSHAKE_MS=5e3,SupervisorActivity=class{constructor(options){this.options=options,this.decider=new IdleExitDecider(options.idleExitMs),this.runs=new SessionRunActivity({settleHoldMs:options.idleExitMs,onSettleHoldExpired:(sessionId,heldMs)=>supervisorLog(`session ${sessionId} settled ${heldMs} ms ago and its agent_settled extension handlers have not finished; idle exit no longer waits for them`)}),this.clients=new ClientOccupancy(()=>this.refresh(),options.instanceId),this.observerLink=createObserverLink({open:()=>this.connectObserver(),settled:options.settled,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}})}current(){return{connections:this.clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:this.observerLink.healthy(),unhealthySince:this.observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:this.decider.idleExitMs,observedBusy:this.runs.busySessions})}}refresh(){let current=this.current();return(current.connections>0||current.activeTurns>0||this.clients.unclassifiedCount>0)&&this.options.onActivity?.(),holdIdleExitForSettling(this.decider.update(current),this.runs)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.runs.settlingSessions===0&&this.clients.attachedCount===0&&this.clients.unclassifiedCount===0}openObserver(){return this.observerLink.open()}stopObserver(){this.observerLink.stop(),this.observerSocket?.destroy()}async connectObserver(){let secret=this.options.internalSecret,next=createConnection(resolveSocketTransportAddress(this.options.internalSocket,process.platform,secret));secret&&sendSocketHandshake(next,secret);let stream;try{this.options.internalKey?stream=await connectInternalConnection(next,this.options.internalKey,{timeoutMs:INTERNAL_OBSERVER_HANDSHAKE_MS}):(await waitForConnect(next,5e3),stream=next)}catch(cause){throw next.destroy(),cause}return this.observerSocket=stream,attachJsonlLineReader(stream,line=>this.observeHostEvent(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{let lost=()=>{handler(),this.options.onActivity?.()};stream.once("close",lost),stream.once("error",lost)}}}observeHostEvent(line){this.runs.observe(line)&&this.refresh()}},OWNER_EXIT_GRACE_MS=2e3,OWNER_PROBE_MAX_INTERVAL_MS=5e3,SupervisorOwner=class{constructor(generationDir){this.watchFailed=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.gone=!1,this.revision=0,this.stopped=!1,this.idle=new IdleExitDecider(OWNER_EXIT_GRACE_MS,()=>performance.now()),this.generationDir=generationDir}async start(fd){if(await this.reload(),!(fd===void 0||this.owner==null))try{let pipe=new Socket({fd,readable:!0,writable:!1});this.pipe=pipe;let bound=this.owner,failed=!1,eof=()=>{!failed&&!this.stopped&&sameHostOwner(this.owner,bound)&&(this.gone=!0)};pipe.once("end",eof),process.platform==="win32"&&pipe.once("close",eof),pipe.once("error",()=>{failed=!0,this.pipe===pipe&&(this.pipe=void 0),pipe.destroy()}),pipe.resume()}catch{this.pipe=void 0}}async reload(){let revision=++this.revision,next=await readHostOwner(this.generationDir);if(!(this.stopped||revision!==this.revision)){if(sameHostOwner(this.owner,next)||(this.pipe?.destroy(),this.pipe=void 0,this.gone=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.activity()),this.owner=next,next==null)this.watcher?.close(),this.watcher=void 0;else if(!this.watcher&&!this.watchFailed)try{this.watcher=watch(this.generationDir,(_event,filename)=>{filename?.toString()==="owner.json"&&this.reload()}),this.watcher.once("error",()=>{this.watchFailed=!0,this.watcher?.close(),this.watcher=void 0})}catch{this.watchFailed=!0}}}activity(){this.idle.update({connections:1,activeTurns:0})}async shouldExit(activity){this.watcher||await this.reload();let owner=this.owner,revision=this.revision;if(owner!=null&&(!this.pipe||process.ppid!==owner.pid)&&!this.gone&&performance.now()>=this.nextProbeAt){let gone=await hostOwnerGone(owner);if(this.stopped||revision!==this.revision)return!1;this.gone=gone,this.nextProbeAt=performance.now()+this.probeIntervalMs,this.probeIntervalMs=Math.min(OWNER_PROBE_MAX_INTERVAL_MS,this.probeIntervalMs*2)}let quiet=this.gone&&owner!=null&&activity.quiescent();if(this.idle.update({connections:quiet?0:1,activeTurns:0})!=="exit")return!1;let current=await readHostOwner(this.generationDir);return!this.stopped&&revision===this.revision&&sameHostOwner(owner,current)&&activity.quiescent()}stop(){this.stopped=!0,this.watcher?.close(),this.pipe?.destroy()}};function waitForConnect(socket,timeoutMs){return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve2()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}import{readFile as readFile2}from"node:fs/promises";var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3,REPLACED_CONFIRMATIONS=3,IDENTITY_PROBE_TIMEOUT_MS=2e3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0)return endpoint.pointer===void 0?()=>{}:watchPointerSupersession(endpoint,endpoint.pointer,onLost);let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function watchPointerSupersession(endpoint,pointer,onLost){let probe=endpoint.probeInstanceId??probeAnsweringInstance,readPointer=endpoint.readPointerInstanceId??pointerInstanceId,agreeingPolls=0,observing=!1,lost=!1,observe=async()=>{let named=await readPointer(pointer.file);return named===void 0||named===pointer.instanceId?!1:await probe(endpoint.path)===named},timer=setInterval(()=>{lost||observing||endpoint.settled?.()===!0||(observing=!0,observe().then(replaced=>{lost||endpoint.settled?.()===!0||(agreeingPolls=replaced?agreeingPolls+1:0,!(agreeingPolls<REPLACED_CONFIRMATIONS)&&(lost=!0,clearInterval(timer),onLost("replaced")))},()=>{agreeingPolls=0}).finally(()=>{observing=!1}))},SUPERSESSION_POLL_MS);return timer.unref?.(),()=>clearInterval(timer)}async function pointerInstanceId(file){try{let parsed=JSON.parse(await readFile2(file,"utf8")),instanceId=typeof parsed=="object"&&parsed!==null?Reflect.get(parsed,"instance_id"):void 0;return typeof instanceId=="string"&&instanceId!==""?instanceId:void 0}catch{return}}async function probeAnsweringInstance(path){let{isRecord:isRecord2,requestOnSocket}=await import("./host-socket-request-F2R5P34M.js"),answer=await requestOnSocket(path,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},IDENTITY_PROBE_TIMEOUT_MS).catch(()=>{});return isRecord2(answer)&&typeof answer.instanceId=="string"?answer.instanceId:void 0}function ignore(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{},relay){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping,this.relay=relay}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}async acceptRequests(generation){let stop=watchDrainRequest(generation.drainRequestFile,request=>{supervisorLog(`drain requested (${request.reason})`),this.drain()});return await writeDrainWatch(generation.drainWatchFile,{pid:process.pid}).catch(cause=>{supervisorLog(`cannot advertise the drain request: ${errorMessage(cause)}`)}),stop}requestChildDrain(){let{child,relay}=this;if(!(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)&&(relay&&writeDrainRequest(relay.file,{sender:relay.sender,reason:"supervisor_drain"}).catch(cause=>{supervisorLog(`could not relay the drain to the host: ${errorMessage(cause)}`)}),process.platform!=="win32"))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path,identity,settled,drain,onReplaced,pointer){return watchForSupersession({path,identity,settled,...pointer&&{pointer}},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}var CHILD_IDENTITY_TICK_MS=500,CHILD_IDENTITY_READ_GAP_TICKS=10,CHILD_IDENTITY_READ_GAP_MAX_TICKS=120;function childLiveness(pid){try{return process.kill(pid,0),"alive"}catch(cause){return cause instanceof Error&&"code"in cause&&cause.code==="ESRCH"?"dead":"unknown"}}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let readStartTime=()=>readProcessStartTime(pid,process.platform,1e3),baseline=await readStartTime().catch(()=>{}),adoptable=!0,suspect=!1,deadTicks=0,reading=!1,ended=!1,ticksUntilRead=0,readGapTicks=CHILD_IDENTITY_READ_GAP_TICKS,backOff=()=>{ticksUntilRead=readGapTicks,readGapTicks=Math.min(readGapTicks*2,CHILD_IDENTITY_READ_GAP_MAX_TICKS)},end=()=>{ended=!0,onGone()},settle=current=>{if(!ended){if(baseline===void 0){current!==void 0&&adoptable&&childLiveness(pid)==="alive"?baseline=current:backOff();return}if(current!==void 0&¤t!==baseline)return end();current===baseline&&(suspect=!1),backOff()}},timer=setInterval(()=>{if(ended||shuttingDown()||child.exitCode!==null||child.signalCode!==null)return;ticksUntilRead>0&&ticksUntilRead--;let liveness=childLiveness(pid);if(liveness==="dead"){if(deadTicks++,deadTicks>=2)return end();suspect=!0,adoptable=!1;return}(deadTicks>0||liveness==="unknown")&&(suspect=!0,adoptable=!1),deadTicks=0,!(!(baseline===void 0?adoptable:suspect)||reading||ticksUntilRead>0)&&(reading=!0,readStartTime().then(settle,()=>{ended||backOff()}).finally(()=>{reading=!1}))},CHILD_IDENTITY_TICK_MS);return timer.unref?.(),()=>{ended=!0,clearInterval(timer)}}import{randomBytes as randomBytes2}from"node:crypto";import{readFile as readFile4}from"node:fs/promises";import{join as join5}from"node:path";import{readFileSync as readFileSync4}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat=readFileSync4(`/proc/${pid}/stat`,"utf8"),ticks=stat.slice(stat.lastIndexOf(")")+2).split(" ")[19];return ticks!==void 0&&/^\d+$/.test(ticks)?ticks:void 0}catch{return}}async function compareRecordedStart(pid,recorded,platform,probe){if(platform==="linux"){if(recorded.ticks===void 0)return"unknown";let observed2=probe.ticks(pid);return observed2===void 0?"unknown":observed2===recorded.ticks?"same":"changed"}if(recorded.time===void 0)return"unknown";let observed=await probe.time(pid),recordedMs=processStartTimeMs(recorded.time),observedMs=observed===void 0?void 0:processStartTimeMs(observed);return recordedMs===void 0||observedMs===void 0?"unknown":sameProcessStartMs(recordedMs,observedMs)?"same":"changed"}import{randomUUID}from"node:crypto";import{realpathSync as realpathSync2}from"node:fs";import{mkdir,readFile as readFile3,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join3}from"node:path";var INTERNAL_HOST_DIR_PREFIX="senpi-rpc-host-internal-",SHORT_TEMP_ROOT="/tmp";function internalHostDirRoots(){let primary=tmpdir();return canonicalPath(primary)!==canonicalPath(SHORT_TEMP_ROOT)?[primary,SHORT_TEMP_ROOT]:[Buffer.byteLength(primary)<Buffer.byteLength(SHORT_TEMP_ROOT)?primary:SHORT_TEMP_ROOT]}function canonicalPath(path){try{return realpathSync2(path)}catch{return path}}function internalHostDirRoot(name){for(let root of internalHostDirRoots())if(Buffer.byteLength(join3(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join3(root,name,"host.sock"));throw new Error(`internal_socket_path_too_long: every candidate exceeds ${MAX_SOCKET_PATH_BYTES} bytes (${tried.join(", ")}); set TMPDIR to a shorter directory`)}async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join3(baseDir,`internal-${randomUUID()}`);return await mkdir(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join3(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID().slice(0,8)}`,dir=join3(internalHostDirRoot(name),name);return await mkdir(dir,{recursive:!1,mode:448}),await writeFile(join3(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join3(dir,"host.sock"),dir,secretPath:join3(dir,".secret")}}var CHILD_START_TIME_WAIT_MS=1e4,CHILD_START_TIME_UNHURRIED_MS=15e3;async function readChildStartTime(pid,timeoutMs){let identity=await readProcessIdentity(pid,process.platform,timeoutMs,void 0,"UTC");if(identity.kind==="error")throw identity.error;return identity.kind==="present"?identity.identity:void 0}async function recordChildPid(file,pid,running){try{await writeJsonAtomic(file,{pid,processStartTime:null});let processStartTime=await waitForStartTime(pid,CHILD_START_TIME_WAIT_MS,p=>readChildStartTime(p,1e3)).catch(()=>{})??await readChildStartTime(pid,CHILD_START_TIME_UNHURRIED_MS).catch(()=>{});if(processStartTime===void 0){supervisorLog(`host child pid ${pid} start time unreadable at recording`);return}if(!running())return;await writeJsonAtomic(file,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile3(settingsFile,"utf8"))}catch{return}}import{execFileSync}from"node:child_process";import{closeSync as closeSync2,constants,fstatSync,openSync,rmSync as rmSync2}from"node:fs";import{join as join4}from"node:path";import{closeSync}from"node:fs";import{Socket as Socket2}from"node:net";function watchHostLifetime(fd,gone,unavailable){let stopped=!1,bun=Reflect.get(globalThis,"Bun");if(typeof bun=="object"&&bun!==null&&typeof Reflect.get(bun,"file")=="function"){let reader=Reflect.get(bun,"file")(fd).stream().getReader();return(async()=>{try{for(;!stopped;){let{done}=await reader.read();if(done){stopped||gone();return}}}catch{stopped||unavailable()}})(),()=>{stopped||(stopped=!0,reader.cancel().catch(()=>{}).finally(()=>closeSync(fd)))}}let socket=new Socket2({fd,readable:!0,writable:!1});return socket.once("end",()=>{stopped||gone()}),socket.once("error",()=>{stopped||unavailable()}),socket.unref(),socket.resume(),()=>{stopped=!0,socket.destroy()}}var HOST_WATCH_LIFETIME_FIFO_ENV="SENPI_RPC_HOST_LIFETIME_FIFO";function prepareLifetimeBinding(hopDir,platform=process.platform){if(platform!=="linux")return{};let path=join4(hopDir,"lifetime.fifo");try{return rmSync2(path,{force:!0}),execFileSync("mkfifo",["-m","600",path],{stdio:"ignore"}),openSync(path,constants.O_RDWR),{lifetimeFifo:path}}catch{return{}}}function armLifetimeBinding(binding,gone,unavailable,platform=process.platform){if(platform==="win32")return;let fifo=platform==="linux"?openFifoReadEnd(binding.lifetimeFifo):void 0;if(fifo!==void 0)return binding.lifetimeFd!==void 0&&closeSync2(binding.lifetimeFd),watchHostLifetime(fifo,()=>gone("supervisor lifetime FIFO closed"),unavailable);if(binding.lifetimeFd!==void 0)return watchHostLifetime(binding.lifetimeFd,()=>gone("supervisor stdin lifetime closed"),unavailable)}function openFifoReadEnd(path){if(path===void 0)return;let fd;try{fd=openSync(path,constants.O_RDONLY|constants.O_NONBLOCK|constants.O_NOFOLLOW)}catch{return}let stat=fstatSync(fd),owned=typeof process.getuid!="function"||stat.uid===process.getuid();if(stat.isFIFO()&&owned&&(stat.mode&511)===384)return fd;closeSync2(fd)}async function recordedOwnerStartTime(dir){if(dir!==void 0)try{let owner=JSON.parse(await readFile4(join5(dir,".owner"),"utf8")),start=owner!==null&&typeof owner=="object"?Reflect.get(owner,"processStartTime"):void 0;return typeof start=="string"?start:void 0}catch{return}}async function prepareInternalHop(daemonDir){let created=await createInternalSocketPath(daemonDir),internal={...created,secretPath:created.secretPath??socketSecretPath(created.socket)},internalSecret=process.platform==="win32"?await createSocketSecret(internal.secretPath):void 0,internalKey=process.platform==="win32"?void 0:randomBytes2(32);return{internal,internalSocket:internal.socket,internalSecret,internalKey,...internalKey&&internal.dir!==void 0?prepareLifetimeBinding(internal.dir):{},supervisorStart:internalKey?{time:await recordedOwnerStartTime(internal.dir),ticks:readProcessStartTicks(process.pid)}:void 0,transport:{...internalSecret?{internalSecret}:{},...internalKey?{internalKey}:{}}}}import childProcess from"node:child_process";import{Socket as Socket4}from"node:net";import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}import{rmSync as rmSync3}from"node:fs";import{rm}from"node:fs/promises";import{Socket as Socket3}from"node:net";var HOST_WATCH_BACKSTOP_INTERVAL_MS=3e4,HOST_WATCH_PPID_INTERVAL_MS=250,HOST_WATCH_PPID_BACKUP_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS=1e3,HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS=6e4;function supervisorPoll(ppid,recorded,fire,stopped){let stopPpid,ppidIntervalMs;return{arm(intervalMs){stopped()||ppid===void 0||ppidIntervalMs===intervalMs||(stopPpid?.(),ppidIntervalMs=intervalMs,stopPpid=watchPpid(ppid,recorded,fire,intervalMs))},soleInterval:recorded.ticks!==void 0||recorded.time!==void 0?HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS:HOST_WATCH_PPID_INTERVAL_MS,stop:()=>stopPpid?.()}}function watchPpid(supervisorPid,recorded,fire,intervalMs){if(supervisorPid===process.pid)return()=>{};let linux=process.platform==="linux",comparable=linux?recorded.ticks!==void 0:recorded.time!==void 0,identityEveryTicks=Math.max(1,Math.round((linux?HOST_WATCH_IDENTITY_INTERVAL_MS:HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS)/intervalMs)),probe={ticks:pid=>readProcessStartTicks(pid),time:pid=>readProcessStartTime(pid,process.platform,1e3)},ticks=0,stopped=!1,probing=!1,timer=setInterval(()=>{if(!stopped){if(!processAlive(supervisorPid)){fire(`supervisor pid ${supervisorPid} is gone`);return}ticks+=1,!(!comparable||probing||ticks%identityEveryTicks!==0)&&(probing=!0,compareRecordedStart(supervisorPid,recorded,process.platform,probe).then(result=>{!stopped&&result==="changed"&&fire(`supervisor pid ${supervisorPid} start time changed`)},()=>{}).finally(()=>{probing=!1}))}},intervalMs);return timer.unref?.(),()=>{stopped=!0,clearInterval(timer)}}function processAlive(pid){try{return process.kill(pid,0),!0}catch(cause){return!(cause instanceof Error&&"code"in cause&&cause.code==="ESRCH")}}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PSTART_ENV="SENPI_RPC_HOST_WATCH_PSTART",HOST_WATCH_PSTART_TICKS_ENV="SENPI_RPC_HOST_WATCH_PSTART_TICKS",HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function readHostWatchdogConfig(env=process.env){let ppid=parsePositiveInteger(env[HOST_WATCH_PPID_ENV]),fd=process.platform!=="win32"&&ppid!==void 0?void 0:parsePositiveInteger(env[HOST_WATCH_FD_ENV]);if(fd===void 0&&ppid===void 0)return;let scratchDir=env[HOST_SCRATCH_DIR_ENV],cleanupPaths=env[HOST_CLEANUP_PATHS_ENV]?.split(`
|
|
13
|
+
`,error=>error?reject(error):resolve2())}))}catch(cause){throw socket.destroy(),cause}finally{timer&&clearTimeout(timer),socket.off("error",onError),socket.off("close",onClose)}}function connectInternalConnection(socket,key,options={}){return handshake(socket,{maxBytes:MAX_RPC_LINE_CHARACTERS,timeoutMs:options.timeoutMs},async(read,send)=>{let clientNonce=randomBytes(32).toString("hex"),[response]=await Promise.all([read(),send({id:"internal-protocol",type:"get_protocol_info",observe:!0,auth:{client_nonce:clientNonce}})]),data=response.data;if(!isObject(data)||!isObject(data.auth))throw new Error("host_identity_unproven");let auth=data.auth,serverNonce=nonce(auth.server_nonce);if(response.id!=="internal-protocol"||response.success!==!0||auth.launch_id!==INTERNAL_LAUNCH_ID||!matches(auth.server_proof,proof(key,"server",clientNonce,serverNonce)))throw new Error("host_identity_unproven");let[result]=await Promise.all([read(),send({id:"internal-auth",type:"authenticate",client_proof:proof(key,"client",serverNonce,clientNonce)})]);if(result.id!=="internal-auth"||result.command!=="authenticate"||result.success!==!0)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"client")})}function acceptInternalConnection(socket,key,protocol={}){return handshake(socket,HOST_PRE_AUTH_BUDGET,async(read,send)=>{let refuse=async frame2=>{throw await send({id:frame2.id,type:"response",command:frame2.type,success:!1,error:"auth_required",errorCode:"auth_required"}),new Error("auth_required")},first=await read(),offered=isObject(first.auth)?first.auth.client_nonce:void 0;if(first.type!=="get_protocol_info"||typeof offered!="string"||!RPC_AUTH_HEX.test(offered))return refuse(first);let clientNonce=offered,serverNonce=randomBytes(32).toString("hex"),[frame]=await Promise.all([read(),send({id:first.id,type:"response",command:first.type,success:!0,data:{...protocol,capabilities:[...Array.isArray(protocol.capabilities)?protocol.capabilities:[],"socket_auth"],auth:{launch_id:INTERNAL_LAUNCH_ID,server_nonce:serverNonce,server_proof:proof(key,"server",clientNonce,serverNonce)}}})]);if(frame.type!=="authenticate")return refuse(frame);let valid=matches(frame.client_proof,proof(key,"client",serverNonce,clientNonce));if(await send({id:frame.id,type:"response",command:"authenticate",success:valid,...valid?{}:{error:"auth_failed",errorCode:"auth_failed"}}),!valid)throw new Error("auth_failed");return createInternalRecordStream(socket,key,Buffer.from(clientNonce,"hex"),Buffer.from(serverNonce,"hex"),"server")})}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}var INTERNAL_OBSERVER_HANDSHAKE_MS=5e3,SupervisorActivity=class{constructor(options){this.options=options,this.decider=new IdleExitDecider(options.idleExitMs),this.runs=new SessionRunActivity({settleHoldMs:options.idleExitMs,onSettleHoldExpired:(sessionId,heldMs)=>supervisorLog(`session ${sessionId} settled ${heldMs} ms ago and its agent_settled extension handlers have not finished; idle exit no longer waits for them`)}),this.clients=new ClientOccupancy(()=>this.refresh(),options.instanceId),this.observerLink=createObserverLink({open:()=>this.connectObserver(),settled:options.settled,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}})}current(){return{connections:this.clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:this.observerLink.healthy(),unhealthySince:this.observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:this.decider.idleExitMs,observedBusy:this.runs.busySessions})}}refresh(){let current=this.current();return(current.connections>0||current.activeTurns>0||this.clients.unclassifiedCount>0)&&this.options.onActivity?.(),holdIdleExitForSettling(this.decider.update(current),this.runs)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.runs.settlingSessions===0&&this.clients.attachedCount===0&&this.clients.unclassifiedCount===0}openObserver(){return this.observerLink.open()}stopObserver(){this.observerLink.stop(),this.observerSocket?.destroy()}async connectObserver(){let secret=this.options.internalSecret,next=createConnection(resolveSocketTransportAddress(this.options.internalSocket,process.platform,secret));secret&&sendSocketHandshake(next,secret);let stream;try{this.options.internalKey?stream=await connectInternalConnection(next,this.options.internalKey,{timeoutMs:INTERNAL_OBSERVER_HANDSHAKE_MS}):(await waitForConnect(next,5e3),stream=next)}catch(cause){throw next.destroy(),cause}return this.observerSocket=stream,attachJsonlLineReader(stream,line=>this.observeHostEvent(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{let lost=()=>{handler(),this.options.onActivity?.()};stream.once("close",lost),stream.once("error",lost)}}}observeHostEvent(line){this.runs.observe(line)&&this.refresh()}},OWNER_EXIT_GRACE_MS=2e3,OWNER_PROBE_MAX_INTERVAL_MS=5e3,SupervisorOwner=class{constructor(generationDir){this.watchFailed=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.gone=!1,this.revision=0,this.stopped=!1,this.idle=new IdleExitDecider(OWNER_EXIT_GRACE_MS,()=>performance.now()),this.generationDir=generationDir}async start(fd){if(await this.reload(),!(fd===void 0||this.owner==null))try{let pipe=new Socket({fd,readable:!0,writable:!1});this.pipe=pipe;let bound=this.owner,failed=!1,eof=()=>{!failed&&!this.stopped&&sameHostOwner(this.owner,bound)&&(this.gone=!0)};pipe.once("end",eof),process.platform==="win32"&&pipe.once("close",eof),pipe.once("error",()=>{failed=!0,this.pipe===pipe&&(this.pipe=void 0),pipe.destroy()}),pipe.resume()}catch{this.pipe=void 0}}async reload(){let revision=++this.revision,next=await readHostOwner(this.generationDir);if(!(this.stopped||revision!==this.revision)){if(sameHostOwner(this.owner,next)||(this.pipe?.destroy(),this.pipe=void 0,this.gone=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.activity()),this.owner=next,next==null)this.watcher?.close(),this.watcher=void 0;else if(!this.watcher&&!this.watchFailed)try{this.watcher=watch(this.generationDir,(_event,filename)=>{filename?.toString()==="owner.json"&&this.reload()}),this.watcher.once("error",()=>{this.watchFailed=!0,this.watcher?.close(),this.watcher=void 0})}catch{this.watchFailed=!0}}}activity(){this.idle.update({connections:1,activeTurns:0})}async shouldExit(activity){this.watcher||await this.reload();let owner=this.owner,revision=this.revision;if(owner!=null&&(!this.pipe||process.ppid!==owner.pid)&&!this.gone&&performance.now()>=this.nextProbeAt){let gone=await hostOwnerGone(owner);if(this.stopped||revision!==this.revision)return!1;this.gone=gone,this.nextProbeAt=performance.now()+this.probeIntervalMs,this.probeIntervalMs=Math.min(OWNER_PROBE_MAX_INTERVAL_MS,this.probeIntervalMs*2)}let quiet=this.gone&&owner!=null&&activity.quiescent();if(this.idle.update({connections:quiet?0:1,activeTurns:0})!=="exit")return!1;let current=await readHostOwner(this.generationDir);return!this.stopped&&revision===this.revision&&sameHostOwner(owner,current)&&activity.quiescent()}stop(){this.stopped=!0,this.watcher?.close(),this.pipe?.destroy()}};function waitForConnect(socket,timeoutMs){return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve2()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}import{readFile as readFile2}from"node:fs/promises";var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3,REPLACED_CONFIRMATIONS=3,IDENTITY_PROBE_TIMEOUT_MS=2e3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0)return endpoint.pointer===void 0?()=>{}:watchPointerSupersession(endpoint,endpoint.pointer,onLost);let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function watchPointerSupersession(endpoint,pointer,onLost){let probe=endpoint.probeInstanceId??probeAnsweringInstance,readPointer=endpoint.readPointerInstanceId??pointerInstanceId,agreeingPolls=0,observing=!1,lost=!1,observe=async()=>{let named=await readPointer(pointer.file);return named===void 0||named===pointer.instanceId?!1:await probe(endpoint.path)===named},timer=setInterval(()=>{lost||observing||endpoint.settled?.()===!0||(observing=!0,observe().then(replaced=>{lost||endpoint.settled?.()===!0||(agreeingPolls=replaced?agreeingPolls+1:0,!(agreeingPolls<REPLACED_CONFIRMATIONS)&&(lost=!0,clearInterval(timer),onLost("replaced")))},()=>{agreeingPolls=0}).finally(()=>{observing=!1}))},SUPERSESSION_POLL_MS);return timer.unref?.(),()=>clearInterval(timer)}async function pointerInstanceId(file){try{let parsed=JSON.parse(await readFile2(file,"utf8")),instanceId=typeof parsed=="object"&&parsed!==null?Reflect.get(parsed,"instance_id"):void 0;return typeof instanceId=="string"&&instanceId!==""?instanceId:void 0}catch{return}}async function probeAnsweringInstance(path){let{isRecord:isRecord2,requestOnSocket}=await import("./host-socket-request-XPXJV3CS.js"),answer=await requestOnSocket(path,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},IDENTITY_PROBE_TIMEOUT_MS).catch(()=>{});return isRecord2(answer)&&typeof answer.instanceId=="string"?answer.instanceId:void 0}function ignore(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{},relay){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping,this.relay=relay}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}async acceptRequests(generation){let stop=watchDrainRequest(generation.drainRequestFile,request=>{supervisorLog(`drain requested (${request.reason})`),this.drain()});return await writeDrainWatch(generation.drainWatchFile,{pid:process.pid}).catch(cause=>{supervisorLog(`cannot advertise the drain request: ${errorMessage(cause)}`)}),stop}requestChildDrain(){let{child,relay}=this;if(!(child.pid===void 0||child.exitCode!==null||child.signalCode!==null)&&(relay&&writeDrainRequest(relay.file,{sender:relay.sender,reason:"supervisor_drain"}).catch(cause=>{supervisorLog(`could not relay the drain to the host: ${errorMessage(cause)}`)}),process.platform!=="win32"))try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path,identity,settled,drain,onReplaced,pointer){return watchForSupersession({path,identity,settled,...pointer&&{pointer}},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}var CHILD_IDENTITY_TICK_MS=500,CHILD_IDENTITY_READ_GAP_TICKS=10,CHILD_IDENTITY_READ_GAP_MAX_TICKS=120;function childLiveness(pid){try{return process.kill(pid,0),"alive"}catch(cause){return cause instanceof Error&&"code"in cause&&cause.code==="ESRCH"?"dead":"unknown"}}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let readStartTime=()=>readProcessStartTime(pid,process.platform,1e3),baseline=await readStartTime().catch(()=>{}),adoptable=!0,suspect=!1,deadTicks=0,reading=!1,ended=!1,ticksUntilRead=0,readGapTicks=CHILD_IDENTITY_READ_GAP_TICKS,backOff=()=>{ticksUntilRead=readGapTicks,readGapTicks=Math.min(readGapTicks*2,CHILD_IDENTITY_READ_GAP_MAX_TICKS)},end=()=>{ended=!0,onGone()},settle=current=>{if(!ended){if(baseline===void 0){current!==void 0&&adoptable&&childLiveness(pid)==="alive"?baseline=current:backOff();return}if(current!==void 0&¤t!==baseline)return end();current===baseline&&(suspect=!1),backOff()}},timer=setInterval(()=>{if(ended||shuttingDown()||child.exitCode!==null||child.signalCode!==null)return;ticksUntilRead>0&&ticksUntilRead--;let liveness=childLiveness(pid);if(liveness==="dead"){if(deadTicks++,deadTicks>=2)return end();suspect=!0,adoptable=!1;return}(deadTicks>0||liveness==="unknown")&&(suspect=!0,adoptable=!1),deadTicks=0,!(!(baseline===void 0?adoptable:suspect)||reading||ticksUntilRead>0)&&(reading=!0,readStartTime().then(settle,()=>{ended||backOff()}).finally(()=>{reading=!1}))},CHILD_IDENTITY_TICK_MS);return timer.unref?.(),()=>{ended=!0,clearInterval(timer)}}import{randomBytes as randomBytes2}from"node:crypto";import{readFile as readFile4}from"node:fs/promises";import{join as join5}from"node:path";import{readFileSync as readFileSync4}from"node:fs";function readProcessStartTicks(pid,platform=process.platform){if(platform==="linux")try{let stat=readFileSync4(`/proc/${pid}/stat`,"utf8"),ticks=stat.slice(stat.lastIndexOf(")")+2).split(" ")[19];return ticks!==void 0&&/^\d+$/.test(ticks)?ticks:void 0}catch{return}}async function compareRecordedStart(pid,recorded,platform,probe){if(platform==="linux"){if(recorded.ticks===void 0)return"unknown";let observed2=probe.ticks(pid);return observed2===void 0?"unknown":observed2===recorded.ticks?"same":"changed"}if(recorded.time===void 0)return"unknown";let observed=await probe.time(pid),recordedMs=processStartTimeMs(recorded.time),observedMs=observed===void 0?void 0:processStartTimeMs(observed);return recordedMs===void 0||observedMs===void 0?"unknown":sameProcessStartMs(recordedMs,observedMs)?"same":"changed"}import{randomUUID}from"node:crypto";import{realpathSync as realpathSync2}from"node:fs";import{mkdir,readFile as readFile3,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join3}from"node:path";var INTERNAL_HOST_DIR_PREFIX="senpi-rpc-host-internal-",SHORT_TEMP_ROOT="/tmp";function internalHostDirRoots(){let primary=tmpdir();return canonicalPath(primary)!==canonicalPath(SHORT_TEMP_ROOT)?[primary,SHORT_TEMP_ROOT]:[Buffer.byteLength(primary)<Buffer.byteLength(SHORT_TEMP_ROOT)?primary:SHORT_TEMP_ROOT]}function canonicalPath(path){try{return realpathSync2(path)}catch{return path}}function internalHostDirRoot(name){for(let root of internalHostDirRoots())if(Buffer.byteLength(join3(root,name,"host.sock"))<=MAX_SOCKET_PATH_BYTES)return root;let tried=internalHostDirRoots().map(root=>join3(root,name,"host.sock"));throw new Error(`internal_socket_path_too_long: every candidate exceeds ${MAX_SOCKET_PATH_BYTES} bytes (${tried.join(", ")}); set TMPDIR to a shorter directory`)}async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join3(baseDir,`internal-${randomUUID()}`);return await mkdir(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join3(dir2,"secret")}}let name=`${INTERNAL_HOST_DIR_PREFIX}${randomUUID().slice(0,8)}`,dir=join3(internalHostDirRoot(name),name);return await mkdir(dir,{recursive:!1,mode:448}),await writeFile(join3(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join3(dir,"host.sock"),dir,secretPath:join3(dir,".secret")}}var CHILD_START_TIME_WAIT_MS=1e4,CHILD_START_TIME_UNHURRIED_MS=15e3;async function readChildStartTime(pid,timeoutMs){let identity=await readProcessIdentity(pid,process.platform,timeoutMs,void 0,"UTC");if(identity.kind==="error")throw identity.error;return identity.kind==="present"?identity.identity:void 0}async function recordChildPid(file,pid,running){try{await writeJsonAtomic(file,{pid,processStartTime:null});let processStartTime=await waitForStartTime(pid,CHILD_START_TIME_WAIT_MS,p=>readChildStartTime(p,1e3)).catch(()=>{})??await readChildStartTime(pid,CHILD_START_TIME_UNHURRIED_MS).catch(()=>{});if(processStartTime===void 0){supervisorLog(`host child pid ${pid} start time unreadable at recording`);return}if(!running())return;await writeJsonAtomic(file,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile3(settingsFile,"utf8"))}catch{return}}import{execFileSync}from"node:child_process";import{closeSync as closeSync2,constants,fstatSync,openSync,rmSync as rmSync2}from"node:fs";import{join as join4}from"node:path";import{closeSync}from"node:fs";import{Socket as Socket2}from"node:net";function watchHostLifetime(fd,gone,unavailable){let stopped=!1,bun=Reflect.get(globalThis,"Bun");if(typeof bun=="object"&&bun!==null&&typeof Reflect.get(bun,"file")=="function"){let reader=Reflect.get(bun,"file")(fd).stream().getReader();return(async()=>{try{for(;!stopped;){let{done}=await reader.read();if(done){stopped||gone();return}}}catch{stopped||unavailable()}})(),()=>{stopped||(stopped=!0,reader.cancel().catch(()=>{}).finally(()=>closeSync(fd)))}}let socket=new Socket2({fd,readable:!0,writable:!1});return socket.once("end",()=>{stopped||gone()}),socket.once("error",()=>{stopped||unavailable()}),socket.unref(),socket.resume(),()=>{stopped=!0,socket.destroy()}}var HOST_WATCH_LIFETIME_FIFO_ENV="SENPI_RPC_HOST_LIFETIME_FIFO";function prepareLifetimeBinding(hopDir,platform=process.platform){if(platform!=="linux")return{};let path=join4(hopDir,"lifetime.fifo");try{return rmSync2(path,{force:!0}),execFileSync("mkfifo",["-m","600",path],{stdio:"ignore"}),openSync(path,constants.O_RDWR),{lifetimeFifo:path}}catch{return{}}}function armLifetimeBinding(binding,gone,unavailable,platform=process.platform){if(platform==="win32")return;let fifo=platform==="linux"?openFifoReadEnd(binding.lifetimeFifo):void 0;if(fifo!==void 0)return binding.lifetimeFd!==void 0&&closeSync2(binding.lifetimeFd),watchHostLifetime(fifo,()=>gone("supervisor lifetime FIFO closed"),unavailable);if(binding.lifetimeFd!==void 0)return watchHostLifetime(binding.lifetimeFd,()=>gone("supervisor stdin lifetime closed"),unavailable)}function openFifoReadEnd(path){if(path===void 0)return;let fd;try{fd=openSync(path,constants.O_RDONLY|constants.O_NONBLOCK|constants.O_NOFOLLOW)}catch{return}let stat=fstatSync(fd),owned=typeof process.getuid!="function"||stat.uid===process.getuid();if(stat.isFIFO()&&owned&&(stat.mode&511)===384)return fd;closeSync2(fd)}async function recordedOwnerStartTime(dir){if(dir!==void 0)try{let owner=JSON.parse(await readFile4(join5(dir,".owner"),"utf8")),start=owner!==null&&typeof owner=="object"?Reflect.get(owner,"processStartTime"):void 0;return typeof start=="string"?start:void 0}catch{return}}async function prepareInternalHop(daemonDir){let created=await createInternalSocketPath(daemonDir),internal={...created,secretPath:created.secretPath??socketSecretPath(created.socket)},internalSecret=process.platform==="win32"?await createSocketSecret(internal.secretPath):void 0,internalKey=process.platform==="win32"?void 0:randomBytes2(32);return{internal,internalSocket:internal.socket,internalSecret,internalKey,...internalKey&&internal.dir!==void 0?prepareLifetimeBinding(internal.dir):{},supervisorStart:internalKey?{time:await recordedOwnerStartTime(internal.dir),ticks:readProcessStartTicks(process.pid)}:void 0,transport:{...internalSecret?{internalSecret}:{},...internalKey?{internalKey}:{}}}}import childProcess from"node:child_process";import{Socket as Socket4}from"node:net";import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}import{rmSync as rmSync3}from"node:fs";import{rm}from"node:fs/promises";import{Socket as Socket3}from"node:net";var HOST_WATCH_BACKSTOP_INTERVAL_MS=3e4,HOST_WATCH_PPID_INTERVAL_MS=250,HOST_WATCH_PPID_BACKUP_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_INTERVAL_MS=5e3,HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS=1e3,HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS=6e4;function supervisorPoll(ppid,recorded,fire,stopped){let stopPpid,ppidIntervalMs;return{arm(intervalMs){stopped()||ppid===void 0||ppidIntervalMs===intervalMs||(stopPpid?.(),ppidIntervalMs=intervalMs,stopPpid=watchPpid(ppid,recorded,fire,intervalMs))},soleInterval:recorded.ticks!==void 0||recorded.time!==void 0?HOST_WATCH_IDENTITY_ONLY_INTERVAL_MS:HOST_WATCH_PPID_INTERVAL_MS,stop:()=>stopPpid?.()}}function watchPpid(supervisorPid,recorded,fire,intervalMs){if(supervisorPid===process.pid)return()=>{};let linux=process.platform==="linux",comparable=linux?recorded.ticks!==void 0:recorded.time!==void 0,identityEveryTicks=Math.max(1,Math.round((linux?HOST_WATCH_IDENTITY_INTERVAL_MS:HOST_WATCH_SPAWNING_IDENTITY_INTERVAL_MS)/intervalMs)),probe={ticks:pid=>readProcessStartTicks(pid),time:pid=>readProcessStartTime(pid,process.platform,1e3)},ticks=0,stopped=!1,probing=!1,timer=setInterval(()=>{if(!stopped){if(!processAlive(supervisorPid)){fire(`supervisor pid ${supervisorPid} is gone`);return}ticks+=1,!(!comparable||probing||ticks%identityEveryTicks!==0)&&(probing=!0,compareRecordedStart(supervisorPid,recorded,process.platform,probe).then(result=>{!stopped&&result==="changed"&&fire(`supervisor pid ${supervisorPid} start time changed`)},()=>{}).finally(()=>{probing=!1}))}},intervalMs);return timer.unref?.(),()=>{stopped=!0,clearInterval(timer)}}function processAlive(pid){try{return process.kill(pid,0),!0}catch(cause){return!(cause instanceof Error&&"code"in cause&&cause.code==="ESRCH")}}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PSTART_ENV="SENPI_RPC_HOST_WATCH_PSTART",HOST_WATCH_PSTART_TICKS_ENV="SENPI_RPC_HOST_WATCH_PSTART_TICKS",HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function readHostWatchdogConfig(env=process.env){let ppid=parsePositiveInteger(env[HOST_WATCH_PPID_ENV]),fd=process.platform!=="win32"&&ppid!==void 0?void 0:parsePositiveInteger(env[HOST_WATCH_FD_ENV]);if(fd===void 0&&ppid===void 0)return;let scratchDir=env[HOST_SCRATCH_DIR_ENV],cleanupPaths=env[HOST_CLEANUP_PATHS_ENV]?.split(`
|
|
14
14
|
`).filter(Boolean),publicSocket=env[HOST_PUBLIC_SOCKET_ENV],daemonDir=env[HOST_DAEMON_DIR_ENV],instanceId=env[HOST_INSTANCE_ID_ENV];return{fd,ppid,...env[HOST_WATCH_PSTART_ENV]?{processStartTime:env[HOST_WATCH_PSTART_ENV]}:{},...env[HOST_WATCH_PSTART_TICKS_ENV]?{processStartTicks:env[HOST_WATCH_PSTART_TICKS_ENV]}:{},...env[HOST_WATCH_LIFETIME_FIFO_ENV]?{lifetimeFifo:env[HOST_WATCH_LIFETIME_FIFO_ENV]}:{},scratchDir:scratchDir===void 0||scratchDir===""?void 0:scratchDir,cleanupPaths,publicSocket:publicSocket===""?void 0:publicSocket,...daemonDir&&instanceId?{daemonDir,instanceId}:{}}}function readHostWatchdogConfigFromBrandEnv(env=process.env){return readHostWatchdogConfig({[HOST_WATCH_FD_ENV]:env[HOST_WATCH_FD_ENV]??envValue("RPC_HOST_WATCH_FD",env),[HOST_WATCH_PPID_ENV]:env[HOST_WATCH_PPID_ENV]??envValue("RPC_HOST_WATCH_PPID",env),[HOST_WATCH_PSTART_ENV]:env[HOST_WATCH_PSTART_ENV]??envValue("RPC_HOST_WATCH_PSTART",env),[HOST_WATCH_PSTART_TICKS_ENV]:env[HOST_WATCH_PSTART_TICKS_ENV]??envValue("RPC_HOST_WATCH_PSTART_TICKS",env),[HOST_WATCH_LIFETIME_FIFO_ENV]:env[HOST_WATCH_LIFETIME_FIFO_ENV]??envValue("RPC_HOST_LIFETIME_FIFO",env),[HOST_SCRATCH_DIR_ENV]:env[HOST_SCRATCH_DIR_ENV]??envValue("RPC_HOST_SCRATCH_DIR",env),[HOST_PUBLIC_SOCKET_ENV]:env[HOST_PUBLIC_SOCKET_ENV]??envValue("RPC_HOST_PUBLIC_SOCKET",env),[HOST_CLEANUP_PATHS_ENV]:env[HOST_CLEANUP_PATHS_ENV]??envValue("RPC_HOST_CLEANUP_PATHS",env),[HOST_DAEMON_DIR_ENV]:env[HOST_DAEMON_DIR_ENV],[HOST_INSTANCE_ID_ENV]:env[HOST_INSTANCE_ID_ENV]})}var WATCH_ENV_SUFFIXES=["RPC_HOST_WATCH_FD","RPC_HOST_WATCH_PPID","RPC_HOST_WATCH_PSTART","RPC_HOST_WATCH_PSTART_TICKS","RPC_HOST_LIFETIME_FIFO","RPC_HOST_SCRATCH_DIR","RPC_HOST_PUBLIC_SOCKET","RPC_HOST_CLEANUP_PATHS"];function consumeHostWatchdogEnv(env=process.env){let config=readHostWatchdogConfigFromBrandEnv(env);return scrubHostWatchdogEnv(env),config}function scrubHostWatchdogEnv(env=process.env){for(let suffix of WATCH_ENV_SUFFIXES)for(let name of[`SENPI_${suffix}`,...brandEnvNames(suffix)])delete env[name]}function armHostWatchdog(config,onSupervisorGone){if(!config)return()=>{};let stopped=!1,fired=!1,fire=reason=>{if(stopped||fired)return;fired=!0,disarm(),config.daemonDir!==void 0&&config.instanceId!==void 0&&recordHostCrash(config.daemonDir,{at:new Date().toISOString(),uptimeMs:Math.round(process.uptime()*1e3),kind:"rpc-host-watchdog",generation:config.instanceId,reason});let captured=captureBeforeCleanup(config);if(process.platform==="win32"){let cleanup=captured.then(()=>cleanupWatchdogPaths(config));onSupervisorGone(reason,cleanup)}else captured.then(()=>cleanupWatchdogPaths(config)).finally(()=>onSupervisorGone(reason))},disarmers=[],disarm=()=>{stopped=!0;for(let stop of disarmers.splice(0))stop()},poll=supervisorPoll(config.ppid,{ticks:config.processStartTicks,time:config.processStartTime},fire,()=>stopped);disarmers.push(()=>poll.stop());let pollWanted=!1,pipeLive=!1;config.fd!==void 0&&(pipeLive=watchFdForEof(config.fd,fire,disarmers,()=>{pipeLive=!1,pollWanted&&poll.arm(poll.soleInterval)}));let fallback=()=>{pollWanted=!0,poll.arm(pipeLive?HOST_WATCH_PPID_BACKUP_INTERVAL_MS:poll.soleInterval)},stopLifetime;try{stopLifetime=armLifetimeBinding(config,fire,fallback)}catch{stopLifetime=void 0}return stopLifetime!==void 0?(disarmers.push(stopLifetime),poll.arm(HOST_WATCH_BACKSTOP_INTERVAL_MS)):fallback(),disarm}function watchFdForEof(fd,fire,disarmers,onUnavailable){let stream,streamFailed=!1,fired=!1,fireOnce=reason=>{fired||(fired=!0,fire(reason))};try{stream=new Socket3({fd,readable:!0,writable:!1})}catch{return!1}stream.resume();let onEnd=()=>fireOnce(`supervisor pipe fd ${fd} closed`),onClose=()=>{streamFailed||onEnd()},onError=()=>{streamFailed=!0,onUnavailable()};return stream.once("end",onEnd),process.platform==="win32"&&stream.once("close",onClose),stream.once("error",onError),disarmers.push(()=>{stream.off("end",onEnd),stream.off("close",onClose),stream.off("error",onError),stream.destroy()}),!0}function captureBeforeCleanup(config){return config.beforeCleanup===void 0?Promise.resolve():Promise.resolve().then(config.beforeCleanup).catch(()=>{})}async function cleanupWatchdogPaths(config){let paths=[...config.cleanupPaths??[],...config.scratchDir?[config.scratchDir]:[]];for(let path of paths)try{process.platform==="win32"?rmSync3(path,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}):await rm(path,{recursive:!0,force:!0})}catch{}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,ownerFd,presenterBootstrapFd,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--mcp-presenter-fd"&&argv[index+1]==="4"){presenterBootstrapFd=4,index++;continue}if(arg==="--owner-fd"&&index+1<argv.length){if(ownerFd=Number(argv[++index]),!Number.isSafeInteger(ownerFd)||ownerFd<3)return;continue}if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0||ownerFd===presenterBootstrapFd&&ownerFd!==void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,ownerFd,bindSocket,replaceIdentity,presenterBootstrapFd}}var OWNER_WATCH_FD=3,ownerPipes=new Set;function keepOwnerPipe(child){let pipe=child.stdio[OWNER_WATCH_FD];if(!(pipe instanceof Socket4))throw new Error("RPC owner pipe was not inherited");ownerPipes.add(pipe),pipe.on("error",()=>{}),pipe.unref(),child.once("exit",()=>{ownerPipes.delete(pipe),pipe.destroy()})}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...runtimeExecArgv(),resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}var HOST_CHILD_WATCH_FD=3;function spawnHostChild(options){let{launch,internalSocket,internal,internalSecret,publicSocket}=options,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),bootstrap=launch.presenterBootstrapFd!==void 0&&!childLaunch.shell;bootstrap&&childLaunch.args.push("--mcp-presenter-fd","4");let child=spawnWithPrivateFds((command,args,options2)=>childProcess.spawn(command,args,options2),childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:options.daemonDir,[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_WATCH_FD_ENV]:String(HOST_CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),[HOST_WATCH_PSTART_ENV]:options.supervisorStart?.time,[HOST_WATCH_PSTART_TICKS_ENV]:options.supervisorStart?.ticks,[HOST_WATCH_LIFETIME_FIFO_ENV]:options.lifetimeFifo,...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},[SOCKET_SECRET_FILE_ENV]:process.platform==="win32"&&internalSecret?internal.secretPath:void 0,[INTERNAL_KEY_STDIN_ENV]:options.internalKey?"1":void 0,[HOST_CLEANUP_PATHS_ENV]:options.cleanupPaths.join(`
|
|
15
15
|
`),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:[process.platform==="win32"?"ignore":"pipe","ignore","inherit","pipe",...bootstrap?["pipe"]:[]],windowsHide:!0},{final:!0});if(launch.presenterBootstrapFd!==void 0){let fd=launch.presenterBootstrapFd;import("./mcp-presenter-bootstrap-XXJSBV7V.js").then(({presenterBootstrapStream,relayPresenterBootstrap})=>{let upstream=presenterBootstrapStream(fd);if(upstream&&bootstrap)return relayPresenterBootstrap(upstream,child);upstream?.destroy(),child.stdio[4]?.destroy()}).catch(()=>child.stdio[4]?.destroy())}return options.internalKey&&(child.stdin?.on("error",()=>{}),child.stdin?.write(options.internalKey)),child}import{chmod,lstat,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection as createConnection2,createServer}from"node:net";import{dirname as dirname2}from"node:path";import{StringDecoder}from"node:string_decoder";function proxyWithAdmission(client,internal,admission,auth){let reply=chunk=>write(client,auth?auth.response(chunk.toString()):chunk),pending=[],refused=new Set,protocols=0,refusals=Promise.resolve(),unsubscribe=admission.onStop(()=>(refusals=refusePending(),refusals));async function refusePending(){let ids=pending.splice(0);for(let id of ids)refused.add(id);try{for(let id of ids)await reply(serializeJsonLine(hostStoppingResponse(id,"open_session",admission)))}catch{fail()}}client.once("close",()=>{unsubscribe(),internal?.destroy()});let fail=()=>{internal?.destroy(),client.destroy()};client.once("error",fail),internal?.once("error",()=>{admission.stopping||fail()}),requests().catch(()=>{admission.stopping||fail()}),internal&&responses(internal).catch(()=>{admission.stopping||fail()});async function requests(){for await(let line of lines(auth?.input??client,MAX_RPC_LINE_CHARACTERS)){if(line===void 0){await reply(serializeJsonLine({type:"response",command:"parse",success:!1,error:`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}));continue}let request=record(line);admission.stopping&&request?.type==="get_protocol_info"?await reply(serializeJsonLine({id:request.id,type:"response",command:request.type,success:!0,data:admission.protocol()})):admission.stopping&&(request?.type==="open_session"||!internal)?await reply(serializeJsonLine(hostStoppingResponse(request?.id,String(request?.type??"parse"),admission))):internal&&(request?.type==="open_session"&&pending.push(request.id),request?.type==="get_protocol_info"&&protocols++,await write(internal,`${line}
|
|
16
16
|
`))}internal?.end()}async function responses(source){let fragments=[];for await(let chunk of source){let newline=chunk.lastIndexOf(10);if(newline===-1){fragments.push(chunk);continue}let complete=chunk.subarray(0,newline+1);if(!auth&&pending.length===0&&protocols===0&&refused.size===0){client.cork();let written;try{for(let fragment of fragments)client.write(fragment);written=write(client,complete)}finally{client.uncork()}await written}else{let batch=fragments.length>0?Buffer.concat([...fragments,complete]):complete;await reply(filterReplies(batch))}fragments=newline+1<chunk.length?[chunk.subarray(newline+1)]:[]}fragments.length>0&&await reply(filterReplies(Buffer.concat(fragments))),await refusals,client.end(()=>client.destroy())}function filterReplies(batch){if(pending.length===0&&protocols===0&&refused.size===0)return batch;let output=[],changed=!1;for(let start=0;start<batch.length;){let newline=batch.indexOf(10,start),end=newline===-1?batch.length:newline+1,line=batch.subarray(start,end);start=end;let response=line.includes('"open_session"')||line.includes('"get_protocol_info"')?record(line.toString("utf8")):void 0;if(response?.type==="response"&&response.command==="open_session"){if(refused.has(response.id)){changed=!0;continue}let index=pending.indexOf(response.id);index!==-1&&pending.splice(index,1)}if(response?.type==="response"&&response.command==="get_protocol_info"&&(protocols=Math.max(0,protocols-1),response.success===!0)){isRecord(response.data)&&admission.observe(response.data),output.push(Buffer.from(serializeJsonLine({...response,data:admission.protocol()}))),changed=!0;continue}output.push(line)}return changed?Buffer.concat(output):batch}}async function write(socket,line){await new Promise((resolve2,reject)=>{socket.write(line,error=>error?reject(error):resolve2())})}async function*lines(socket,limit){let decoder=new StringDecoder("utf8"),buffer="",discarding=!1;for await(let chunk of socket){let text=typeof chunk=="string"?chunk:decoder.write(chunk),offset=0;for(;offset<text.length;){let newline=text.indexOf(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{legacyJsonText}from"./chunk-H52J72VA.js";import{USAGE_LIMIT_EXHAUSTION,classifyErrorMessage}from"./chunk-
|
|
2
|
+
import{legacyJsonText}from"./chunk-H52J72VA.js";import{USAGE_LIMIT_EXHAUSTION,classifyErrorMessage}from"./chunk-AVP6DDBF.js";var KIMI_RETRYABLE_STATUS_CODES=new Set([408,409,429,500,502,503,504,529]);function classifyKimiHttpStatus(statusCode){return statusCode===void 0||!KIMI_RETRYABLE_STATUS_CODES.has(statusCode)?{verdict:"terminal"}:statusCode===429?{verdict:"rate-limited"}:{verdict:"transient"}}function assertNever(kind){throw new Error(`Unhandled retry failure kind: ${kind}`)}var classifyKimiFailure=failure=>{switch(failure.kind){case"abort":case"refusal":case"sensitive":case"quota-exhausted":case"image-format":case"unknown":return{verdict:"terminal"};case"connection":case"timeout":case"provider":return{verdict:"transient"};case"empty-response":return failure.finishReason==="filtered"?{verdict:"terminal"}:{verdict:"transient"};case"http-status":return classifyKimiHttpStatus(failure.statusCode);default:return assertNever(failure.kind)}},SENPI_STRUCTURED_RETRYABLE_STATUS_CODES=new Set([408,409,429,500,502,503,504,522,524,529]),SENPI_STRUCTURED_TERMINAL_PROVIDER_CODES=new Set(["insufficient_quota","credits_required",...USAGE_LIMIT_EXHAUSTION.codes]),classifySenpiAssistantFailure=failure=>{switch(failure.kind){case"abort":case"refusal":case"sensitive":case"quota-exhausted":case"image-format":return{verdict:"terminal"}}let regexVerdict=classifyErrorMessage(failure.message);return regexVerdict==="non-retryable"?{verdict:"terminal"}:failure.shouldRetry===!1?{verdict:"terminal"}:failure.providerCodes?.some(code=>SENPI_STRUCTURED_TERMINAL_PROVIDER_CODES.has(code))?{verdict:"terminal"}:regexVerdict==="retryable"?{verdict:"transient"}:failure.statusCode!==void 0&&SENPI_STRUCTURED_RETRYABLE_STATUS_CODES.has(failure.statusCode)?failure.statusCode===429?{verdict:"rate-limited"}:{verdict:"transient"}:{verdict:"terminal"}};var extractNormalizedHint=failure=>failure.retryAfterMs,senpiDefaultTurnStrategy=()=>{throw new Error("senpi-default turn tier strategy must be injected by coding-agent")},SENPI_DEFAULT_RETRY_PROFILE={id:"senpi-default",providerRequest:{enabled:!0,maxRetries:0,backoff:{baseDelayMs:500,growthFactor:2,perAttemptCapMs:8e3,jitter:{mode:"subtractive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"override",acceptZero:!0,ceiling:{maxDelayMs:6e4,onExceeded:"error-with-marker"}},classify:classifySenpiAssistantFailure},turn:{enabled:!0,maxRetries:5,backoff:{baseDelayMs:2e3,growthFactor:2,perAttemptCapMs:8e3,jitter:{mode:"additive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"tiered",strategy:senpiDefaultTurnStrategy},classify:classifySenpiAssistantFailure},fallback:{terminal:"immediate-if-eligible",transient:"after-turn-budget",rateLimited:"tiered",resetBudgetOnModelChange:!0}},KIMI_CODE_RETRY_PROFILE={id:"kimi-code",providerRequest:{enabled:!1,maxRetries:0,backoff:{baseDelayMs:500,growthFactor:2,perAttemptCapMs:32e3,jitter:{mode:"additive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"override",acceptZero:!1,ceiling:{maxDelayMs:null,onExceeded:"error-with-marker"}},classify:classifyKimiFailure},turn:{enabled:!0,maxRetries:9,backoff:{baseDelayMs:500,growthFactor:2,perAttemptCapMs:32e3,jitter:{mode:"additive",ratio:.25}},extractServerHint:extractNormalizedHint,serverHint:{mode:"override",acceptZero:!1,ceiling:{maxDelayMs:null,onExceeded:"error-with-marker"}},classify:classifyKimiFailure},fallback:{terminal:"immediate-if-eligible",transient:"after-turn-budget",rateLimited:"after-turn-budget",resetBudgetOnModelChange:!0}};import{isBigIntObject,isBooleanObject,isNumberObject,isStringObject}from"node:util/types";function normalizeJsonValue(input){let ancestors=new Set,changed=!1,visit=(input2,key)=>{let value2=input2;if(typeof value2=="object"&&value2!==null||typeof value2=="function"||typeof value2=="bigint"){let toJSON=value2.toJSON;typeof toJSON=="function"&&(value2=toJSON.call(value2,key),changed=!0)}if(typeof value2=="object"&&value2!==null){if(isNumberObject(value2))value2=+value2,changed=!0;else if(isStringObject(value2))value2=String(value2),changed=!0;else if(isBooleanObject(value2))value2=Boolean.prototype.valueOf.call(value2),changed=!0;else if(isBigIntObject(value2))throw new TypeError("Do not know how to serialize a BigInt")}if(typeof value2=="bigint")throw new TypeError("Do not know how to serialize a BigInt");if(typeof value2=="number"){let normalized=Number.isFinite(value2)?Object.is(value2,-0)?0:value2:null;return Object.is(normalized,value2)||(changed=!0),normalized}if(typeof value2>"u"||typeof value2=="function"||typeof value2=="symbol"){changed=!0;return}if(typeof value2!="object"||value2===null)return value2;if(ancestors.has(value2))throw new TypeError("Converting circular structure to JSON");ancestors.add(value2);try{if("toJSON"in value2&&(changed=!0),Array.isArray(value2)){let array=[],length=value2.length;for(let index=0;index<length;index++){let descriptor=Object.getOwnPropertyDescriptor(value2,String(index));(!descriptor||descriptor.get)&&(changed=!0),array.push(visit(value2[index],String(index))??null)}return array}let result={},names=Object.keys(value2);(Object.getPrototypeOf(value2)!==Object.prototype||Reflect.ownKeys(value2).length!==names.length)&&(changed=!0);for(let name of names){Object.getOwnPropertyDescriptor(value2,name)?.get&&(changed=!0);let child=visit(value2[name],name);child!==void 0&&Object.defineProperty(result,name,{value:child,enumerable:!0,configurable:!0,writable:!0})}return result}finally{ancestors.delete(value2)}},value;try{value=visit(input,"")}catch(error){if(!(error instanceof RangeError))throw error;return{value:JSON.parse(legacyJsonText(input)),changed:!0}}if(value===void 0)throw new SyntaxError("JSON input has no representation");return{value,changed}}var MEDIA_BEARING_RECORD_TYPES=new Set(["tool_execution_end","message_start","message_end","turn_end","agent_end","entry_appended"]),MEDIA_BEARING_RESPONSE_COMMANDS=new Set(["get_messages","get_entries","get_tree","get_state","open_session"]);function base64ByteLength(data){let padding=data.endsWith("==")?2:data.endsWith("=")?1:0;return Math.max(0,Math.floor(data.length*3/4)-padding)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isInlineImage(value){return isPlainObject(value)&&value.type==="image"&&typeof value.data=="string"}function omitContentImages(content,toolCallId,persist){let replaced;for(let index=0;index<content.length;index++){let block=content[index];if(!isInlineImage(block))continue;replaced??=[...content];let ref={toolCallId,contentIndex:index};replaced[index]={type:"image_ref",mimeType:typeof block.mimeType=="string"?block.mimeType:"application/octet-stream",byteLength:base64ByteLength(block.data),ref,...persist?.(ref,block)}}return replaced??content}function omitToolResultImages(message,persist){let content=message.content,toolCallId=typeof message.toolCallId=="string"?message.toolCallId:"";if(!Array.isArray(content))return message;let omitted=omitContentImages(content,toolCallId,persist);return omitted===content?message:{...message,content:omitted}}function enter(value,key,persist){if(Array.isArray(value))return{key,value,index:0};if(!isPlainObject(value))return;let scrubbed=value.role==="toolResult"?omitToolResultImages(value,persist):value,entries=Object.entries(scrubbed).filter(([name,child])=>(name!=="content"||scrubbed===value)&&(isPlainObject(child)||Array.isArray(child)));return scrubbed===value?{key,value,scrubbed,entries,index:0}:{key,value,scrubbed,entries,index:0,replaced:{...scrubbed}}}function walk(root,persist){let first=enter(root,0,persist);if(!first)return root;let stack=[first],ancestors=new Set([first.value]);for(;;){let top=stack[stack.length-1];if("entries"in top?top.index<top.entries.length:top.index<top.value.length){let[key,child]="entries"in top?top.entries[top.index]:[top.index,top.value[top.index]];top.index++;let frame=enter(child,key,persist);if(!frame)continue;if(ancestors.has(frame.value))throw new TypeError("Converting circular structure to JSON");ancestors.add(frame.value),stack.push(frame);continue}stack.pop(),ancestors.delete(top.value);let result=top.replaced??top.value,parent=stack[stack.length-1];if(!parent)return result;result!==top.value&&("entries"in parent?(parent.replaced??={...parent.scrubbed})[top.key]=result:(parent.replaced??=[...parent.value])[top.key]=result)}}function omitToolExecutionEndImages(record,persist){let result=record.result;if(!isPlainObject(result)||!Array.isArray(result.content))return record;let toolCallId=typeof record.toolCallId=="string"?record.toolCallId:"",omitted=omitContentImages(result.content,toolCallId,persist);return omitted===result.content?record:{...record,result:{...result,content:omitted}}}function carriesMedia(record){return typeof record.type!="string"?!1:MEDIA_BEARING_RECORD_TYPES.has(record.type)?!0:record.type==="response"&&typeof record.command=="string"?MEDIA_BEARING_RESPONSE_COMMANDS.has(record.command):!1}function omitNormalInlineMedia(record,persist){let typed=record;if(!carriesMedia(typed))return record;let scrubbed=typed.type==="tool_execution_end"?omitToolExecutionEndImages(typed,persist):typed,walked=walk(scrubbed,persist);return walked===typed?record:walked}export{SENPI_DEFAULT_RETRY_PROFILE,KIMI_CODE_RETRY_PROFILE,normalizeJsonValue,base64ByteLength,carriesMedia,omitNormalInlineMedia};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{usageLimitResetMs}from"./chunk-ZNPH5BWS.js";import{rateLimitModelFamily}from"./chunk-6VWIMHMH.js";import{normalizeProviderError}from"./chunk-AC72EWI5.js";import{extract429RetryAfterMs,parseRetryAfterMsMarker}from"./chunk-RQFD6LG2.js";import{getOverflowPatterns}from"./chunk-GKP34H3C.js";import{readProviderDiagnostic}from"./chunk-Z7HTHT6K.js";import{ModelsError,OAuthTokenEndpointError,PROVIDER_NOT_CONFIGURED_PREFIX,USAGE_LIMIT_EXHAUSTION,isOAuthRefreshUnavailableError}from"./chunk-AVP6DDBF.js";import{siwcRecoveryFromDiagnostic}from"./chunk-3SASTB6Y.js";function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}function applyAccountOrder(order,ranked){if(order===void 0||order.length===0)return[...ranked];let byName=new Map(ranked.map(slot=>[slot.name,slot])),front=[];for(let name of order){let slot=byName.get(name);slot!==void 0&&!front.includes(slot)&&front.push(slot)}return[...front,...ranked.filter(slot=>!front.includes(slot))]}function withoutOrderedAccount(credential,name){if(credential.order===void 0||!credential.order.includes(name))return credential;let order=credential.order.filter(entry=>entry!==name),next={...credential};return order.length===0?delete next.order:next.order=order,next}function isSlotBlocked(slot,now){return slot.blockReason==="auth_error"||slot.blockedUntil!==void 0&&slot.blockedUntil>now}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ACCOUNT_USAGE_LIMIT_TEXT=new RegExp([...USAGE_LIMIT_EXHAUSTION.markers.map(escapeRegExp),String.raw`\b(?:hit|reached)\s+your\b[^.]*?\blimit\b`,String.raw`\busage\s+limit\s+reached\b`,String.raw`\b(?:Go|Free)UsageLimitError\b`,String.raw`\bblocking_limit\b`,String.raw`\brapid_refill_breaker\b`,String.raw`\bquota\s+exceeded\b`].join("|"),"i");function isAccountUsageLimitText(text){return ACCOUNT_USAGE_LIMIT_TEXT.test(text)}var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,GUESSED_BACKOFF_CAP_MS=1800*1e3,RETRY_SAME_MAX_ATTEMPTS=2,ACCOUNT_POOL_REFUSAL_NOTE="No request was sent: the account pool refused it locally.";function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,GUESSED_BACKOFF_CAP_MS,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}function usageLimitCooldown(resetMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS;return{cooldownMs:Math.min(cap,resetMs),retryAfterWasCapped:resetMs>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,REVOKED_TOKEN_TEXT=/invalidated (?:oauth )?token|(?<!\b(?:session|csrf|xsrf|page|pagination|continuation|cursor|sync|stream|upload|idempotency|request|nonce|state)[ _-])token(?:[ _-](?:invalidated|revoked)|\s(?:has been|was) (?:invalidated|revoked))/i,REFUSED_GRANT_CODES=new Set(["invalid_grant","refresh_token_expired","refresh_token_invalidated","refresh_token_reused","token_revoked"]),REFUSED_GRANT_TOKEN=/(?<![a-z_])(invalid_grant|refresh_token_(?:expired|invalidated|reused)|token_revoked)(?![a-z_])/,CLIENT_FAULT_CODES=new Set(["invalid_client","invalid_request","invalid_scope","unauthorized_client","unsupported_grant_type"]),NETWORK_FAULT_CODES=new Set(["ECONNRESET","ECONNREFUSED","ECONNABORTED","ETIMEDOUT","EHOSTUNREACH","EHOSTDOWN","ENETUNREACH","ENETDOWN","ENETRESET","ENOTFOUND","EAI_AGAIN","EPIPE","EADDRNOTAVAIL","ERR_SOCKET_CONNECTION_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CLOSED","ConnectionRefused","ConnectionClosed","FailedToOpenSocket"]),AUTH_ERROR_CODES=new Set(["authentication_error","invalid_api_key","token_invalidated",...REFUSED_GRANT_CODES]),MAX_CAUSE_LINKS=16,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i,TEMPORARY_FAULT_TEXT=/time[ds]?[ _-]?out|timed out|disconnect|reset before|connection reset|gateway|temporarily|unavailable/i;function limitFromProviderCode(error){let diagnostic=readProviderDiagnostic(error);if(diagnostic?.evidence==="structured_code")switch(diagnostic.code){case"rate_limit_exceeded":return{kind:"throttle"};case"usage_limit_reached":case"usage_not_included":return diagnostic.resetsAt===void 0?{kind:"spent"}:{kind:"spent",resetsAt:diagnostic.resetsAt};default:return}}function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function failedRefresh(error){let seen=new Set;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof ModelsError)return error.code==="oauth"?error:void 0;error=Reflect.get(error,"cause")}}function oauthBodyErrorCode(message){let start=message.indexOf("{"),end=message.lastIndexOf("}");if(!(start<0||end<=start))try{let body=JSON.parse(message.slice(start,end+1));if(typeof body!="object"||body===null)return;let field=Reflect.get(body,"error");if(typeof field=="string")return field;if(typeof field=="object"&&field!==null){let code=Reflect.get(field,"code");return typeof code=="string"?code:void 0}return}catch{return}}function isRefusedGrant(refresh){let cause=refresh.cause;if(!(cause instanceof OAuthTokenEndpointError))return!1;let code=cause.oauthError??oauthBodyErrorCode(cause.message);return code!==void 0&&CLIENT_FAULT_CODES.has(code)?!1:cause.credentialRefused||cause.status===401?!0:code!==void 0&&REFUSED_GRANT_CODES.has(code)?[400,403,404].includes(cause.status):cause.status===400&&REFUSED_GRANT_TOKEN.test(cause.message)}function isRefreshNetworkFault(refresh,text){let seen=new Set,error=refresh.cause;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof OAuthTokenEndpointError)return!1;let code=Reflect.get(error,"code");if(typeof code=="string")return NETWORK_FAULT_CODES.has(code);error=Reflect.get(error,"cause")}return NETWORK_TEXT.test(text)}function hasAuthDiagnostic(error){let diagnostic=readProviderDiagnostic(error);return diagnostic===void 0?!1:diagnostic.category==="auth"||diagnostic.code!==void 0&&AUTH_ERROR_CODES.has(diagnostic.code)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){if(isOAuthRefreshUnavailableError(error))return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(error instanceof Error&&error.name==="AbortError")return{kind:"fail_request"};switch(siwcRecoveryFromDiagnostic(readProviderDiagnostic(error))){case"usage_limit":return{kind:"failover",block:{reason:"rate_limit",...rateLimitCooldown(failureCount,void 0,{baseMs:context.cooldownBaseMs,capMs:Math.min(context.cooldownCapMs??COOLDOWN_CAP_MS,30*6e4)})}};case"account_disabled":return{kind:"failover",block:{reason:"account_disabled"}};case"auth":return{kind:"failover",block:{reason:"auth_error"}};case"request":return{kind:"fail_request"};case"transient":return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};case void 0:break}if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(ACCOUNT_POOL_REFUSAL_NOTE))return{kind:"fail_request"};let providerFault=status===408||status!==void 0&&status>=500&&status<600||status===void 0&&(TEMPORARY_FAULT_TEXT.test(text)||NETWORK_TEXT.test(text)||OVERLOAD_TEXT.test(text)),codedLimit=limitFromProviderCode(error),usageLimit=codedLimit!==void 0?codedLimit.kind==="spent":isAccountUsageLimitText(text)&&!isOverflowText(text),limitText=codedLimit!==void 0||RATE_LIMIT_TEXT.test(text)||usageLimit;if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};let statusFault=status===408||status===429||status!==void 0&&status>=500&&status<600,refresh=failedRefresh(error);if(refresh!==void 0)return!statusFault&&isRefusedGrant(refresh)?{kind:"failover",block:{reason:"auth_error"}}:isRefreshNetworkFault(refresh,text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"};if(!providerFault&&status!==429&&hasAuthDiagnostic(error))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||!providerFault&&status!==429&&(INVALID_KEY_TEXT.test(text)||REVOKED_TOKEN_TEXT.test(text)))return{kind:"failover",block:{reason:"auth_error"}};if(status===403&&!limitText)return ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||!providerFault&&BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||limitText){let nowMs=context.nowMs??Date.now(),codedResetMs=codedLimit?.kind==="spent"&&codedLimit.resetsAt!==void 0?codedLimit.resetsAt-nowMs:void 0,codedReset=codedResetMs!==void 0&&codedResetMs>0?codedResetMs:void 0,hint=codedLimit?.kind==="throttle"?parseRetryAfterMsMarker(text):codedReset??extract429RetryAfterMs({status:status??429,bodyText:text},nowMs)??(usageLimit?normalized.retryAfterMs??usageLimitResetMs(text,nowMs):void 0),modelFamily=rateLimitModelFamily(text),policy={baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs};return{kind:"failover",block:{reason:"rate_limit",...usageLimit&&hint!==void 0&&hint>0?usageLimitCooldown(hint,policy):rateLimitCooldown(failureCount,hint,policy),...modelFamily===void 0?{}:{modelFamily}}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function coolingProbe(slots,attempted){if(attempted.size>0)return[];let soonest=slots.filter(slot=>slot.blockReason==="rate_limit"&&slot.blockedUntil!==void 0).reduce((best,slot)=>best===void 0||(slot.blockedUntil??0)<(best.blockedUntil??0)?slot:best,void 0);return soonest===void 0?[]:[soonest]}function attemptCandidates(slots,attempted,now){let available=slots.filter(slot=>!attempted.has(slot.name)&&isAvailable(slot,now));return available.length>0?available:coolingProbe(slots,attempted)}function noSlotsError(slots,now){let retryAt=soonestRetryAt(slots,now);return new CredentialFailoverError({kind:"fail_request"},new Error(noSlotsMessage(slots,now)),retryAt===void 0?{}:{retryAt})}function dueBack(epochMs){return`${localTime(epochMs)} (${new Date(epochMs).toISOString()})`}function localTime(epochMs){return new Date(epochMs).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function noSlotsMessage(slots,now){let blocked=slots.map(slot=>{let reason=slot.blockReason??"blocked";return slot.blockedUntil!==void 0&&slot.blockedUntil>now?`${slot.name} (${reason} until ${dueBack(slot.blockedUntil)})`:reason==="account_disabled"?`${slot.name} (account_disabled until re-login)`:`${slot.name} (${reason})`}),firstBack=soonestRetryAt(slots,now),step=firstBack===void 0?"Sign in again or add a new API key for this provider, or choose another model.":`Wait until ${localTime(firstBack)}, or choose another model.`;return blocked.length===0?`No credential slots available. ${step}`:`No credential slots available: ${blocked.join(", ")}. ${step}`}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1,unsettled;try{for(;;){let slots=await options.listSlots(),candidates=attemptCandidates(slots,attempted,now());if(candidates.length===0){if(lastTerminalEvent!==void 0){yield lastTerminalEvent;return}if(lastError===void 0||lastOriginal===void 0)throw noSlotsError(slots,now());let retryAt=soonestRetryAt(slots,now());throw new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt})}let slot=options.select(candidates);unsettled=slot;let committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}unsettled=void 0,await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts){unsettled=void 0,await options.releaseSlot?.(slot);continue}if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}unsettled=void 0,await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}finally{unsettled!==void 0&&await options.releaseSlot?.(unsettled)}}export{rendezvousOrder,applyAccountOrder,withoutOrderedAccount,isSlotBlocked,MAX_SLOT_BLOCK_MS,ACCOUNT_POOL_REFUSAL_NOTE,classifyCredentialFailure,CredentialFailoverError,isAvailable,attemptCandidates,noSlotsError,runCredentialFailover};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-UKSFF47T.js";import{envValue}from"./chunk-
|
|
3
|
-
`)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-
|
|
2
|
+
import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-UKSFF47T.js";import{envValue}from"./chunk-SODMQEHO.js";import{format}from"node:util";var OUTPUT_DELIVERY_LIMIT_MS=3e4,nativeLog=console.log,nativeStdoutWrite=process.stdout.write;async function captureStdout(print){if(console.log!==nativeLog||process.stdout.write!==nativeStdoutWrite)return{result:await print(),output:""};let chunks=[];console.log=(...args)=>{chunks.push(`${format(...args)}
|
|
3
|
+
`)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-PP7L2Q5M.js");return await handlePackageCommand(args,runtimeOptions)}async function dispatchConfigCommand(args,runtimeOptions={}){if(args[0]!==CONFIG_COMMAND_ARGV)return!1;let{handleConfigCommand}=await import("./package-manager-cli-PP7L2Q5M.js");return await handleConfigCommand(args,runtimeOptions)}async function dispatchHostCommand(args){if(args[0]!==HOST_COMMAND_ARGV)return;if(args[1]==="session"){let{runHostSessionCommand}=await import("./host-session-command-IPH3WXSG.js");return await runHostSessionCommand(args.slice(2))}let{runHostCommand}=await import("./host-command-KJXUTSQ7.js");return await runHostCommand(args.slice(1))}async function dispatchScheduleCommand(args){if(args[0]!==SCHEDULE_COMMAND_ARGV)return;let{runScheduleCommand}=await import("./schedule-command-ZNFEJNTT.js");return await runScheduleCommand(args.slice(1))}export{captureStdout,exitAfterOutput,printThenExit,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv,dispatchPackageCommand,dispatchConfigCommand,dispatchHostCommand,dispatchScheduleCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{appendDebugLogEntry}from"./chunk-
|
|
2
|
+
import{appendDebugLogEntry}from"./chunk-EBZ6IP4V.js";import{isRecoverableInspectorVmImportError}from"./chunk-6NPK2O3C.js";import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-UKSFF47T.js";function containStaleExtensionError(error,origin){if(!isStaleExtensionContextError(error))return!1;try{appendDebugLogEntry(`contained stale extension ctx (${origin})`,error.stack??error.message)}catch{}return!0}var installed=!1;function installStaleExtensionContainment(){installed||(installed=!0,process.on("uncaughtException",(error,origin)=>{containStaleExtensionError(error,origin??"uncaughtException")||hasModeCrashHandler("uncaughtException")||isRecoverableInspectorVmImportError(error,origin??"uncaughtException")||(console.error(error),process.exit(1))}))}export{containStaleExtensionError,installStaleExtensionContainment};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{applyAccountOrder,attemptCandidates,noSlotsError,rendezvousOrder}from"./chunk-6ISOXWH2.js";function pickRotationSlot(candidates,policy){let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let ranked=policy.useAffinity?rendezvousOrder(policy.affinityKey,candidates,policy.hasher):candidates;return applyAccountOrder(policy.order,ranked)[0]}function selectSessionSlot(slots,policy,now){if(slots.length===0)return;let candidates=attemptCandidates(slots,new Set,now);if(candidates.length===0)throw noSlotsError(slots,now);return pickRotationSlot(candidates,policy)}export{pickRotationSlot,selectSessionSlot};
|