@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,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{reportedCount}from"./chunk-GVSBCJFI.js";import{splitDeferredTools}from"./chunk-HK46JMSC.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-
|
|
2
|
+
import{reportedCount}from"./chunk-GVSBCJFI.js";import{splitDeferredTools}from"./chunk-HK46JMSC.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-2PGSRQBF.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{calculateCost,getCurrentTools,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,supportsConfigurationUpdate}from"./chunk-AVP6DDBF.js";import{enableAssistantCapture,pushAssistantProgress}from"./chunk-5CSZPC55.js";function isOpenAIResponsesPromptCacheModel(model){if(model.api!=="openai-responses"||model.compat?.supportsExplicitPromptCacheMode!==!0)return!1;try{return new URL(model.baseUrl||"https://api.openai.com/v1").hostname==="api.openai.com"}catch{return!1}}function findPromptCacheComparisonResponseId(model,messages){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role==="assistant"&&!(message.api!==model.api||message.provider!==model.provider||message.model!==model.id)&&!(message.stopReason==="error"||message.stopReason==="aborted")&&typeof message.responseId=="string"&&message.responseId.length>0)return message.responseId.startsWith("resp")?message.responseId:void 0}}function withPromptCacheComparison(options,comparisonResponseId){return comparisonResponseId===void 0?options:{...options,comparison_response_id:comparisonResponseId}}function finiteCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:void 0}function parsePromptCacheDiagnostics(raw){if(typeof raw!="object"||raw===null)return;let record=raw;if(typeof record.type!="string"||record.type.length===0)return;let diagnostics={type:record.type};typeof record.reason=="string"&&(diagnostics.reason=record.reason);let cacheMissedTokens=finiteCount(record.cache_missed_tokens);cacheMissedTokens!==void 0&&(diagnostics.cacheMissedTokens=cacheMissedTokens);let comparisonReusableTokens=finiteCount(record.comparison_reusable_tokens);return comparisonReusableTokens!==void 0&&(diagnostics.comparisonReusableTokens=comparisonReusableTokens),diagnostics}var CONTEXT_PROVENANCE_FIELD="__piContextProvenance";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function getContextProvenance(value){if(!isRecord(value))return;let provenance=value[CONTEXT_PROVENANCE_FIELD];return isRecord(provenance)?provenance:void 0}function copyContextProvenance(source,target){let provenance=getContextProvenance(source);return provenance?Object.assign(target,{[CONTEXT_PROVENANCE_FIELD]:provenance}):target}function contextProvenanceFingerprint(value){if(!isRecord(value))return;let clone={...value};return delete clone[CONTEXT_PROVENANCE_FIELD],JSON.stringify(clone)}function formatResponsesCompletionStall(graceMs){return`Provider stream stalled after the last output item: response.completed timed out after ${graceMs}ms`}var ResponsesCompletionStallError=class extends Error{constructor(graceMs){super(formatResponsesCompletionStall(graceMs)),this.name="ResponsesCompletionStallError",this.graceMs=graceMs}},GRACE_EXPIRED=Symbol("responses-completion-grace-expired");function withResponsesCompletionGrace(source,graceMs=6e4){return{[Symbol.asyncIterator](){let iterator=source[Symbol.asyncIterator](),openItems=0,sawItemDone=!1,finished=!1,observe=event=>{event.type==="response.output_item.added"?openItems++:event.type==="response.output_item.done"&&(openItems=Math.max(0,openItems-1),sawItemDone=!0)},boundedNext=async()=>{let next=iterator.next();if(!sawItemDone||openItems>0||graceMs<=0)return next;let timer,deadline=new Promise(resolve=>{timer=setTimeout(()=>resolve(GRACE_EXPIRED),graceMs)});try{let winner=await Promise.race([next,deadline]);if(winner===GRACE_EXPIRED)throw finished=!0,iterator.return?.().catch(()=>{}),new ResponsesCompletionStallError(graceMs);return winner}finally{timer!==void 0&&clearTimeout(timer)}};return{async next(){if(finished)return{done:!0,value:void 0};let result=await boundedNext();return result.done?finished=!0:observe(result.value),result},async return(value){return finished=!0,await iterator.return?.(value),{done:!0,value:void 0}},async throw(error){if(finished=!0,iterator.throw)return iterator.throw(error);throw error}}}}}function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function parseReasoningSignature(signature){if(signature)try{let parsed=JSON.parse(signature);return parsed?.type==="reasoning"?parsed:void 0}catch{return}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
3
3
|
`),images=content.filter(c=>c.type==="image"),hasText=textResult.length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}var CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL="custom";function isResponseCustomToolCallItem(item){return item.type==="custom_tool_call"}function isFreeformTool(tool){return tool.freeform!==void 0}function isFreeformToolName(toolName,tools){return tools?.some(tool=>tool.name===toolName&&isFreeformTool(tool))??!1}function getFreeformToolInput(argumentsValue){return typeof argumentsValue.input=="string"?argumentsValue.input:JSON.stringify(argumentsValue)}function contextProvenanceForInput(message,seal){let provenance=getContextProvenance(message);if(!provenance)return;let fingerprint=contextProvenanceFingerprint(message);if(fingerprint===void 0)return;let stored=provenance.integrity;return stored===void 0&&seal?(provenance.integrity=fingerprint,provenance):stored===fingerprint?provenance:void 0}function withContextProvenance(item,message,seal){let provenance=contextProvenanceForInput(message,seal);return provenance&&Object.defineProperty(item,CONTEXT_PROVENANCE_FIELD,{value:provenance,enumerable:!1}),item}function resolveResponsesDeferredToolsMode(compat){return compat?.supportsAdditionalTools?"additional-tools":compat?.supportsToolSearch?"tool-search":void 0}function resolveResponsesToolPlacement(messages,supportsToolAdditions){let transcriptTools=resolveTranscriptTools(messages,supportsToolAdditions),{deferred}=splitDeferredTools({messages:[...messages],tools:getCurrentTools(messages)},supportsToolAdditions);return{requestTools:transcriptTools.requestTools.filter(tool=>!deferred.has(tool.name)),anchorsAdditions:transcriptTools.anchorsAdditions,deferred}}function convertResponsesMessages(model,context,allowedToolCallProviders,options){let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],deferredToolsMode=resolveResponsesDeferredToolsMode(options),toolPlacement=resolveResponsesToolPlacement(normalizedContext.messages,deferredToolsMode!==void 0),declaredTools=getDeclaredTools(normalizedContext.messages),loadedToolNames=new Set,normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId);if(itemId===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL)return`${normalizedCallId}|${CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`;if(!allowedToolCallProviders.has(model.provider))return normalizeIdPart(id);let normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(normalizedContext.messages,model,normalizeToolCallId,{preserveThinking:options?.preserveThinking,preserveTextSignatures:options?.preserveTextSignatures}),appendSystemToolAdditions=(message,seed)=>{let tools=toolPlacement.anchorsAdditions?(message.toolsAdded??[]).filter(tool=>!loadedToolNames.has(tool.name)):[];if(tools.length===0)return;for(let tool of tools)loadedToolNames.add(tool.name);if(options?.supportsAdditionalTools){messages.push({type:"additional_tools",role:"developer",tools:convertResponsesTools(tools,options.toolOptions)});return}if(!options?.supportsToolSearch)return;let names=tools.map(tool=>tool.name),callId=`pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;messages.push({type:"tool_search_call",call_id:callId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}}),messages.push({type:"tool_search_output",call_id:callId,execution:"client",status:"completed",tools:convertResponsesTools(tools,{...options.toolOptions,toolSearchResult:!0})})},includeInitialSystemMessage=options?.includeSystemPrompt??!0,compat=model.compat,instructionRole=model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",msgIndex=0,sourceIndex=0;for(let msg of transformedMessages){let isLeadingSystemMessage=sourceIndex++===0&&msg.role==="system";if(msg.role==="configurationUpdate"){if(!supportsConfigurationUpdate(model))continue;messages[messages.length-1]?.type==="configuration_update"?messages[messages.length-1]={type:"configuration_update",reasoning:{effort:msg.effort}}:messages.push({type:"configuration_update",reasoning:{effort:msg.effort}});continue}if(msg.role==="system"){if(isLeadingSystemMessage||appendSystemToolAdditions(msg,`system:${msgIndex}`),!isLeadingSystemMessage||includeInitialSystemMessage){let text=isLeadingSystemMessage?getSystemMessageText(msg):renderSystemMessageUpdate(msg);if(text.length>0&&isLeadingSystemMessage&&options?.systemPromptCacheBreakpoint===!0){let block={type:"input_text",text:sanitizeSurrogates(text),prompt_cache_breakpoint:{mode:"explicit"}};messages.push({role:instructionRole,content:[block]})}else text.length>0&&messages.push({role:instructionRole,content:sanitizeSurrogates(text)})}}else if(msg.role==="user")if(typeof msg.content=="string")messages.push(withContextProvenance({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]},msg,options?.sealContextProvenance));else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push(withContextProvenance({role:"user",content},msg,options?.sealContextProvenance))}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0,pushAssistantText=(text,textSignature)=>{let parsedSignature=parseTextSignature(textSignature),fallbackMessageId=textBlockIndex===0?`msg_pi_${msgIndex}`:`msg_pi_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})};for(let block of msg.content)if(block.type==="thinking"){let reasoningItem=parseReasoningSignature(block.thinkingSignature);reasoningItem?output.push(reasoningItem):block.thinkingSignature&&block.thinking.trim()!==""&&pushAssistantText(block.thinking)}else if(block.type==="providerNative"){let raw=block.raw;isSameModel&&block.subtype==="web_search_call"&&raw!==null&&typeof raw=="object"&&"type"in raw&&raw.type==="web_search_call"&&"id"in raw&&typeof raw.id=="string"&&"action"in raw&&"status"in raw&&(raw.status==="completed"||raw.status==="failed")&&output.push(raw)}else if(block.type==="text"){let textBlock=block;pushAssistantText(textBlock.text,textBlock.textSignature)}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL,isFreeform=isFreeformToolName(toolCall.name,declaredTools)||isPersistedFreeform,itemId=isPersistedFreeform?void 0:itemIdRaw,itemIdPrefix=customInputProperty===void 0?"fc_":"ctc_";(isDifferentModel||!itemId?.startsWith(itemIdPrefix))&&(itemId=void 0);let canReplayNamespace=isSameModel||toolPlacement.deferred.has(toolCall.name);customInputProperty!==void 0?output.push({type:"custom_tool_call",...itemId!==void 0?{id:itemId}:{},call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):isFreeform?output.push({type:"custom_tool_call",call_id:callId,name:toolCall.name,input:getFreeformToolInput(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",...itemId?.startsWith("fc_")?{id:itemId}:{},call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}if(output.length===0)continue;messages.push(...output.map(item=>withContextProvenance(item,msg,options?.sealContextProvenance)))}else if(msg.role==="toolResult"){let[callId,itemIdRaw]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content),customInputProperty=options?.grammarToolInputProperties?.get(msg.toolName),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;customInputProperty!==void 0?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,output},msg,options?.sealContextProvenance)):isFreeformToolName(msg.toolName,declaredTools)||isPersistedFreeform?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,name:msg.toolName,output},msg,options?.sealContextProvenance)):messages.push(withContextProvenance({type:"function_call_output",call_id:callId,output},msg,options?.sealContextProvenance));let deferredTools=[];for(let name of msg.addedToolNames??[]){let tool=toolPlacement.deferred.get(name);!tool||loadedToolNames.has(name)||(loadedToolNames.add(name),deferredTools.push(tool))}if(deferredTools.length>0&&deferredToolsMode==="additional-tools")messages.push(withContextProvenance({type:"additional_tools",role:"developer",tools:convertResponsesTools(deferredTools,options?.toolOptions)},msg,options?.sealContextProvenance));else if(deferredTools.length>0&&deferredToolsMode==="tool-search"){let names=deferredTools.map(tool=>tool.name),searchCallId=`pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(",")}`)}`;messages.push(withContextProvenance({type:"tool_search_call",call_id:searchCallId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}},msg,options?.sealContextProvenance)),messages.push(withContextProvenance({type:"tool_search_output",call_id:searchCallId,execution:"client",status:"completed",tools:convertResponsesTools(deferredTools,{...options?.toolOptions,toolSearchResult:!0})},msg,options?.sealContextProvenance))}}isLeadingSystemMessage||msgIndex++}return messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return[...tools].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0).map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.toolSearchResult?{defer_loading:!0}:{}};if(tool.freeform)return{type:"custom",name:tool.name,description:tool.description,format:tool.freeform,...options?.toolSearchResult?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.toolSearchResult?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}function getCustomToolCallInput(block){let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""}function appendCustomToolCallInput(block,nextInput,close){let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta}var MAX_NATIVE_IMAGE_BASE64_CHARS=24*1024*1024;function readNativeImageGenerationCall(value){if(!(typeof value!="object"||value===null||!("type"in value)||!("status"in value))&&!(value.type!=="image_generation_call"||typeof value.status!="string"))return{type:"image_generation_call",..."id"in value&&typeof value.id=="string"?{id:value.id}:{},status:value.status,..."result"in value&&(typeof value.result=="string"||value.result===null)?{result:value.result}:{},..."revised_prompt"in value&&typeof value.revised_prompt=="string"?{revised_prompt:value.revised_prompt}:{}}}function isValidBase64(value){return value.length>0&&value.length%4===0&&/^[A-Za-z0-9+/]*={0,2}$/.test(value)}function reconcileNativeImageGenerationCall(item){return item.status!=="completed"?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:item.status}:typeof item.result!="string"||!isValidBase64(item.result)?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"}:{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"completed",result:item.result,...item.revised_prompt?.trim()?{revised_prompt:item.revised_prompt}:{}}}async function processResponsesStream(openaiStream,output,stream,model,options){enableAssistantCapture(stream);let sawTerminalResponseEvent=!1,nativeImageBase64Chars=0,outputSlots=new Map,reasoningBlocksById=new Map,nativeImageCharsByOutputIndex=new Map,finalizedNativeImageOutputIndexes=new Set,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block2={type:"thinking",thinking:""};output.content.push(block2);let slot2={type:"thinking",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"thinking_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="message"){applyMessagePhaseStopReason(item);let block2={type:"text",text:""};output.content.push(block2);let slot2={type:"text",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"text_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="function_call"){let block2={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{},...item.namespace!==void 0?{namespace:item.namespace}:{},partialJson:item.arguments||""};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output},{rawArgumentPrefix:block2.partialJson}),slot2}if(isResponseCustomToolCallItem(item)){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block2={type:"toolCall",id:`${item.call_id}|${item.id??CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{},customInput:{property:inputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output}),slot2}let imageItem=readNativeImageGenerationCall(item),block={type:"providerNative",subtype:item.type,raw:imageItem?reconcileNativeImageGenerationCall(imageItem):item},slot={type:"providerNative",block,contentIndex:output.content.length};return imageItem&&reconcileNativeImageSlot(outputIndex,slot,imageItem),output.content.push(block),outputSlots.set(outputIndex,slot),pushAssistantProgress(stream,{type:"message_block_state",contentIndex:slot.contentIndex,phase:"insert",block}),slot},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item);function scrubNativeImageResults(){for(let block of output.content){if(block.type!=="providerNative"||block.subtype!=="image_generation_call")continue;let item=readNativeImageGenerationCall(block.raw);typeof item?.result=="string"&&(block.raw={type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"})}nativeImageBase64Chars=0,nativeImageCharsByOutputIndex.clear()}function reconcileNativeImageSlot(outputIndex,slot,item){let reconciled=reconcileNativeImageGenerationCall(item),previousChars=nativeImageCharsByOutputIndex.get(outputIndex)??0,nextChars=typeof reconciled.result=="string"?reconciled.result.length:0,nextTotal=nativeImageBase64Chars-previousChars+nextChars;if(nextTotal>MAX_NATIVE_IMAGE_BASE64_CHARS)throw scrubNativeImageResults(),new Error("Native image generation results exceed the 24 MiB base64 limit");nativeImageBase64Chars=nextTotal,nextChars>0?nativeImageCharsByOutputIndex.set(outputIndex,nextChars):nativeImageCharsByOutputIndex.delete(outputIndex),slot.block.subtype="image_generation_call",slot.block.raw=reconciled}let backfillNativeImageGenerationCalls=responseOutput=>{for(let[outputIndex,outputItem]of responseOutput.entries()){if(finalizedNativeImageOutputIndexes.has(outputIndex))continue;let imageItem=readNativeImageGenerationCall(outputItem);if(!imageItem)continue;let existingSlot=getSlot(outputIndex,"providerNative"),slot=existingSlot??createSlot(outputIndex,outputItem);existingSlot&&reconcileNativeImageSlot(outputIndex,existingSlot,imageItem),slot&&pushAssistantProgress(stream,{type:"message_block_state",contentIndex:slot.contentIndex,phase:"end",block:slot.block}),outputSlots.delete(outputIndex)}},backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=parseReasoningSignature(block.thinkingSignature);!storedItem||storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),backfillNativeImageGenerationCalls(response.output??[]),response?.id&&(output.responseId=response.id);let promptCacheDiagnostics=parsePromptCacheDiagnostics(response?.prompt_cache_diagnostics);if(promptCacheDiagnostics&&(output.promptCacheDiagnostics=promptCacheDiagnostics),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens??inputDetails?.cache_creation_tokens??0,reasoning=reportedCount(response.usage.output_tokens_details?.reasoning_tokens);output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,...reasoning===void 0?{}:{reasoning},totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of withResponsesCompletionGrace(openaiStream))if(await options?.onProviderStreamEvent?.(event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
|
|
4
4
|
|
|
5
5
|
`,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
|
|
@@ -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{peekProviderDiagnostic,siwcErrorForCode}from"./chunk-3SASTB6Y.js";var PROVIDER_DIAGNOSTIC_MAX_BYTES=512;function categoryForProviderCode(code){let siwc=siwcErrorForCode(code);if(siwc!==void 0)return siwc.category;switch(code){case"authentication_error":case"invalid_api_key":case"account_pool_auth_blocked":return"auth";case"rate_limit_error":case"rate_limit_exceeded":case"account_pool_blocked":return"rate_limit";case"insufficient_quota":case"exceeded_current_quota_error":case"usage_limit_reached":case"usage_not_included":return"quota";case"context_length_exceeded":return"context_limit";case"invalid_request_error":return"invalid_request";case"overloaded_error":case"api_error":case"timeout_error":return"provider_unavailable";case"billing_error":case"permission_error":case"not_found_error":return"unknown";default:return}}var TLS_CHAIN_VERIFICATION_CODES=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_UNTRUSTED"]);function isTlsChainVerificationCode(code){return TLS_CHAIN_VERIFICATION_CODES.has(code)}function categoryForTransportCode(code){switch(code){case"ECONNRESET":case"ECONNREFUSED":case"ETIMEDOUT":case"ENOTFOUND":case"EAI_AGAIN":case"EPIPE":case"UND_ERR_SOCKET":case"UND_ERR_CONNECT_TIMEOUT":case"UND_ERR_HEADERS_TIMEOUT":case"UND_ERR_BODY_TIMEOUT":case"UND_ERR_CLOSED":case"APIConnectionError":case"APIConnectionTimeoutError":return"network";default:return isTlsChainVerificationCode(code)?"network":void 0}}function isProviderCodeStatusCompatible(code,status){let siwc=siwcErrorForCode(code);if(siwc!==void 0)return status===siwc.status;switch(code){case"authentication_error":case"invalid_api_key":return status===401;case"rate_limit_error":case"rate_limit_exceeded":case"insufficient_quota":case"exceeded_current_quota_error":case"usage_limit_reached":case"usage_not_included":return status===429;case"context_length_exceeded":case"invalid_request_error":return status===400;case"overloaded_error":case"api_error":case"timeout_error":return status>=500&&status<=599;case"billing_error":return status===402;case"permission_error":return status===403;case"not_found_error":return status===404;default:return!1}}var OPAQUE_PROVIDER_CODE=/^[a-z]+(?:[_.][a-z]+)*$/,OPAQUE_PROVIDER_CODE_MAX_LENGTH=64;function isOpaqueProviderCode(code){return code.length<=OPAQUE_PROVIDER_CODE_MAX_LENGTH&&OPAQUE_PROVIDER_CODE.test(code)&&categoryForProviderCode(code)===void 0}function isProviderDiagnosticResetsAt(value){return typeof value=="number"&&Number.isInteger(value)&&value>9466848e5&&value<41024448e5}function categoryForProviderStatus(status){return status===401?"auth":status===400?"invalid_request":status>=500&&status<=599?"provider_unavailable":"unknown"}function isProviderDiagnosticStatus(value){return typeof value=="number"&&Number.isInteger(value)&&value>=400&&value<=599}function isProviderDiagnosticCategory(value){switch(value){case"auth":case"rate_limit":case"quota":case"context_limit":case"invalid_request":case"provider_unavailable":case"network":case"unknown":return!0;default:return!1}}function buildProviderDiagnostic(input){let diagnostic={category:input.category,evidence:input.evidence};return input.httpStatus!==void 0&&(diagnostic.httpStatus=input.httpStatus),input.code!==void 0&&(diagnostic.code=input.code),input.route!==void 0&&(diagnostic.route=input.route),input.resetsAt!==void 0&&(input.category==="quota"||input.category==="rate_limit")&&(diagnostic.resetsAt=input.resetsAt),new TextEncoder().encode(JSON.stringify(diagnostic)).length<=PROVIDER_DIAGNOSTIC_MAX_BYTES?diagnostic:void 0}function classifyProviderFailure(facts){let statusSupplied=facts.status!==void 0&&facts.status!==null;if(statusSupplied&&!isProviderDiagnosticStatus(facts.status))return;let status=statusSupplied&&isProviderDiagnosticStatus(facts.status)?facts.status:void 0,category=facts.code===void 0?void 0:categoryForProviderCode(facts.code);if(facts.code!==void 0&&category!==void 0)return status!==void 0&&!isProviderCodeStatusCompatible(facts.code,status)?void 0:buildProviderDiagnostic({category,...status===void 0?{}:{httpStatus:status},code:facts.code,evidence:"structured_code"});if(status!==void 0)return buildProviderDiagnostic({category:categoryForProviderStatus(status),httpStatus:status,evidence:"structured_status"})}function readField(value,key){return Reflect.get(value,key)}function sanitizeProviderDiagnostic(value){try{if(typeof value!="object"||value===null||Array.isArray(value))return;let category=readField(value,"category"),evidence=readField(value,"evidence"),httpStatus=readField(value,"httpStatus"),code=readField(value,"code"),resetsAt=readField(value,"resetsAt"),route=readField(value,"route");if(route!==void 0&&route!=="siwc")return;let routed=route==="siwc"?{route}:{};if(!isProviderDiagnosticCategory(category)||httpStatus!==void 0&&!isProviderDiagnosticStatus(httpStatus)||resetsAt!==void 0&&!isProviderDiagnosticResetsAt(resetsAt))return;let reset=resetsAt===void 0?{}:{resetsAt};return evidence==="structured_status"?code!==void 0||!isProviderDiagnosticStatus(httpStatus)||category!==categoryForProviderStatus(httpStatus)?void 0:buildProviderDiagnostic({category,httpStatus,evidence,...reset,...routed}):evidence==="structured_transport"?httpStatus!==void 0||typeof code!="string"||categoryForTransportCode(code)!==category?void 0:buildProviderDiagnostic({category,code,evidence}):evidence!=="structured_code"||typeof code!="string"?void 0:isOpaqueProviderCode(code)?category!=="unknown"||httpStatus!==void 0?void 0:buildProviderDiagnostic({category,code,evidence}):categoryForProviderCode(code)!==category||httpStatus!==void 0&&!isProviderCodeStatusCompatible(code,httpStatus)?void 0:buildProviderDiagnostic({category,...httpStatus===void 0?{}:{httpStatus},code,evidence,...reset,...routed})}catch{return}}function readProviderDiagnostic(error){return sanitizeProviderDiagnostic(peekProviderDiagnostic(error))}export{PROVIDER_DIAGNOSTIC_MAX_BYTES,categoryForProviderCode,isTlsChainVerificationCode,categoryForTransportCode,isOpaqueProviderCode,isProviderDiagnosticResetsAt,isProviderDiagnosticStatus,buildProviderDiagnostic,classifyProviderFailure,sanitizeProviderDiagnostic,readProviderDiagnostic};
|
|
@@ -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{source_default}from"./chunk-26UBFF6N.js";import{legacyProviderIdRejection}from"./chunk-TBARMJ75.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,brandEnvNames,envValue}from"./chunk-ISZ4EWIS.js";function isSpawnedBy(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&"parentSessionId"in value&&typeof value.parentSessionId=="string"&&value.parentSessionId.length>0&&"rootSessionId"in value&&typeof value.rootSessionId=="string"&&value.rootSessionId.length>0&&"taskId"in value&&typeof value.taskId=="string"&&value.taskId.length>0}function applyAttachArgs(args){let value=args.unknownFlags.get("attach");if(value===void 0)return;args.unknownFlags.delete("attach");let error=message=>args.diagnostics.push({type:"error",message});if(typeof value!="string"||value.length===0){error("--attach requires a local RPC endpoint address");return}args.attach=value,args.mode&&args.mode!=="text"&&error("--attach is interactive and cannot be combined with --mode rpc or json"),!args.session&&!args.help&&!args.version&&error("--attach requires --session <ref>"),(args.print||args.readStdin||args.messages.length||args.fileArgs.length)&&error("--attach needs interactive input; omit --print, stdin input, prompt arguments and @files"),(args.continue||args.resume||args.fork||args.rebind||args.sessionId||args.noSession||args.listen||args.multiSession)&&error("--attach selects an existing session; omit session creation, resume and listener options"),(args.provider||args.model||args.apiKey||args.systemPrompt||args.appendSystemPrompt||args.export)&&error("--attach uses the endpoint's session configuration; omit model, prompt configuration and export options")}function isGrokNeoEnabled(env=process.env){let value=envValue("ENABLE_GROK_NEO",env);if(value===void 0)return!1;let normalized=value.trim().toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"}var TOOL_RUNTIMES=["in-process","child"];function isToolRuntimeKind(value){return TOOL_RUNTIMES.some(kind=>kind===value)}var TOOL_RUNTIME_ENV_SUFFIX="TOOL_RUNTIME",TOOL_CHILD_PLACEMENTS=["launch-barrier","job-policy","hostcall","offload","terminal"],OFFLOAD_API_CAPABILITY="offload_api";function toolRuntimeCapabilities(runtime){return[toolRuntimeCapability(runtime),...runtime==="child"?TOOL_CHILD_PLACEMENTS.map(name=>`placement:${name}`):[],OFFLOAD_API_CAPABILITY]}function isHostOwnedToolRuntimeCapability(capability){return capability.startsWith("tool_runtime:")||capability.startsWith("placement:")||capability===OFFLOAD_API_CAPABILITY}function toolRuntimeCapability(runtime){return`tool_runtime:${runtime}`}var TOOL_RUNTIME_UNSUPPORTED_HOST="tool_runtime_unsupported_host";function toolRuntimeHostRefusal(runtime,platform=process.platform,hasFfi=()=>process.getBuiltinModule("bun:ffi")!==void 0){if(!(runtime!=="child"||platform!=="win32"||hasFfi()))return`${TOOL_RUNTIME_UNSUPPORTED_HOST}: --tool-runtime child on Windows needs the Bun runtime (bun:ffi holds the tool child in a Job Object); run senpi under Bun or use in-process`}var ToolRuntimeUnsupportedHostError=class extends Error{constructor(message){super(message),this.code=TOOL_RUNTIME_UNSUPPORTED_HOST,this.name="ToolRuntimeUnsupportedHostError"}};function resolveToolRuntime(parsed,env=process.env,platform=process.platform,hasFfi){let resolved=resolveRequestedToolRuntime(parsed,env);if(!resolved.ok)return resolved;let refusal=toolRuntimeHostRefusal(resolved.value,platform,hasFfi);return refusal===void 0?resolved:{ok:!1,message:refusal}}function resolveRequestedToolRuntime(parsed,env){if(parsed.toolRuntime!==void 0)return{ok:!0,value:parsed.toolRuntime};let fromEnv=envValue(TOOL_RUNTIME_ENV_SUFFIX,env);return fromEnv===void 0||fromEnv===""?{ok:!0,value:"in-process"}:isToolRuntimeKind(fromEnv)?{ok:!0,value:fromEnv}:{ok:!1,message:`${brandEnvNames(TOOL_RUNTIME_ENV_SUFFIX).find(candidate=>env[candidate]!==void 0)??TOOL_RUNTIME_ENV_SUFFIX} (--tool-runtime) must be in-process or child, got ${JSON.stringify(fromEnv)}`}}var SESSION_RUNTIMES=["in-process","worker"];function isSessionRuntimeKind(value){return SESSION_RUNTIMES.some(runtime=>runtime===value)}function resolveSessionRuntime(parsed){return parsed.sessionRuntime?parsed.sessionRuntime:parsed.listen!==void 0&&parsed.listen!=="stdio://"?"in-process":"worker"}var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.some(candidate=>candidate===level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseArgs(args,options={}){let grokNeoEnabled=options.grokNeoEnabled??isGrokNeoEnabled(),result={messages:[],fileArgs:[],unknownFlags:new Map,diagnostics:[]};if(args[0]==="app-server")return result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`}),result;let hasRetiredCommand=!1;for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"){let mode=args[i+1];if(mode===void 0||mode.startsWith("-")){result.diagnostics.push({type:"error",message:"--mode requires text, json, or rpc"});continue}if(i++,mode!=="text"&&mode!=="json"&&mode!=="rpc"){result.diagnostics.push({type:"error",message:`Invalid mode "${mode}". Valid values: text, json, rpc`});continue}result.mode=mode}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length){let typedProvider=args[++i],rejection=typedProvider===void 0?void 0:legacyProviderIdRejection(typedProvider);if(rejection)throw new Error(rejection);result.provider=typedProvider}else if(arg==="--model"&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--spawned-by"){let value=args[i+1];if(value===void 0||value.startsWith("-"))result.diagnostics.push({type:"error",message:"--spawned-by requires a JSON object"});else{i++;try{let ancestry=JSON.parse(value);isSpawnedBy(ancestry)?result.spawnedBy=ancestry:result.diagnostics.push({type:"error",message:"--spawned-by requires non-empty parentSessionId, rootSessionId, and taskId strings"})}catch(error){if(!(error instanceof SyntaxError))throw error;result.diagnostics.push({type:"error",message:"--spawned-by must be valid JSON"})}}}else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--rebind"&&i+1<args.length)result.rebind=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if((arg==="--extension"||arg==="-e")&&i+1<args.length)result.extensions=result.extensions??[],result.extensions.push(args[++i]);else if(arg==="--no-extensions"||arg==="-ne")result.noExtensions=!0;else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--print-prompt-sizes")result.printPromptSizes=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--list-tips")result.listTips=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else if(arg==="--verbose")result.verbose=!0;else if(arg==="--approve"||arg==="-a")result.projectTrustOverride=!0;else if(arg==="--no-approve"||arg==="-na")result.projectTrustOverride=!1;else if(arg==="--offline")result.offline=!0;else if(grokNeoEnabled&&arg==="--grok-neo")result.grokNeo=!0;else if(arg==="--multi-session")result.multiSession=!0;else if(arg==="--mcp-presenter-fd")args[++i]==="4"?result.presenterBootstrapFd=4:result.diagnostics.push({type:"error",message:"Invalid presenter bootstrap descriptor"});else if(arg==="--mcp-presenter-enforcement")result.mcpPresenterEnforcement=!0;else if(arg==="--auto-title-sessions")result.autoTitleSessions=!0;else if(arg==="--session-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isSessionRuntimeKind(value)?result.sessionRuntime=value:result.diagnostics.push({type:"error",message:"--session-runtime must be in-process or worker"})}else if(arg==="--tool-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isToolRuntimeKind(value)?result.toolRuntime=value:result.diagnostics.push({type:"error",message:"--tool-runtime must be in-process or child"})}else if(arg==="--listen"&&result.mode==="rpc"){let value=args[i+1];value===void 0||value.startsWith("--")?result.diagnostics.push({type:"error",message:"--listen requires a value"}):(result.listen=value,result.multiSession=!0,i++)}else if(arg.startsWith("@"))result.fileArgs.push(arg.slice(1));else if(arg.startsWith("--")){let eqIndex=arg.indexOf("=");if(eqIndex!==-1)result.unknownFlags.set(arg.slice(2,eqIndex),arg.slice(eqIndex+1));else{let flagName=arg.slice(2),next=args[i+1];next!==void 0&&!next.startsWith("-")&&!next.startsWith("@")?(result.unknownFlags.set(flagName,next),i++):result.unknownFlags.set(flagName,!0)}}else arg==="-"?result.readStdin=!0:arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||(result.messages.length===0&&arg==="app-server"&&(hasRetiredCommand=!0),result.messages.push(arg))}return hasRetiredCommand&&result.mode===void 0&&!result.print&&(result.messages=[],result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`})),applyAttachArgs(result),result}function printHelp(extensionFlags,grokNeoEnabled=isGrokNeoEnabled()){let extensionFlagsText=extensionFlags&&extensionFlags.length>0?`
|
|
2
|
+
import{source_default}from"./chunk-26UBFF6N.js";import{legacyProviderIdRejection}from"./chunk-AVP6DDBF.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,brandEnvNames,envValue}from"./chunk-SODMQEHO.js";function isSpawnedBy(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&"parentSessionId"in value&&typeof value.parentSessionId=="string"&&value.parentSessionId.length>0&&"rootSessionId"in value&&typeof value.rootSessionId=="string"&&value.rootSessionId.length>0&&"taskId"in value&&typeof value.taskId=="string"&&value.taskId.length>0}function applyAttachArgs(args){let value=args.unknownFlags.get("attach");if(value===void 0)return;args.unknownFlags.delete("attach");let error=message=>args.diagnostics.push({type:"error",message});if(typeof value!="string"||value.length===0){error("--attach requires a local RPC endpoint address");return}args.attach=value,args.mode&&args.mode!=="text"&&error("--attach is interactive and cannot be combined with --mode rpc or json"),!args.session&&!args.help&&!args.version&&error("--attach requires --session <ref>"),(args.print||args.readStdin||args.messages.length||args.fileArgs.length)&&error("--attach needs interactive input; omit --print, stdin input, prompt arguments and @files"),(args.continue||args.resume||args.fork||args.rebind||args.sessionId||args.noSession||args.listen||args.multiSession)&&error("--attach selects an existing session; omit session creation, resume and listener options"),(args.provider||args.model||args.apiKey||args.systemPrompt||args.appendSystemPrompt||args.export)&&error("--attach uses the endpoint's session configuration; omit model, prompt configuration and export options")}function isGrokNeoEnabled(env=process.env){let value=envValue("ENABLE_GROK_NEO",env);if(value===void 0)return!1;let normalized=value.trim().toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"}var TOOL_RUNTIMES=["in-process","child"];function isToolRuntimeKind(value){return TOOL_RUNTIMES.some(kind=>kind===value)}var TOOL_RUNTIME_ENV_SUFFIX="TOOL_RUNTIME",TOOL_CHILD_PLACEMENTS=["launch-barrier","job-policy","hostcall","offload","terminal"],OFFLOAD_API_CAPABILITY="offload_api";function toolRuntimeCapabilities(runtime){return[toolRuntimeCapability(runtime),...runtime==="child"?TOOL_CHILD_PLACEMENTS.map(name=>`placement:${name}`):[],OFFLOAD_API_CAPABILITY]}function isHostOwnedToolRuntimeCapability(capability){return capability.startsWith("tool_runtime:")||capability.startsWith("placement:")||capability===OFFLOAD_API_CAPABILITY}function toolRuntimeCapability(runtime){return`tool_runtime:${runtime}`}var TOOL_RUNTIME_UNSUPPORTED_HOST="tool_runtime_unsupported_host";function toolRuntimeHostRefusal(runtime,platform=process.platform,hasFfi=()=>process.getBuiltinModule("bun:ffi")!==void 0){if(!(runtime!=="child"||platform!=="win32"||hasFfi()))return`${TOOL_RUNTIME_UNSUPPORTED_HOST}: --tool-runtime child on Windows needs the Bun runtime (bun:ffi holds the tool child in a Job Object); run senpi under Bun or use in-process`}var ToolRuntimeUnsupportedHostError=class extends Error{constructor(message){super(message),this.code=TOOL_RUNTIME_UNSUPPORTED_HOST,this.name="ToolRuntimeUnsupportedHostError"}};function resolveToolRuntime(parsed,env=process.env,platform=process.platform,hasFfi){let resolved=resolveRequestedToolRuntime(parsed,env);if(!resolved.ok)return resolved;let refusal=toolRuntimeHostRefusal(resolved.value,platform,hasFfi);return refusal===void 0?resolved:{ok:!1,message:refusal}}function resolveRequestedToolRuntime(parsed,env){if(parsed.toolRuntime!==void 0)return{ok:!0,value:parsed.toolRuntime};let fromEnv=envValue(TOOL_RUNTIME_ENV_SUFFIX,env);return fromEnv===void 0||fromEnv===""?{ok:!0,value:"in-process"}:isToolRuntimeKind(fromEnv)?{ok:!0,value:fromEnv}:{ok:!1,message:`${brandEnvNames(TOOL_RUNTIME_ENV_SUFFIX).find(candidate=>env[candidate]!==void 0)??TOOL_RUNTIME_ENV_SUFFIX} (--tool-runtime) must be in-process or child, got ${JSON.stringify(fromEnv)}`}}var SESSION_RUNTIMES=["in-process","worker"];function isSessionRuntimeKind(value){return SESSION_RUNTIMES.some(runtime=>runtime===value)}function resolveSessionRuntime(parsed){return parsed.sessionRuntime?parsed.sessionRuntime:parsed.listen!==void 0&&parsed.listen!=="stdio://"?"in-process":"worker"}var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.some(candidate=>candidate===level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseArgs(args,options={}){let grokNeoEnabled=options.grokNeoEnabled??isGrokNeoEnabled(),result={messages:[],fileArgs:[],unknownFlags:new Map,diagnostics:[]};if(args[0]==="app-server")return result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`}),result;let hasRetiredCommand=!1;for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"){let mode=args[i+1];if(mode===void 0||mode.startsWith("-")){result.diagnostics.push({type:"error",message:"--mode requires text, json, or rpc"});continue}if(i++,mode!=="text"&&mode!=="json"&&mode!=="rpc"){result.diagnostics.push({type:"error",message:`Invalid mode "${mode}". Valid values: text, json, rpc`});continue}result.mode=mode}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length){let typedProvider=args[++i],rejection=typedProvider===void 0?void 0:legacyProviderIdRejection(typedProvider);if(rejection)throw new Error(rejection);result.provider=typedProvider}else if(arg==="--model"&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--spawned-by"){let value=args[i+1];if(value===void 0||value.startsWith("-"))result.diagnostics.push({type:"error",message:"--spawned-by requires a JSON object"});else{i++;try{let ancestry=JSON.parse(value);isSpawnedBy(ancestry)?result.spawnedBy=ancestry:result.diagnostics.push({type:"error",message:"--spawned-by requires non-empty parentSessionId, rootSessionId, and taskId strings"})}catch(error){if(!(error instanceof SyntaxError))throw error;result.diagnostics.push({type:"error",message:"--spawned-by must be valid JSON"})}}}else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--rebind"&&i+1<args.length)result.rebind=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if((arg==="--extension"||arg==="-e")&&i+1<args.length)result.extensions=result.extensions??[],result.extensions.push(args[++i]);else if(arg==="--no-extensions"||arg==="-ne")result.noExtensions=!0;else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--print-prompt-sizes")result.printPromptSizes=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--list-tips")result.listTips=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else if(arg==="--verbose")result.verbose=!0;else if(arg==="--approve"||arg==="-a")result.projectTrustOverride=!0;else if(arg==="--no-approve"||arg==="-na")result.projectTrustOverride=!1;else if(arg==="--offline")result.offline=!0;else if(grokNeoEnabled&&arg==="--grok-neo")result.grokNeo=!0;else if(arg==="--multi-session")result.multiSession=!0;else if(arg==="--mcp-presenter-fd")args[++i]==="4"?result.presenterBootstrapFd=4:result.diagnostics.push({type:"error",message:"Invalid presenter bootstrap descriptor"});else if(arg==="--mcp-presenter-enforcement")result.mcpPresenterEnforcement=!0;else if(arg==="--auto-title-sessions")result.autoTitleSessions=!0;else if(arg==="--session-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isSessionRuntimeKind(value)?result.sessionRuntime=value:result.diagnostics.push({type:"error",message:"--session-runtime must be in-process or worker"})}else if(arg==="--tool-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isToolRuntimeKind(value)?result.toolRuntime=value:result.diagnostics.push({type:"error",message:"--tool-runtime must be in-process or child"})}else if(arg==="--listen"&&result.mode==="rpc"){let value=args[i+1];value===void 0||value.startsWith("--")?result.diagnostics.push({type:"error",message:"--listen requires a value"}):(result.listen=value,result.multiSession=!0,i++)}else if(arg.startsWith("@"))result.fileArgs.push(arg.slice(1));else if(arg.startsWith("--")){let eqIndex=arg.indexOf("=");if(eqIndex!==-1)result.unknownFlags.set(arg.slice(2,eqIndex),arg.slice(eqIndex+1));else{let flagName=arg.slice(2),next=args[i+1];next!==void 0&&!next.startsWith("-")&&!next.startsWith("@")?(result.unknownFlags.set(flagName,next),i++):result.unknownFlags.set(flagName,!0)}}else arg==="-"?result.readStdin=!0:arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||(result.messages.length===0&&arg==="app-server"&&(hasRetiredCommand=!0),result.messages.push(arg))}return hasRetiredCommand&&result.mode===void 0&&!result.print&&(result.messages=[],result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`})),applyAttachArgs(result),result}function printHelp(extensionFlags,grokNeoEnabled=isGrokNeoEnabled()){let extensionFlagsText=extensionFlags&&extensionFlags.length>0?`
|
|
3
3
|
${source_default.bold("Extension CLI Flags:")}
|
|
4
4
|
${extensionFlags.map(flag=>{let value=flag.type==="string"?" <value>":"",description=flag.description??`Registered by ${flag.extensionPath}`;return` --${flag.name}${value}`.padEnd(30)+description}).join(`
|
|
5
5
|
`)}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
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 = () => {}; } }
|
|
3
|
-
import"./chunk-6STZ65LL.js";import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunk-
|
|
3
|
+
import"./chunk-6STZ65LL.js";import{dispatchAgentDirectoryCommand,enableStartupCompileCache}from"./chunk-KY4V3TSO.js";import"./chunk-OD7RT7G7.js";import{installStaleExtensionContainment}from"./chunk-7C4W5HMU.js";import{configureHttpDispatcher}from"./chunk-FEQDJBDL.js";import"./chunk-UYO5Z35O.js";import"./chunk-EBZ6IP4V.js";import"./chunk-LNAZ7XEU.js";import"./chunk-DLAY7CIU.js";import"./chunk-GKP34H3C.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-YXL3PNTL.js";import"./chunk-GVSBCJFI.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z7HTHT6K.js";import"./chunk-HK46JMSC.js";import"./chunk-2PGSRQBF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-6NPK2O3C.js";import"./chunk-ZFIC2DZV.js";import"./chunk-XVRRNJQD.js";import"./chunk-42XRJQM6.js";import"./chunk-UKSFF47T.js";import"./chunk-OM7LH7AP.js";import"./chunk-QEESHRTS.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";await dispatchAgentDirectoryCommand(process.argv.slice(2));await enableStartupCompileCache();installEarlyInspectorVmImportRecovery();installStaleExtensionContainment();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();var{main}=await import("./main-P7PKMJUG.js");await main(process.argv.slice(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{classifySystemOne,isRecord}from"./chunk-
|
|
2
|
+
import{classifySystemOne,isRecord}from"./chunk-UHUM55TR.js";import"./chunk-GIT63LXN.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var LABEL="Cloudflare Workers AI";function cloudflareErrorMessage(errors){if(Array.isArray(errors)){let messages=errors.map(error=>isRecord(error)&&typeof error.message=="string"?error.message:void 0).filter(message=>message!==void 0);if(messages.length>0)return`${LABEL} error: ${messages.join("; ")}`}return`${LABEL} request failed`}var transport={api:"cloudflare-workers-ai-system-one",label:LABEL,url:model=>new URL("run",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,input:request}),output:body=>{if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);if(body.success===!1)throw new Error(cloudflareErrorMessage(body.errors));let run=body.result;if(!isRecord(run))throw new Error(`${LABEL} returned an unexpected response`);if(run.state!=="Completed")throw new Error(`${LABEL} run did not complete (state: ${String(run.state)})`);if(!isRecord(run.result))throw new Error(`${LABEL} returned an unexpected response`);return run.result}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
|
|
@@ -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{assertValidAccountName2 as assertValidAccountName,credentialPoolRepository,getCredentialAccounts,pinCredentialAccount,removeCredentialAccount,renameCredentialAccount,signOutClaudeCliSlotsForLogout,summarizeCredentialAccounts}from"./chunk-WO6I5PRF.js";import"./chunk-SJWTZ3Z2.js";import"./chunk-VDDJADPV.js";import"./chunk-KLAX467B.js";import"./chunk-RUOTFZQR.js";import"./chunk-QPYDQ4QK.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import"./chunk-EBZ6IP4V.js";import"./chunk-6ISOXWH2.js";import"./chunk-ZNPH5BWS.js";import"./chunk-6VWIMHMH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-LNAZ7XEU.js";import"./chunk-DLAY7CIU.js";import"./chunk-GKP34H3C.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-YXL3PNTL.js";import"./chunk-GVSBCJFI.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z7HTHT6K.js";import"./chunk-HK46JMSC.js";import"./chunk-2PGSRQBF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{assertValidAccountName,credentialPoolRepository,getCredentialAccounts,pinCredentialAccount,removeCredentialAccount,renameCredentialAccount,signOutClaudeCliSlotsForLogout,summarizeCredentialAccounts};
|
|
@@ -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
|
-
var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});import{createServer}from"node:http";
|
|
2
|
+
var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});import{createServer}from"node:http";function processSingleton(key,create){let slot=Symbol.for(key),existing=Reflect.get(globalThis,slot);if(existing!==void 0)return existing;let created=create();return Reflect.set(globalThis,slot,created),created}var brandSlot=processSingleton("@code-yeongyu/senpi-ai:oauth-page-brand",()=>({current:void 0}));function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0,brand=brandSlot.current,logo=brand?.logo?`<img class="logo" src="${brand.logo}" alt="" />`:"",brandName=brand?`<div class="brand-name">${escapeHtml(brand.name)}</div>`:"";return`<!doctype html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8" />
|
|
@@ -39,7 +39,14 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
|
|
|
39
39
|
width: 72px;
|
|
40
40
|
height: 72px;
|
|
41
41
|
display: block;
|
|
42
|
+
margin-bottom: 16px;
|
|
43
|
+
}
|
|
44
|
+
.brand-name {
|
|
42
45
|
margin-bottom: 24px;
|
|
46
|
+
font-size: 15px;
|
|
47
|
+
font-weight: 600;
|
|
48
|
+
letter-spacing: 0.02em;
|
|
49
|
+
color: var(--text-dim);
|
|
43
50
|
}
|
|
44
51
|
h1 {
|
|
45
52
|
margin: 0 0 10px;
|
|
@@ -66,7 +73,8 @@ var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(
|
|
|
66
73
|
</head>
|
|
67
74
|
<body>
|
|
68
75
|
<main>
|
|
69
|
-
|
|
76
|
+
${logo}
|
|
77
|
+
${brandName}
|
|
70
78
|
<h1>${heading}</h1>
|
|
71
79
|
<p>${message}</p>
|
|
72
80
|
${details?`<div class="details">${details}</div>`:""}
|
|
@@ -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{fetchWithinOrigin}from"./chunk-YP72RYUP.js";import{InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION}from"./chunk-WJOT3DFL.js";import"./chunk-AX72VNRS.js";import{AuthError,ConnectError,ModernParameterHeaders,ParameterHeaderValidationError,clearMcpParameterHeaders,configureMcpElicitation,encodeMcpHeaderValue,getModernDispatchGuard,installModernRequestAdapter,isMcpNeedsAuthError,legacyMcpFormEligible,loadMcpSdkAuth,loadMcpSdkClient,loadMcpSdkStdioTransport,loadMcpSdkStreamableHttpTransport,loadMcpSdkTypes,mcpClientCapabilities,mcpElapsedClock,modernDispatchGuard,reapProcessTree,safeOn}from"./chunk-ETCYVVVO.js";import{McpMrtrError,isRecord}from"./chunk-7ICGN62G.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-DLAY7CIU.js";import"./chunk-ISZ4EWIS.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";var modernCredentialSnapshot=tokens=>tokens===void 0?void 0:JSON.stringify([tokens.access_token,tokens.refresh_token]);function modernHttpFetch(spec,signal,authorizeResend=!0){let fetch=fetchWithinOrigin();return async(url,init)=>{let requestSignal=init?.signal?AbortSignal.any([signal,init.signal]):signal,send=()=>{let headers=new Headers,tokens=spec.authProvider?.tokens(),guard=init?.[modernDispatchGuard];guard?.(modernCredentialSnapshot(tokens)),tokens&&headers.set("Authorization",`Bearer ${tokens.access_token}`),new Headers(spec.requestInit?.headers).forEach((value,key)=>{headers.set(key,value)});for(let key of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(key);return clearMcpParameterHeaders(headers),new Headers(init?.headers).forEach((value,key)=>{headers.set(key,value)}),headers.delete("Mcp-Session-Id"),fetch(url,{...spec.requestInit,...init,headers,signal:requestSignal})},response=await send();if(authorizeResend&&spec.authProvider&&(response.status===401||response.status===403)){let{auth,extractWWWAuthenticateParams,UnauthorizedError}=await loadMcpSdkAuth(),{resourceMetadataUrl,scope,error}=extractWWWAuthenticateParams(response);if(response.status===401||error==="insufficient_scope"){if(await response.body?.cancel(),await auth(spec.authProvider,{serverUrl:spec.url,resourceMetadataUrl,scope,fetchFn:(target,request2)=>fetch(target,{...request2,signal:request2?.signal?AbortSignal.any([requestSignal,request2.signal]):requestSignal})})!=="AUTHORIZED")throw new UnauthorizedError;if(response=await send(),response.status===401)throw await response.body?.cancel(),new UnauthorizedError("Server returned 401 after successful authentication")}}return response}}async function createMcpRequestClient(protocol,uiProvider,readCredential=()=>{},elicitationEnabled=!0){let{Client}=await loadMcpSdkClient();protocol.privateForms=uiProvider?.enforced?.()===!0;let legacyEligible=legacyMcpFormEligible(uiProvider,elicitationEnabled);protocol.legacyFormEligible=legacyEligible;let client=new Client({name:"senpi-mcp-client",version:"0.0.0"},{capabilities:mcpClientCapabilities(legacyEligible)});return await configureMcpElicitation(client,uiProvider,void 0,legacyEligible),installModernRequestAdapter(client,protocol,mcpElapsedClock,readCredential),client}import{PassThrough}from"node:stream";var ProjectStdioTransport=class{#resolve;#create;#current;#epoch;constructor(resolve,create){this.stderr=new PassThrough,this.#epoch=0,this.#resolve=resolve,this.#create=create}get pid(){return this.#current?.pid??null}async start(){let epoch=this.#epoch,spec=await this.#resolve();if(epoch!==this.#epoch)throw new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0});let transport=this.#create(spec);if(this.#current=transport,transport.onmessage=message=>this.onmessage?.(message),transport.onclose=()=>this.onclose?.(),transport.onerror=error=>this.onerror?.(error),transport.stderr?.pipe(this.stderr,{end:!1}),await transport.start(),epoch!==this.#epoch)throw await transport.close(),new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0})}async send(message,_options){if(this.#current===void 0)throw new ConnectError("Project MCP transport has not started",{phase:"send",retriable:!0});await this.#current.send(message)}async close(){this.#epoch++,await this.#current?.close()}};async function materializeMcpTransport(options,protocol={}){let client=await createMcpRequestClient(protocol,options.elicitationUiProvider,()=>modernCredentialSnapshot(options.spec.authProvider?.tokens()),options.elicitationEnabled);return options.spec.kind==="stdio"?materializeStdio(options.spec,options,client,protocol):materializeHttp(options.spec,client)}async function materializeStdio(spec,options,client,protocol){let{getDefaultEnvironment,StdioClientTransport}=await loadMcpSdkStdioTransport(),create=current=>new StdioClientTransport({args:current.args,command:current.command,cwd:current.cwd,env:{...current.projectPolicy?{}:getDefaultEnvironment(),...current.env,...oauthAccessTokenEnv(current.authProvider)},stderr:"pipe"}),transport=spec.projectPolicy&&spec.resolveBeforeStart!==void 0?new ProjectStdioTransport(spec.resolveBeforeStart,create):create(spec);return trackStdioStart(transport,options.onStart),pipeStderr(transport,options.logger,options.sink,protocol),dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>transport.pid,transport}}async function materializeHttp(spec,client){let{StreamableHTTPClientTransport}=await loadMcpSdkStreamableHttpTransport(),transport=new StreamableHTTPClientTransport(spec.url,{authProvider:spec.authProvider,requestInit:spec.requestInit});return dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>null,transport}}function oauthAccessTokenEnv(authProvider){let accessToken=authProvider?.tokens()?.access_token;return accessToken===void 0||accessToken.length===0?{}:{OAUTH_ACCESS_TOKEN:accessToken}}function dropNullNextCursor(transport){let originalStart=transport.start.bind(transport);transport.start=async()=>{let deliver=transport.onmessage;deliver!==void 0&&(transport.onmessage=(message,extra)=>{if("result"in message&&message.result!==null&&typeof message.result=="object"){let result=message.result;result.nextCursor===null&&delete result.nextCursor}deliver(message,extra)}),await originalStart()}}function trackStdioStart(transport,onStart){let start=transport.start.bind(transport);transport.start=async()=>{await start(),onStart()}}function pipeStderr(transport,logger,sink,protocol){let pending="",undecided="",stderrEnded=!1,stderr=transport.stderr;if(stderr==null)return;let start=transport.start.bind(transport);transport.start=async()=>{let onclose=transport.onclose;transport.onclose=()=>{stderrEnded=!0,protocol.version===void 0&&protocol.resolveStdioDiagnostics?.(!1),onclose?.()},await start()};let logLine=line=>{let code=protocol.privateForms?line.match(/\b(?:EACCES|ENOENT|EPIPE|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOSPC|ENOMEM|EMFILE)\b/)?.[0]:void 0;logger.stderr(protocol.privateForms?`[private MCP stderr redacted]${code?` ${code}`:""}`:line)},append=text=>{pending+=text;let lines=pending.split(/\r?\n/);pending=lines.pop()??"";for(let line of lines)line.length>0&&logLine(line)};protocol.resolveStdioDiagnostics=modern=>{(!modern||protocol.privateForms)&&(append(undecided),stderrEnded&&pending.length>0&&(logLine(pending),pending="")),undecided="",modern&&!protocol.privateForms&&(pending="")},safeOn(stderr,"data","transport.stderr.data",chunk=>{if(protocol.version!==void 0&&!protocol.privateForms){pending="",undecided="";return}if(!Buffer.isBuffer(chunk)&&typeof chunk!="string")return;let text=Buffer.isBuffer(chunk)?chunk.toString("utf8"):chunk;if(!protocol.legacy&&!protocol.privateForms){undecided+=text.slice(0,Math.max(0,512*1024-undecided.length));return}append(text)},sink),safeOn(stderr,"end","transport.stderr.end",()=>{stderrEnded=!0,(protocol.privateForms||protocol.legacy&&protocol.version===void 0)&&pending.length>0&&logLine(pending),pending="",(protocol.legacy||protocol.version!==void 0)&&(undecided="")},sink)}async function closeClientAndTransport(transport,client){isTerminableHttpTransport(transport)&&await transport.terminateSession().catch(()=>{}),await transport.close().catch(()=>{}),await client.close().catch(()=>{})}function isTerminableHttpTransport(transport){return"terminateSession"in transport&&typeof transport.terminateSession=="function"}var MODERN_PROTOCOL_VERSION="2026-07-28",MODERN_ERROR_CODES={HeaderMismatch:-32020,MissingRequiredClientCapabilityError:-32021,UnsupportedProtocolVersionError:-32022};function buildModernRequest(id,method,clientInfo2,clientCapabilities,params={}){return{jsonrpc:"2.0",id,method,params:{...params,_meta:{...params._meta,"io.modelcontextprotocol/protocolVersion":MODERN_PROTOCOL_VERSION,"io.modelcontextprotocol/clientInfo":clientInfo2,"io.modelcontextprotocol/clientCapabilities":clientCapabilities}}}}function modernizeRequest(id,method,clientInfo2,clientCapabilities,version,params){let built=buildModernRequest(id,method,clientInfo2,clientCapabilities,params),capabilities=params?._meta?.["io.modelcontextprotocol/clientCapabilities"];return{...built,params:{...built.params,_meta:{...built.params._meta,"io.modelcontextprotocol/clientCapabilities":isRecord2(capabilities)?capabilities:clientCapabilities,"io.modelcontextprotocol/protocolVersion":version}}}}function deriveModernHeaders(request2){let headers={"MCP-Protocol-Version":request2.params._meta["io.modelcontextprotocol/protocolVersion"],"Mcp-Method":request2.method},name=request2.method==="resources/read"?request2.params.uri:request2.method==="tools/call"||request2.method==="prompts/get"?request2.params.name:["tasks/get","tasks/update","tasks/cancel"].includes(request2.method)?request2.params.taskId:void 0;return typeof name=="string"&&(headers["Mcp-Name"]=encodeMcpHeaderValue(name)),headers}function classifyModernError(body2){let response=parseBody(body2);if(!isRecord2(response)||response.jsonrpc!=="2.0"||!isRecord2(response.error))return;let error=response.error;if(typeof error.message!="string")return;let common={message:error.message,..."data"in error?{data:error.data}:{}};switch(error.code){case MODERN_ERROR_CODES.HeaderMismatch:return{...common,kind:"HeaderMismatch",code:error.code};case MODERN_ERROR_CODES.MissingRequiredClientCapabilityError:return{...common,kind:"MissingRequiredClientCapabilityError",code:error.code};case MODERN_ERROR_CODES.UnsupportedProtocolVersionError:{let supported=isRecord2(error.data)?error.data.supported:void 0;return{...common,kind:"UnsupportedProtocolVersionError",code:error.code,...Array.isArray(supported)&&supported.every(version=>typeof version=="string")?{supportedVersions:supported}:{}}}default:return}}function parseBody(body2){if(typeof body2!="string")return body2;try{return JSON.parse(body2)}catch(error){if(error instanceof SyntaxError)return;throw error}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var discoverySchema=external_exports.object({resultType:external_exports.literal("complete"),supportedVersions:external_exports.array(external_exports.string()),capabilities:external_exports.record(external_exports.string(),external_exports.unknown()),_meta:external_exports.object({"io.modelcontextprotocol/serverInfo":external_exports.object({name:external_exports.string(),version:external_exports.string()}).passthrough()}).passthrough(),instructions:external_exports.string().optional(),ttlMs:external_exports.number().nonnegative().optional(),cacheScope:external_exports.string().optional()}).passthrough(),modernError=classifyModernError,STDIO_PROBE_ID="senpi-era-probe",StdioProbeSilence=class extends Error{constructor(){super("MCP stdio server did not answer discovery in time"),this.name="StdioProbeSilence"}};function discoveryReply(value,id){return complete(value,id)}function request(options,version,id=1){let built=buildModernRequest(id,"server/discover",options.clientInfo,options.clientCapabilities);return{...built,params:{_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function complete(value,id=1){let parsed=external_exports.object({jsonrpc:external_exports.literal("2.0"),id:external_exports.literal(id),result:discoverySchema}).safeParse(value);return parsed.success?parsed.data.result:void 0}function errorReply(value,id){return external_exports.object({jsonrpc:external_exports.literal("2.0"),id:id===void 0?external_exports.union([external_exports.string(),external_exports.number(),external_exports.null()]):external_exports.literal(id),error:external_exports.object({code:external_exports.number(),message:external_exports.string()})}).safeParse(value).success}async function mutualVersion(error,options){if(error.kind!=="UnsupportedProtocolVersionError"||!error.supportedVersions)return;let modern=error.supportedVersions.filter(candidate=>options.supportedVersions.includes(candidate)).sort().at(-1);if(modern)return modern;let{SUPPORTED_PROTOCOL_VERSIONS}=await loadMcpSdkTypes();return error.supportedVersions.filter(candidate=>SUPPORTED_PROTOCOL_VERSIONS.includes(candidate)).sort().at(-1)}function noMutualVersion(error){let supported=error.kind==="UnsupportedProtocolVersionError"?error.supportedVersions:void 0;return indeterminate("no-mutual-version",`Update client or server to share a supported protocol version. Server supported versions: ${supported?.join(", ")??"not provided"}.`,{era:"modern"})}function indeterminate(reason,action,details={}){return{kind:"indeterminate",reason,action,...details}}function parseJson(text){try{return JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}}async function body(response){let text=await response.text();if(!response.headers.get("Content-Type")?.includes("text/event-stream"))return parseJson(text);for(let event of text.replace(/\r\n/g,`
|
|
2
|
+
import{fetchWithinOrigin}from"./chunk-YP72RYUP.js";import{InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION}from"./chunk-WJOT3DFL.js";import"./chunk-AX72VNRS.js";import{AuthError,ConnectError,ModernParameterHeaders,ParameterHeaderValidationError,clearMcpParameterHeaders,configureMcpElicitation,encodeMcpHeaderValue,getModernDispatchGuard,installModernRequestAdapter,isMcpNeedsAuthError,legacyMcpFormEligible,loadMcpSdkAuth,loadMcpSdkClient,loadMcpSdkStdioTransport,loadMcpSdkStreamableHttpTransport,loadMcpSdkTypes,mcpClientCapabilities,mcpElapsedClock,modernDispatchGuard,reapProcessTree,safeOn}from"./chunk-WVEIJ437.js";import{McpMrtrError,isRecord}from"./chunk-7ICGN62G.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-DLAY7CIU.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";var modernCredentialSnapshot=tokens=>tokens===void 0?void 0:JSON.stringify([tokens.access_token,tokens.refresh_token]);function modernHttpFetch(spec,signal,authorizeResend=!0){let fetch=fetchWithinOrigin();return async(url,init)=>{let requestSignal=init?.signal?AbortSignal.any([signal,init.signal]):signal,send=()=>{let headers=new Headers,tokens=spec.authProvider?.tokens(),guard=init?.[modernDispatchGuard];guard?.(modernCredentialSnapshot(tokens)),tokens&&headers.set("Authorization",`Bearer ${tokens.access_token}`),new Headers(spec.requestInit?.headers).forEach((value,key)=>{headers.set(key,value)});for(let key of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(key);return clearMcpParameterHeaders(headers),new Headers(init?.headers).forEach((value,key)=>{headers.set(key,value)}),headers.delete("Mcp-Session-Id"),fetch(url,{...spec.requestInit,...init,headers,signal:requestSignal})},response=await send();if(authorizeResend&&spec.authProvider&&(response.status===401||response.status===403)){let{auth,extractWWWAuthenticateParams,UnauthorizedError}=await loadMcpSdkAuth(),{resourceMetadataUrl,scope,error}=extractWWWAuthenticateParams(response);if(response.status===401||error==="insufficient_scope"){if(await response.body?.cancel(),await auth(spec.authProvider,{serverUrl:spec.url,resourceMetadataUrl,scope,fetchFn:(target,request2)=>fetch(target,{...request2,signal:request2?.signal?AbortSignal.any([requestSignal,request2.signal]):requestSignal})})!=="AUTHORIZED")throw new UnauthorizedError;if(response=await send(),response.status===401)throw await response.body?.cancel(),new UnauthorizedError("Server returned 401 after successful authentication")}}return response}}async function createMcpRequestClient(protocol,uiProvider,readCredential=()=>{},elicitationEnabled=!0){let{Client}=await loadMcpSdkClient();protocol.privateForms=uiProvider?.enforced?.()===!0;let legacyEligible=legacyMcpFormEligible(uiProvider,elicitationEnabled);protocol.legacyFormEligible=legacyEligible;let client=new Client({name:"senpi-mcp-client",version:"0.0.0"},{capabilities:mcpClientCapabilities(legacyEligible)});return await configureMcpElicitation(client,uiProvider,void 0,legacyEligible),installModernRequestAdapter(client,protocol,mcpElapsedClock,readCredential),client}import{PassThrough}from"node:stream";var ProjectStdioTransport=class{#resolve;#create;#current;#epoch;constructor(resolve,create){this.stderr=new PassThrough,this.#epoch=0,this.#resolve=resolve,this.#create=create}get pid(){return this.#current?.pid??null}async start(){let epoch=this.#epoch,spec=await this.#resolve();if(epoch!==this.#epoch)throw new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0});let transport=this.#create(spec);if(this.#current=transport,transport.onmessage=message=>this.onmessage?.(message),transport.onclose=()=>this.onclose?.(),transport.onerror=error=>this.onerror?.(error),transport.stderr?.pipe(this.stderr,{end:!1}),await transport.start(),epoch!==this.#epoch)throw await transport.close(),new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0})}async send(message,_options){if(this.#current===void 0)throw new ConnectError("Project MCP transport has not started",{phase:"send",retriable:!0});await this.#current.send(message)}async close(){this.#epoch++,await this.#current?.close()}};async function materializeMcpTransport(options,protocol={}){let client=await createMcpRequestClient(protocol,options.elicitationUiProvider,()=>modernCredentialSnapshot(options.spec.authProvider?.tokens()),options.elicitationEnabled);return options.spec.kind==="stdio"?materializeStdio(options.spec,options,client,protocol):materializeHttp(options.spec,client)}async function materializeStdio(spec,options,client,protocol){let{getDefaultEnvironment,StdioClientTransport}=await loadMcpSdkStdioTransport(),create=current=>new StdioClientTransport({args:current.args,command:current.command,cwd:current.cwd,env:{...current.projectPolicy?{}:getDefaultEnvironment(),...current.env,...oauthAccessTokenEnv(current.authProvider)},stderr:"pipe"}),transport=spec.projectPolicy&&spec.resolveBeforeStart!==void 0?new ProjectStdioTransport(spec.resolveBeforeStart,create):create(spec);return trackStdioStart(transport,options.onStart),pipeStderr(transport,options.logger,options.sink,protocol),dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>transport.pid,transport}}async function materializeHttp(spec,client){let{StreamableHTTPClientTransport}=await loadMcpSdkStreamableHttpTransport(),transport=new StreamableHTTPClientTransport(spec.url,{authProvider:spec.authProvider,requestInit:spec.requestInit});return dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>null,transport}}function oauthAccessTokenEnv(authProvider){let accessToken=authProvider?.tokens()?.access_token;return accessToken===void 0||accessToken.length===0?{}:{OAUTH_ACCESS_TOKEN:accessToken}}function dropNullNextCursor(transport){let originalStart=transport.start.bind(transport);transport.start=async()=>{let deliver=transport.onmessage;deliver!==void 0&&(transport.onmessage=(message,extra)=>{if("result"in message&&message.result!==null&&typeof message.result=="object"){let result=message.result;result.nextCursor===null&&delete result.nextCursor}deliver(message,extra)}),await originalStart()}}function trackStdioStart(transport,onStart){let start=transport.start.bind(transport);transport.start=async()=>{await start(),onStart()}}function pipeStderr(transport,logger,sink,protocol){let pending="",undecided="",stderrEnded=!1,stderr=transport.stderr;if(stderr==null)return;let start=transport.start.bind(transport);transport.start=async()=>{let onclose=transport.onclose;transport.onclose=()=>{stderrEnded=!0,protocol.version===void 0&&protocol.resolveStdioDiagnostics?.(!1),onclose?.()},await start()};let logLine=line=>{let code=protocol.privateForms?line.match(/\b(?:EACCES|ENOENT|EPIPE|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOSPC|ENOMEM|EMFILE)\b/)?.[0]:void 0;logger.stderr(protocol.privateForms?`[private MCP stderr redacted]${code?` ${code}`:""}`:line)},append=text=>{pending+=text;let lines=pending.split(/\r?\n/);pending=lines.pop()??"";for(let line of lines)line.length>0&&logLine(line)};protocol.resolveStdioDiagnostics=modern=>{(!modern||protocol.privateForms)&&(append(undecided),stderrEnded&&pending.length>0&&(logLine(pending),pending="")),undecided="",modern&&!protocol.privateForms&&(pending="")},safeOn(stderr,"data","transport.stderr.data",chunk=>{if(protocol.version!==void 0&&!protocol.privateForms){pending="",undecided="";return}if(!Buffer.isBuffer(chunk)&&typeof chunk!="string")return;let text=Buffer.isBuffer(chunk)?chunk.toString("utf8"):chunk;if(!protocol.legacy&&!protocol.privateForms){undecided+=text.slice(0,Math.max(0,512*1024-undecided.length));return}append(text)},sink),safeOn(stderr,"end","transport.stderr.end",()=>{stderrEnded=!0,(protocol.privateForms||protocol.legacy&&protocol.version===void 0)&&pending.length>0&&logLine(pending),pending="",(protocol.legacy||protocol.version!==void 0)&&(undecided="")},sink)}async function closeClientAndTransport(transport,client){isTerminableHttpTransport(transport)&&await transport.terminateSession().catch(()=>{}),await transport.close().catch(()=>{}),await client.close().catch(()=>{})}function isTerminableHttpTransport(transport){return"terminateSession"in transport&&typeof transport.terminateSession=="function"}var MODERN_PROTOCOL_VERSION="2026-07-28",MODERN_ERROR_CODES={HeaderMismatch:-32020,MissingRequiredClientCapabilityError:-32021,UnsupportedProtocolVersionError:-32022};function buildModernRequest(id,method,clientInfo2,clientCapabilities,params={}){return{jsonrpc:"2.0",id,method,params:{...params,_meta:{...params._meta,"io.modelcontextprotocol/protocolVersion":MODERN_PROTOCOL_VERSION,"io.modelcontextprotocol/clientInfo":clientInfo2,"io.modelcontextprotocol/clientCapabilities":clientCapabilities}}}}function modernizeRequest(id,method,clientInfo2,clientCapabilities,version,params){let built=buildModernRequest(id,method,clientInfo2,clientCapabilities,params),capabilities=params?._meta?.["io.modelcontextprotocol/clientCapabilities"];return{...built,params:{...built.params,_meta:{...built.params._meta,"io.modelcontextprotocol/clientCapabilities":isRecord2(capabilities)?capabilities:clientCapabilities,"io.modelcontextprotocol/protocolVersion":version}}}}function deriveModernHeaders(request2){let headers={"MCP-Protocol-Version":request2.params._meta["io.modelcontextprotocol/protocolVersion"],"Mcp-Method":request2.method},name=request2.method==="resources/read"?request2.params.uri:request2.method==="tools/call"||request2.method==="prompts/get"?request2.params.name:["tasks/get","tasks/update","tasks/cancel"].includes(request2.method)?request2.params.taskId:void 0;return typeof name=="string"&&(headers["Mcp-Name"]=encodeMcpHeaderValue(name)),headers}function classifyModernError(body2){let response=parseBody(body2);if(!isRecord2(response)||response.jsonrpc!=="2.0"||!isRecord2(response.error))return;let error=response.error;if(typeof error.message!="string")return;let common={message:error.message,..."data"in error?{data:error.data}:{}};switch(error.code){case MODERN_ERROR_CODES.HeaderMismatch:return{...common,kind:"HeaderMismatch",code:error.code};case MODERN_ERROR_CODES.MissingRequiredClientCapabilityError:return{...common,kind:"MissingRequiredClientCapabilityError",code:error.code};case MODERN_ERROR_CODES.UnsupportedProtocolVersionError:{let supported=isRecord2(error.data)?error.data.supported:void 0;return{...common,kind:"UnsupportedProtocolVersionError",code:error.code,...Array.isArray(supported)&&supported.every(version=>typeof version=="string")?{supportedVersions:supported}:{}}}default:return}}function parseBody(body2){if(typeof body2!="string")return body2;try{return JSON.parse(body2)}catch(error){if(error instanceof SyntaxError)return;throw error}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var discoverySchema=external_exports.object({resultType:external_exports.literal("complete"),supportedVersions:external_exports.array(external_exports.string()),capabilities:external_exports.record(external_exports.string(),external_exports.unknown()),_meta:external_exports.object({"io.modelcontextprotocol/serverInfo":external_exports.object({name:external_exports.string(),version:external_exports.string()}).passthrough()}).passthrough(),instructions:external_exports.string().optional(),ttlMs:external_exports.number().nonnegative().optional(),cacheScope:external_exports.string().optional()}).passthrough(),modernError=classifyModernError,STDIO_PROBE_ID="senpi-era-probe",StdioProbeSilence=class extends Error{constructor(){super("MCP stdio server did not answer discovery in time"),this.name="StdioProbeSilence"}};function discoveryReply(value,id){return complete(value,id)}function request(options,version,id=1){let built=buildModernRequest(id,"server/discover",options.clientInfo,options.clientCapabilities);return{...built,params:{_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function complete(value,id=1){let parsed=external_exports.object({jsonrpc:external_exports.literal("2.0"),id:external_exports.literal(id),result:discoverySchema}).safeParse(value);return parsed.success?parsed.data.result:void 0}function errorReply(value,id){return external_exports.object({jsonrpc:external_exports.literal("2.0"),id:id===void 0?external_exports.union([external_exports.string(),external_exports.number(),external_exports.null()]):external_exports.literal(id),error:external_exports.object({code:external_exports.number(),message:external_exports.string()})}).safeParse(value).success}async function mutualVersion(error,options){if(error.kind!=="UnsupportedProtocolVersionError"||!error.supportedVersions)return;let modern=error.supportedVersions.filter(candidate=>options.supportedVersions.includes(candidate)).sort().at(-1);if(modern)return modern;let{SUPPORTED_PROTOCOL_VERSIONS}=await loadMcpSdkTypes();return error.supportedVersions.filter(candidate=>SUPPORTED_PROTOCOL_VERSIONS.includes(candidate)).sort().at(-1)}function noMutualVersion(error){let supported=error.kind==="UnsupportedProtocolVersionError"?error.supportedVersions:void 0;return indeterminate("no-mutual-version",`Update client or server to share a supported protocol version. Server supported versions: ${supported?.join(", ")??"not provided"}.`,{era:"modern"})}function indeterminate(reason,action,details={}){return{kind:"indeterminate",reason,action,...details}}function parseJson(text){try{return JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}}async function body(response){let text=await response.text();if(!response.headers.get("Content-Type")?.includes("text/event-stream"))return parseJson(text);for(let event of text.replace(/\r\n/g,`
|
|
3
3
|
`).split(`
|
|
4
4
|
|
|
5
5
|
`)){let data=event.split(`
|
package/dist/bundle/chunks/{google-generative-ai-7PQ4QRHJ.js → google-generative-ai-2TZSCSIS.js}
RENAMED
|
@@ -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{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-2YFPDNNP.js";import"./chunk-QPGJHUIK.js";import"./chunk-UFVZTQKN.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-2XBKE2BZ.js";import"./chunk-GIT63LXN.js";import{formatProviderError,normalizeProviderError}from"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-ED7VJGL4.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-TBARMJ75.js";import"./chunk-3SASTB6Y.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-5CSZPC55.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,providerHeadersToRecord(options?.headers)),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
2
|
+
import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-DNZKKG4V.js";import"./chunk-QPGJHUIK.js";import"./chunk-TQQG5L4D.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-BIWFWGUA.js";import"./chunk-GIT63LXN.js";import{formatProviderError,normalizeProviderError}from"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-2PGSRQBF.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-5CSZPC55.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,providerHeadersToRecord(options?.headers)),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -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{buildGoogleAuthOptions,resolveVertexProjectFromEnv}from"./chunk-74YFRVGQ.js";import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-2YFPDNNP.js";import"./chunk-QPGJHUIK.js";import"./chunk-UFVZTQKN.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-2XBKE2BZ.js";import"./chunk-GIT63LXN.js";import{formatProviderError,normalizeProviderError}from"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-ED7VJGL4.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-TBARMJ75.js";import"./chunk-3SASTB6Y.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-5CSZPC55.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),headers=providerHeadersToRecord(options?.headers),client=apiKey?createClientWithApiKey(model,apiKey,headers):createClient(model,resolveProject(options),resolveLocation(options),headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=resolveVertexProjectFromEnv(options);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
2
|
+
import{buildGoogleAuthOptions,resolveVertexProjectFromEnv}from"./chunk-74YFRVGQ.js";import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-DNZKKG4V.js";import"./chunk-QPGJHUIK.js";import"./chunk-TQQG5L4D.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-BIWFWGUA.js";import"./chunk-GIT63LXN.js";import{formatProviderError,normalizeProviderError}from"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-2PGSRQBF.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-5CSZPC55.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),headers=providerHeadersToRecord(options?.headers),client=apiKey?createClientWithApiKey(model,apiKey,headers):createClient(model,resolveProject(options),resolveLocation(options),headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=resolveVertexProjectFromEnv(options);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -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{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-
|
|
2
|
+
import{STORE_BUSY,writeHealthUnlessStoreBusy}from"./chunk-E7SA75PP.js";import"./chunk-7X72IACK.js";import"./chunk-EBZ6IP4V.js";import"./chunk-LNAZ7XEU.js";import"./chunk-DLAY7CIU.js";import"./chunk-GKP34H3C.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-YXL3PNTL.js";import"./chunk-GVSBCJFI.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z7HTHT6K.js";import"./chunk-HK46JMSC.js";import"./chunk-2PGSRQBF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{STORE_BUSY,writeHealthUnlessStoreBusy};
|
|
@@ -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{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-
|
|
2
|
+
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-VIHXG53S.js";import"./chunk-YP47G4YP.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-ZTPG27EJ.js";import"./chunk-26UBFF6N.js";import"./chunk-GKP34H3C.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-YXL3PNTL.js";import"./chunk-GVSBCJFI.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z7HTHT6K.js";import"./chunk-HK46JMSC.js";import"./chunk-2PGSRQBF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
|
|
@@ -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{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-S5Y7NEHB.js";import"./chunk-OOU3BRUY.js";import"./chunk-Q5CKFBQT.js";import"./chunk-QMRJYMNH.js";import"./chunk-SQAQEITV.js";import"./chunk-XPSXUKSD.js";import"./chunk-7DWTKE4Z.js";import"./chunk-5BMIET5O.js";import"./chunk-DCI4QOUX.js";import"./chunk-YI6KRJDC.js";import"./chunk-E6UCZ7E5.js";import"./chunk-UYO5Z35O.js";import"./chunk-H52J72VA.js";import"./chunk-VDDJADPV.js";import"./chunk-KUPQO7MC.js";import"./chunk-U3VOXCGP.js";import"./chunk-ZTPG27EJ.js";import"./chunk-26UBFF6N.js";import"./chunk-EVTTLPIY.js";import"./chunk-GKP34H3C.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-YXL3PNTL.js";import"./chunk-GVSBCJFI.js";import"./chunk-TG4E7Z7W.js";import"./chunk-32R442XT.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z7HTHT6K.js";import"./chunk-HK46JMSC.js";import"./chunk-2PGSRQBF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-AVP6DDBF.js";import"./chunk-3SASTB6Y.js";import"./chunk-5CSZPC55.js";import"./chunk-PJ34QVL5.js";import"./chunk-6WISUXVI.js";import"./chunk-XVRRNJQD.js";import"./chunk-42XRJQM6.js";import"./chunk-OM7LH7AP.js";import"./chunk-QEESHRTS.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
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 = () => {}; } }
|
|
3
|
-
import{INTERNAL_SUPERVISOR_FLAG,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,runHostSupervisor,spawnableChildLaunch}from"./chunk-
|
|
3
|
+
import{INTERNAL_SUPERVISOR_FLAG,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,runHostSupervisor,spawnableChildLaunch}from"./chunk-5BMIET5O.js";import{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,IdleExitDecider,parseColdStart,parseIdleExitMs,resolveHostPolicy}from"./chunk-DCI4QOUX.js";import"./chunk-YI6KRJDC.js";import"./chunk-E6UCZ7E5.js";import"./chunk-UYO5Z35O.js";import"./chunk-H52J72VA.js";import"./chunk-U3VOXCGP.js";import"./chunk-6WISUXVI.js";import"./chunk-XVRRNJQD.js";import"./chunk-42XRJQM6.js";import"./chunk-OM7LH7AP.js";import"./chunk-QEESHRTS.js";import"./chunk-SODMQEHO.js";import"./chunk-ATQFN5HI.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch};
|