@code-yeongyu/senpi 2026.10.4 → 2026.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/bundle/chunks/{anthropic-messages-GE4OCV55.js → anthropic-messages-G5236QNK.js} +1 -1
- package/dist/bundle/chunks/{app-server-command-I2AKSC6I.js → app-server-command-3Q5G4CAF.js} +1 -1
- package/dist/bundle/chunks/{chunk-2CS2GZBE.js → chunk-2WV426OJ.js} +2 -2
- package/dist/bundle/chunks/{chunk-INGR4HFB.js → chunk-ECDLITEY.js} +2 -2
- package/dist/bundle/chunks/{chunk-6O26XO2C.js → chunk-EEOKVSNF.js} +220 -252
- package/dist/bundle/chunks/{chunk-MNLBL232.js → chunk-JVSOW4QU.js} +1 -1
- package/dist/bundle/chunks/chunk-K3BXFPWZ.js +2 -0
- package/dist/bundle/chunks/{chunk-QOT4HXY2.js → chunk-UHRXXTFZ.js} +3 -3
- package/dist/bundle/chunks/chunk-UUAKEDVS.js +14 -0
- package/dist/bundle/chunks/{chunk-ZKLQIAG5.js → chunk-UXIQK5NQ.js} +1 -1
- package/dist/bundle/chunks/chunk-WTJU5B2C.js +51 -0
- package/dist/bundle/chunks/chunk-YSPHACIN.js +2 -0
- package/dist/bundle/chunks/{cli-main-BLXUYHLQ.js → cli-main-VZWSUHFB.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-TQWU6DPG.js → help-fast-path-SHZJ3QWQ.js} +1 -1
- package/dist/bundle/chunks/{host-command-JXNOYPAC.js → host-command-7JIGGOWR.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-CSVSUAS7.js → interactive-mode-JA7AHYYL.js} +1 -1
- package/dist/bundle/chunks/multi-session-host-34WOINP4.js +23 -0
- package/dist/bundle/chunks/{openai-completions-2DUKDEVN.js → openai-completions-VSH22FCN.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-WCB4HIPI.js → openai-responses-WLBHCFYL.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-Q5EQZL7I.js → package-manager-cli-2QLVGQSC.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-VZLJIEP5.js → rotation-stream-JUCEXHWU.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-6VMXY46C.js → rpc-mode-QEBSN2OH.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-K3RWX652.js → session-control-endpoint-UGQIP6ZN.js} +1 -1
- package/dist/bundle/chunks/{session-picker-IPG3MKRC.js → session-picker-HX4LOJZ7.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +251 -242
- package/dist/bundle/cli.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-runtime.d.ts +5 -0
- package/dist/core/agent-session-runtime.js +5 -0
- package/dist/core/agent-session-services.d.ts +1 -0
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session.d.ts +14 -0
- package/dist/core/agent-session.js +31 -0
- package/dist/core/browser-engine.d.ts +7 -0
- package/dist/core/browser-engine.js +7 -0
- package/dist/core/continue-from-leaf.d.ts +18 -0
- package/dist/core/continue-from-leaf.js +30 -0
- package/dist/core/extensions/builtin/gpt-apply-patch/line-endings.d.ts +28 -0
- package/dist/core/extensions/builtin/gpt-apply-patch/line-endings.js +76 -0
- package/dist/core/extensions/builtin/gpt-apply-patch/parser.js +21 -23
- package/dist/core/extensions/builtin/gpt-apply-patch/patch-replace.js +5 -16
- package/dist/core/extensions/builtin/gpt-apply-patch/streaming-parser.js +3 -1
- package/dist/core/extensions/builtin/gpt-apply-patch/text.d.ts +8 -0
- package/dist/core/extensions/builtin/gpt-apply-patch/text.js +26 -3
- package/dist/core/extensions/builtin/gpt-apply-patch/types.d.ts +2 -0
- package/dist/core/extensions/builtin/terminal/tools/bash.d.ts +1 -0
- package/dist/core/extensions/builtin/terminal/tools/bash.js +8 -1
- package/dist/core/extensions/runner.d.ts +1 -0
- package/dist/core/extensions/runner.js +7 -0
- package/dist/core/extensions/types.d.ts +4 -0
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/sdk.d.ts +3 -0
- package/dist/core/sdk.js +1 -0
- package/dist/core/tools/bash.js +3 -0
- package/dist/main.js +1 -0
- package/dist/modes/interactive/components/session-selector.d.ts +11 -0
- package/dist/modes/interactive/components/session-selector.js +30 -5
- package/dist/modes/rpc/connection-handler.js +18 -1
- package/dist/modes/rpc/custom-capability.d.ts +9 -0
- package/dist/modes/rpc/custom-capability.js +9 -0
- package/dist/modes/rpc/host-daemon-env.js +2 -0
- package/dist/modes/rpc/host-idle-handover.js +1 -0
- package/dist/modes/rpc/media-placeholders.d.ts +23 -1
- package/dist/modes/rpc/media-placeholders.js +16 -13
- package/dist/modes/rpc/rpc-client.d.ts +8 -0
- package/dist/modes/rpc/rpc-client.js +8 -0
- package/dist/modes/rpc/rpc-input-validation.d.ts +6 -0
- package/dist/modes/rpc/rpc-input-validation.js +11 -0
- package/dist/modes/rpc/rpc-types.d.ts +19 -0
- package/dist/modes/rpc/session-command-router.js +11 -2
- package/dist/modes/rpc/session-event-writer.d.ts +4 -0
- package/dist/modes/rpc/session-event-writer.js +12 -1
- package/dist/modes/rpc/session-registry-attach.js +4 -0
- package/dist/modes/rpc/session-worker-client.d.ts +3 -0
- package/dist/modes/rpc/session-worker-client.js +6 -0
- package/dist/modes/rpc/session-worker-protocol.d.ts +5 -0
- package/dist/modes/rpc/session-worker.js +6 -0
- package/dist/modes/rpc/tool-media-store.d.ts +59 -0
- package/dist/modes/rpc/tool-media-store.js +190 -0
- package/dist/modes/rpc/worker-session-registry.js +8 -3
- package/docs/environment-variables.md +1 -0
- package/docs/rpc.md +62 -3
- package/package.json +7 -6
- package/dist/bundle/chunks/chunk-KMMECBM2.js +0 -15
- package/dist/bundle/chunks/chunk-LHYG7TK7.js +0 -2
- package/dist/bundle/chunks/chunk-LJWC5IVX.js +0 -2
- package/dist/bundle/chunks/chunk-PC3E2YS6.js +0 -9
- package/dist/bundle/chunks/multi-session-host-5AFJKSSM.js +0 -23
|
@@ -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
|
+
var forcedToolChoiceRefusals=new Set;function isRecord(value){return typeof value=="object"&&value!==null}function extractHttpStatus(error){if(!isRecord(error))return;let status=error.status;if(typeof status=="number")return status;let response=error.response;if(isRecord(response)&&typeof response.status=="number")return response.status}function errorMessage(error){return error instanceof Error?error.message:typeof error=="string"?error:String(error)}function isForcedToolChoiceUnsupportedError(error,sentForcedToolChoice){if(!sentForcedToolChoice||extractHttpStatus(error)!==400)return!1;let message=errorMessage(error);return/tool[_\s-]?choices?\b.*?(not\s+(?:currently\s+)?compatible|incompatible|not\s+(?:currently\s+)?supported|unsupported)/is.test(message)||/forces?\s+tool\s+use.*?(not\s+(?:currently\s+)?compatible|incompatible|not\s+(?:currently\s+)?supported|unsupported)/is.test(message)||/does\s+not\s+support\s+forced\s+tool[_\s-]?choices?/is.test(message)||/\bonly\s+[`"]*auto(?:matic)?[`"]*\s.{0,40}?tool[_\s-]?choice/is.test(message)||/thinking\s+may\s+not\s+be\s+enabled\s+when\s+tool[_\s-]?choice\s+forces\s+tool\s+use/is.test(message)||/tool[_\s-]?choice\s+cannot\s+force\s+tool\s+use/is.test(message)}function forcedToolName(toolChoice){if(!isRecord(toolChoice))return;let named=isRecord(toolChoice.function)?toolChoice.function.name:toolChoice.name;return typeof named=="string"&&named.length>0?named:void 0}function toolNames(tools){return Array.isArray(tools)?tools.map(tool=>{if(!isRecord(tool))return;let named=isRecord(tool.function)?tool.function.name:tool.name;return typeof named=="string"?named:void 0}):[]}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function refusalNamesForcedTool(error,params){if(extractHttpStatus(error)!==400)return!1;let name=forcedToolName(params.tool_choice);if(name===void 0)return!1;let message=errorMessage(error),index=toolNames(params.tools).indexOf(name);return index>=0&&new RegExp(`\\btools(?:\\.${index}|\\[${index}\\])(?!\\d)`).test(message)?!0:new RegExp(`['"\`]${escapeRegExp(name)}['"\`]`).test(message)}function omitToolChoiceParam(params){let nextParams={...params};return delete nextParams.tool_choice,nextParams}function refusalKey(target){return JSON.stringify([target.api,target.provider,target.baseUrl,target.id])}function hasRefusedForcedToolChoice(target){return forcedToolChoiceRefusals.has(refusalKey(target))}async function sendWithForcedToolChoiceFallback(request){let forced=request.isForced(request.params.tool_choice);if(forced&&(!request.acceptsForcedToolChoice||hasRefusedForcedToolChoice(request.target))){let params=omitToolChoiceParam(request.params);return{params,result:await request.send(params)}}try{return{params:request.params,result:await request.send(request.params)}}catch(error){if(!isForcedToolChoiceUnsupportedError(error,forced)&&!(forced&&refusalNamesForcedTool(error,request.params)))throw error;let params=omitToolChoiceParam(request.params),result=await request.send(params);return/thinking/i.test(errorMessage(error))||forcedToolChoiceRefusals.add(refusalKey(request.target)),{params,result}}}export{hasRefusedForcedToolChoice,sendWithForcedToolChoiceFallback};
|
|
@@ -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{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-
|
|
3
|
+
import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-EEOKVSNF.js";import"./chunk-UUAKEDVS.js";import"./chunk-QNAG7FYM.js";import"./chunk-WTJU5B2C.js";import{configureHttpDispatcher}from"./chunk-UXIQK5NQ.js";import"./chunk-LYYI74CY.js";import"./chunk-V2VQ4BHG.js";import"./chunk-K4AZKFRB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-ECDLITEY.js";import"./chunk-JABBHOD5.js";import"./chunk-2WV426OJ.js";import"./chunk-K3BXFPWZ.js";import"./chunk-QMRJYMNH.js";import"./chunk-6JXPZACL.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-JVSOW4QU.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-HKG7XL4H.js";import"./chunk-CIRZTP7W.js";import"./chunk-22DAHAHO.js";import"./chunk-XYDZ3LIE.js";import"./chunk-HB35RBP4.js";import"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-UHRXXTFZ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-YSPHACIN.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();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{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-
|
|
2
|
+
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-UHRXXTFZ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-6WCOSBI7.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
|
|
@@ -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{parseHostArgs,runHostCommand}from"./chunk-
|
|
2
|
+
import{parseHostArgs,runHostCommand}from"./chunk-2WV426OJ.js";import"./chunk-K3BXFPWZ.js";import"./chunk-QMRJYMNH.js";import"./chunk-6JXPZACL.js";import"./chunk-KUPQO7MC.js";import"./chunk-HKG7XL4H.js";import"./chunk-CIRZTP7W.js";import"./chunk-22DAHAHO.js";import"./chunk-XYDZ3LIE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-UHRXXTFZ.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-RKJNJ3GI.js";import"./chunk-6WCOSBI7.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,runHostCommand};
|
|
@@ -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{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-EEOKVSNF.js";import{isApiKeyLoginProvider}from"./chunk-UUAKEDVS.js";import"./chunk-QNAG7FYM.js";import"./chunk-WTJU5B2C.js";import"./chunk-UXIQK5NQ.js";import"./chunk-LYYI74CY.js";import"./chunk-V2VQ4BHG.js";import"./chunk-K4AZKFRB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import"./chunk-ECDLITEY.js";import"./chunk-JABBHOD5.js";import"./chunk-2WV426OJ.js";import"./chunk-K3BXFPWZ.js";import"./chunk-QMRJYMNH.js";import"./chunk-6JXPZACL.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-JVSOW4QU.js";import"./chunk-F6EQ7EV3.js";import"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-HKG7XL4H.js";import"./chunk-CIRZTP7W.js";import"./chunk-22DAHAHO.js";import"./chunk-XYDZ3LIE.js";import"./chunk-HB35RBP4.js";import"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-UHRXXTFZ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-YSPHACIN.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
|
|
@@ -0,0 +1,23 @@
|
|
|
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{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,runWithProviderScope,startHostChildReaper}from"./chunk-EEOKVSNF.js";import{DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,createRpcConnectionHandler,readCodemodeKernelRows,readMainThreadHeapBytes,readOwnFootprint}from"./chunk-UUAKEDVS.js";import"./chunk-QNAG7FYM.js";import{SessionManager,assertValidSessionId,liveToolMediaScope,omitInlineMedia,toolMediaPersister}from"./chunk-WTJU5B2C.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-UXIQK5NQ.js";import"./chunk-LYYI74CY.js";import"./chunk-V2VQ4BHG.js";import"./chunk-K4AZKFRB.js";import"./chunk-WIAXG52U.js";import"./chunk-U5KVIAHJ.js";import{buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError}from"./chunk-ECDLITEY.js";import"./chunk-JABBHOD5.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,GENERATION_HANDOFF_CAPABILITY,HostIdleHandover,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,beginHandoverResponse,computeRuntimeBuildId,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-2WV426OJ.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,WARM_CAPABILITY,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-K3BXFPWZ.js";import"./chunk-QMRJYMNH.js";import"./chunk-6JXPZACL.js";import"./chunk-UWYQPA26.js";import"./chunk-H4QOEVS5.js";import"./chunk-JVSOW4QU.js";import"./chunk-F6EQ7EV3.js";import{killTrackedDetachedChildren}from"./chunk-JEZWV7JW.js";import"./chunk-S2TCHQTE.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import{ClientOccupancy,armHostWatchdog,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-HKG7XL4H.js";import"./chunk-CIRZTP7W.js";import{PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-22DAHAHO.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-XYDZ3LIE.js";import"./chunk-HB35RBP4.js";import"./chunk-7Q3EY6HH.js";import"./chunk-6SMU7ANE.js";import"./chunk-MH2BFYGN.js";import"./chunk-26UBFF6N.js";import"./chunk-UHRXXTFZ.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KC5TT7DH.js";import"./chunk-KEMQXWPY.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-463OK2Y4.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-RKJNJ3GI.js";import"./chunk-CWLCGRUS.js";import"./chunk-6WCOSBI7.js";import"./chunk-YSPHACIN.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-2WEI2XTZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-XL5KIYQF.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);return beginHandoverResponse(parsed.id,typeof request=="string"?request:await this.handover.begin(request))}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB",DEFAULT_HOST_RSS_WARN_MB=4096,HOST_MEMORY_SAMPLE_MS=3e4,HOST_MEMORY_STDERR_INTERVAL_MS=5*6e4,BYTES_PER_MEGABYTE=1024*1024;function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readFootprint=options.readFootprint??readOwnFootprint,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.readKernels=options.readKernels??readCodemodeKernelRows,this.readMainHeap=options.readMainHeap??readMainThreadHeapBytes,this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??DEFAULT_HOST_RSS_WARN_MB}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),HOST_MEMORY_SAMPLE_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let footprint=this.readFootprint(),reading={footprintMb:Math.round(footprint.bytes/BYTES_PER_MEGABYTE),measure:footprint.measure,rssMb:Math.round(this.readRssBytes()/BYTES_PER_MEGABYTE),main:{heapBytes:this.readMainHeap()},kernels:this.readKernels()};if(reading.footprintMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(reading));let{footprintMb,measure,rssMb}=reading;this.emit({type:"host_memory_pressure",rssMb,footprintMb,measure,sessions,main:reading.main,kernels:reading.kernels});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<HOST_MEMORY_STDERR_INTERVAL_MS||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb} sessions=${sessions} (idle parking halved)
|
|
3
|
+
`))}};var ZERO_SESSION_TRIM_TICK_MS=1e3,ZERO_SESSION_TRIM_MIN_INTERVAL_MS=6e4,BYTES_PER_MEGABYTE2=1024*1024,ZeroSessionTrimmer=class{constructor(options){this.heldSessions=!1,this.options=options,this.now=options.now??Date.now}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.check(),ZERO_SESSION_TRIM_TICK_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}observe(size){size>0&&(this.heldSessions=!0)}check(){if(this.pending!==void 0&&this.report(this.pending),this.options.sessions()>0){this.heldSessions=!0;return}this.heldSessions&&(this.heldSessions=!1,!(this.lastTrimAt!==void 0&&this.now()-this.lastTrimAt<ZERO_SESSION_TRIM_MIN_INTERVAL_MS)&&this.trim())}trim(){let beforeBytes=this.readFootprint().bytes;this.pending={beforeBytes,collected:(this.options.collect??collectFully)()},this.lastTrimAt=this.now()}report(pending){this.pending=void 0;let after=this.readFootprint();this.options.emit({type:"host_trimmed",footprintBeforeMb:Math.round(pending.beforeBytes/BYTES_PER_MEGABYTE2),footprintAfterMb:Math.round(after.bytes/BYTES_PER_MEGABYTE2),measure:after.measure,collected:pending.collected})}readFootprint(){return(this.options.readFootprint??readOwnFootprint)()}};function collectFully(){let bun=Reflect.get(globalThis,"Bun"),bunGc=typeof bun=="object"&&bun!==null?Reflect.get(bun,"gc"):void 0;if(typeof bunGc=="function")return Reflect.apply(bunGc,bun,[!0]),!0;let nodeGc=Reflect.get(globalThis,"gc");return typeof nodeGc!="function"?!1:(Reflect.apply(nodeGc,globalThis,[]),!0)}var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4,BYTES_PER_MB=1024*1024;function describeWindow(processCpuMs,heapDeltaMb){return`cpu=${processCpuMs}ms heap=${heapDeltaMb>=0?"+":""}${heapDeltaMb}MB`}function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0,this.cpuMicrosAtTick=0,this.heapBytesAtTick=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.cpuUsage=options.cpuUsage??(()=>process.cpuUsage()),this.heapUsed=options.heapUsed??(()=>process.memoryUsage().heapUsed),this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){if(this.timer!==void 0)return;this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage();this.cpuMicrosAtTick=cpu.user+cpu.system,this.heapBytesAtTick=this.heapUsed(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.()}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage(),cpuMicros=cpu.user+cpu.system,heapBytes=this.heapUsed(),previousCpuMicros=this.cpuMicrosAtTick,previousHeapBytes=this.heapBytesAtTick;this.cpuMicrosAtTick=cpuMicros,this.heapBytesAtTick=heapBytes;let driftMs=Math.round(now-expectedAt);if(recordLoopBlockedMs(driftMs),driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark),processCpuMs=Math.round((cpuMicros-previousCpuMicros)/1e3),heapDeltaMb=Math.round((heapBytes-previousHeapBytes)/BYTES_PER_MB);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool,processCpuMs,heapDeltaMb}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)}; ${describeWindow(processCpuMs,heapDeltaMb)})
|
|
4
|
+
`))}};function startHostObservers(router,writer,options){let loopLag=new LoopLagWatchdog({emit:record=>writer.broadcastHostRecord(record)}),kernels=readCodemodeKernelRows,memory=new HostMemorySampler({emit:record=>writer.broadcastHostRecord(record),sessions:()=>router.sessionCount,onPressure:pressure=>router.setMemoryPressure(pressure),readKernels:kernels,...options.onIdlePressure?{onIdlePressure:options.onIdlePressure}:{}});router.setHostMemoryView({mainHeapBytes:readMainThreadHeapBytes,kernels});let{trim}=options;return loopLag.start(),memory.start(),trim.start(),{stop:()=>{loopLag.stop(),memory.stop(),trim.stop()}}}function createZeroSessionTrim(writer,sessions){return new ZeroSessionTrimmer({emit:record=>writer.broadcastHostRecord(record),sessions})}import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code){return{id:command.id,type:"response",command:"warm",success:!1,error:code}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
|
|
5
|
+
`)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),handler=await runWithProviderScope(entry.scope,async()=>{let taggedSink={writeRaw:bindToProviderScope(enqueueRecords),waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),...options})});return await handler.ready,{handle:command=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}import{existsSync}from"node:fs";import{isAbsolute as isAbsolute2}from"node:path";var RpcSessionRegistryError=class extends Error{constructor(code,reason,detail){super(code==="open_failed"&&reason?`${code}: ${reason}`:code),this.code=code,this.name="RpcSessionRegistryError",detail&&(this.detail=detail)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}async function attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now){let existing=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="open");if(!existing)throw new RpcSessionRegistryError("session_path_in_use");let[handle,entry]=existing,wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;if(entry.attachments+=1,pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),!entry.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return profile.promptSurface!==void 0&&profile.promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface:profile.promptSurface}),entry.runtime?.setPromptSurface(profile.promptSurface)),profile.browserEngine!==void 0&&profile.browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine:profile.browserEngine}),entry.runtime?.setBrowserEngine(profile.browserEngine)),entry.lastCommandAt=now,wasParked&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed")),await entry.lifecycleMutex),{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,attached:!0}}function syncRuntimeMetadata(entries,reservations,pathReservations){for(let entry of entries){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(reservations.delete(entry.reservationKey),pathReservations?.release(entry.reservationKey)),currentKey&&(reservations.add(currentKey),pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}async function settleClosingReservation(entries,sessionPath,closeGraceMs){let closing=[...entries].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve=>{deadline=setTimeout(resolve,closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}function createEntrySwitchSession(entry,createRuntime,syncRuntimeMetadata2){return(sessionPath,options)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath,options);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),runtime.releaseSessionHold(),entry.runtime=replacement,syncRuntimeMetadata2(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation}}function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle,cause){process.stderr.write(`senpi rpc session ${handle} teardown failed: ${String(cause)}
|
|
6
|
+
`)}function beginSessionClose(host,handle,onRole,options){let entry=host.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry.reservationKey&&!sessionIsWriting(entry)&&host.markDetached(entry.reservationKey),entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve=>{entry.closeResolve=resolve}),entry)}function closeSession(host,handle){return beginSessionClose(host,handle).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle)}function closeMarkedSession(host,handle){host.sync();let entry=host.get(handle);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await disposeOnce().catch(()=>{}),await entry.scope.close?.())},release=()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.state="closed",host.delete(handle),entry.reservationKey&&host.releaseReservation(entry.reservationKey))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle,cause)}})(),settled=!1,finish=()=>{settled||(settled=!0,release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle,cause)),graceful.catch(cause=>reportDetachedFailure(handle,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>{reportDetachedFailure(handle,cause),finish()}),completion}var RpcSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new Set,this.nextHandle=0,options.createRuntime.prepare&&(this.warm=createRegistryWarm(options.createRuntime.prepare,{agentDir:options.agentDir,...options.mcpRegistry!==void 0?{mcpRegistry:options.mcpRegistry}:{}})),this.options=options.mcpRegistry===void 0?options:{...options,createRuntime:runtimeOptions=>options.createRuntime({...runtimeOptions,mcpRegistry:options.mcpRegistry})},this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle=>this.entries.get(handle),delete:handle=>{let deleted=this.entries.delete(handle);return this.options.onSizeChange?.(this.entries.size),deleted},releaseReservation:key=>{this.reservations.delete(key),this.options.pathReservations?.release(key)},markDetached:key=>this.options.pathReservations?.setAttached(key,!1),sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}async openSession(profile,options){this.validateProfile(profile),this.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalSessionPath(profile.sessionPath):void 0,requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(sessionPath!==void 0&&entry2.reservationKey===sessionPath))throw new RpcSessionRegistryError("session_id_in_use")}if(sessionPath&&await settleClosingReservation(this.entries.values(),sessionPath,this.closeGraceMs),sessionPath&&this.reservations.has(sessionPath))return attachToOpenSession(this.entries,sessionPath,profile,options,this.options.pathReservations,this.now());if(sessionPath){this.reservations.add(sessionPath);let holder=this.options.pathReservations?await this.options.pathReservations.claim(sessionPath):void 0;if(holder)throw this.reservations.delete(sessionPath),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}let isResume=sessionPath!==void 0&&existsSync(sessionPath),sessionStartEvent=isResume?{type:"session_start",reason:"resume"}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,handle=`rpc-${++this.nextHandle}`,entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve()};entry.switchSession=createEntrySwitchSession(entry,this.options.createRuntime,()=>this.syncRuntimeMetadata()),requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),this.entries.set(handle,entry),this.options.onSizeChange?.(this.entries.size);try{let newSessionOptions=requestedDurableId!==void 0?{id:requestedDurableId}:void 0,manager=sessionPath?SessionManager.open(sessionPath,void 0,storedProfile.cwd,newSessionOptions):SessionManager.create(storedProfile.cwd,void 0,newSessionOptions);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(this.options.createRuntime,{cwd:manager.getCwd(),agentDir:this.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),entry.state="open",{sessionId:handle,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{this.entries.delete(handle),this.options.onSizeChange?.(this.entries.size),sessionPath&&(this.reservations.delete(sessionPath),this.options.pathReservations?.release(sessionPath))}}throw error2 instanceof RpcSessionRegistryError?error2:new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0)}}peek(handle){return this.entries.get(handle)}getForCommand(handle,command){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return entry.lastCommandAt=this.now(),entry}beginClose(handle,onRole,options){return beginSessionClose(this.teardownHost,handle,onRole,options)}async close(handle){return closeSession(this.teardownHost,handle)}async closeMarked(handle){return closeMarkedSession(this.teardownHost,handle)}list(){return this.syncRuntimeMetadata(),[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}))}syncRuntimeMetadata(){syncRuntimeMetadata(this.entries.values(),this.reservations,this.options.pathReservations)}validateProfile(profile){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");if(profile.durableSessionId!==void 0)try{assertValidSessionId(profile.durableSessionId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}}};var NOTHING_DROPPED={deliveries:[],user_messages:[]};function takeQueuedInput(session){let admittedBefore=session.externalAdmission.list().pending,cleared=session.clearQueue({abortWillFollow:!0}),stillAdmitted=new Set(session.externalAdmission.list().pending);return{deliveries:admittedBefore.filter(deliveryId=>!stillAdmitted.has(deliveryId)),user_messages:cleared.ordered.map(queued=>queued.text)}}async function abortAndSettle(port,sessionId,session){session.abortBash();let stopStarts=session.subscribe(event=>{event.type==="agent_start"&&session.abort()}),deadline,expired=new Promise(resolve=>{deadline=setTimeout(resolve,1e4)});try{await Promise.race([Promise.allSettled([session.abort().then(()=>session.waitForIdle()),port.otherRequestsSettled(sessionId),...port.pendingPrompts(sessionId)]),expired])}finally{clearTimeout(deadline),stopStarts()}}var SESSION_RELEASED_ENTRY_TYPE="session_released",RELEASED_ADMISSION_CLOSED="release_session handed this session to another runtime; deliver there instead (admission is closed here)",RELEASE_QUEUED_HINT="queued user input is still owed a turn; release with interrupt: true to take it out and receive it in dropped.user_messages";async function releaseSession(port,command){if(command.reason!=="takeover")return refusal2(command.id,RPC_ERROR_INVALID_RELEASE_REASON);if(port.draining())return refusal2(command.id,RPC_ERROR_HOST_DRAINING);let first=releasable(port,command,void 0);if(!("session"in first))return first;let busy=busySignals(port,command.sessionId,first.session),interrupted=busy.length>0;if(interrupted&&command.interrupt!==!0)return refusal2(command.id,busyCode(busy),{attachments:first.attachments,...busyData(busy)});let admission=first.session.externalAdmission,dropped=NOTHING_DROPPED,answer;try{interrupted&&(admission.close(RELEASED_ADMISSION_CLOSED),dropped=takeQueuedInput(first.session),await abortAndSettle(port,command.sessionId,first.session));let manager=first.session.sessionManager;return manager.isTranscriptFlushed()||await manager.persistHeaderNow(),answer=await claimAndRelease(port,command,interrupted,dropped),answer}catch(cause){return answer=refusal2(command.id,RPC_ERROR_RELEASE_FAILED,{detail:cause instanceof Error?cause.message:String(cause),...interrupted?{interrupted:!0,dropped}:{}}),answer}finally{answer?.success!==!0&&admission.reopen()}}async function claimAndRelease(port,command,interrupted,dropped){let taken=interrupted?{interrupted:!0,dropped}:void 0,ready=releasable(port,command,taken);if(!("session"in ready))return ready;let stillBusy=busySignals(port,command.sessionId,ready.session);if(stillBusy.length>0)return refusal2(command.id,busyCode(stillBusy),{attachments:ready.attachments,...busyData(stillBusy),interrupted,...taken});let admission=ready.session.externalAdmission;admission.close(RELEASED_ADMISSION_CLOSED);try{ready.session.sessionManager.appendCustomEntry(SESSION_RELEASED_ENTRY_TYPE,{reason:command.reason,interrupted,attachments:ready.attachments,host_instance:port.hostInstance??null,released_at:new Date().toISOString()})}catch(cause){throw admission.reopen(),cause}return await port.tearDown(command.sessionId,ready.sessionPath)?{id:command.id,type:"response",command:"release_session",success:!0,data:{released:!0,session_path:ready.sessionPath,attachments:ready.attachments,dropped}}:refusal2(command.id,RPC_ERROR_SESSION_CLOSING,taken)}function busySignals(port,sessionId,session){let activity=session.activitySnapshot,signals=[];return activity.isStreaming&&signals.push("turn"),port.pendingPrompts(sessionId).length>0&&signals.push("prompt"),session.pendingMessageCount>0&&signals.push("queued"),session.externalAdmission.list().pending.length>0&&signals.push("delivery"),activity.isBashRunning&&signals.push("bash"),activity.isCompacting&&signals.push("compaction"),activity.hasSessionWork&&signals.push("session_work"),signals.length===0&&isHandoffBusy(activity)&&signals.push("activity"),port.otherRequests(sessionId)>0&&signals.push("request"),signals}function busyData(signals){return signals.includes("queued")?{busy:signals,retry_with:{interrupt:!0},hint:RELEASE_QUEUED_HINT}:{busy:signals}}function busyCode(signals){return signals.some(signal=>signal==="turn"||signal==="prompt"||signal==="queued"||signal==="delivery")?RPC_ERROR_TURN_ACTIVE:RPC_ERROR_SESSION_BUSY}function releasable(port,command,taken){let refuse=(code,data)=>refusal2(command.id,code,data||taken?{...data,...taken}:void 0),entry;try{entry=port.lookup(command.sessionId)}catch(cause){return refuse(port.code(cause))}if(entry.state!=="open")return refuse(RPC_ERROR_SESSION_CLOSING);let session=entry.runtime?.session;if(session===void 0)return refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"worker_runtime"});let sessionPath=entry.sessionPath??session.sessionFile;return sessionPath===void 0?refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"no_session_file"}):entry.attachments>0&&command.force!==!0?refuse(RPC_ERROR_ATTACHED,{attachments:entry.attachments}):{session,sessionPath,attachments:entry.attachments}}function refusal2(id,code,data){return{id,type:"response",command:"release_session",success:!1,error:code,...data&&{errorCode:code,errorData:data}}}function selectSweepEvictions(registry,now,idleEvictionMs){let idle=[],orphaned=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open")continue;let entry=registry.peek(sessionId);if(entry){if(entry.attachments===0&&sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)){orphaned.push(sessionId);continue}if(Number.isFinite(idleEvictionMs)){if(entry.worker?.busy||entry.runtime?.session.isSessionBusy){entry.lastCommandAt=now;continue}now-entry.lastCommandAt>=idleEvictionMs&&idle.push(sessionId)}}}return{idle,orphaned}}var DRAIN_SWEEP_MS=50;function error(id,command,code,data){return{id,type:"response",command,success:!1,error:code,...data&&{errorCode:code,errorData:data}}}var SessionCommandRouter=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.canExitWhenEmpty=idle?.canExitWhenEmpty,Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>this.sweepIdleSessions(),tickMs),this.sweepTimer.unref?.()}}get sessionCount(){return this.registry.size}setHostMemoryView(view){this.hostMemoryView=view}sessionMemory(sessionId){let view=this.hostMemoryView;if(view===void 0)return{main_heap_bytes:0,kernel_heap_bytes:0,kernel_count:0};let kernels=view.kernels().filter(kernel=>kernel.sessionId===sessionId),kernelHeapBytes=0;for(let kernel of kernels)kernelHeapBytes+=kernel.liveBytes;return{main_heap_bytes:view.mainHeapBytes(),kernel_heap_bytes:kernelHeapBytes,kernel_count:kernels.length}}beginDrain(){this.draining=!0,this.stopSweep(),this.drainTimer===void 0&&!this.drainExitRequested&&(this.drainTimer=setInterval(()=>this.sweepDrain(),DRAIN_SWEEP_MS),this.drainTimer.unref?.()),this.sweepDrain()}sweepDrain(){if(this.activeRequests.has(void 0))return;let verdicts=readDrainVerdicts(this.registry,sessionId=>this.activeRequests.has(sessionId));if(verdicts){for(let sessionId of verdicts.gone)this.parkForHandoff(sessionId,"session_dir_removed");for(let sessionId of verdicts.park)this.parkForHandoff(sessionId,"handoff_parked");this.registry.size>0||this.handoffParks>0||this.finalizations.size>0||(this.drainTimer!==void 0&&(clearInterval(this.drainTimer),this.drainTimer=void 0),this.stopSweep(),!this.drainExitRequested&&(this.drainExitRequested=!0,this.onEmptyExit?.()))}}parkForHandoff(sessionId,reason){this.handoffClosed.add(sessionId),this.handoffParks++,this.evictIdleSession(sessionId,reason).catch(cause=>{process.stderr.write(`senpi rpc handoff park ${sessionId} failed: ${String(cause)}
|
|
7
|
+
`)}).finally(()=>{this.handoffParks--,this.sweepDrain()})}setMemoryPressure(pressure){this.memoryPressure=pressure}handle(command){let sessionId="sessionId"in command?command.sessionId:void 0;return this.draining&&sessionId!==void 0&&this.handoffClosed.has(sessionId)?Promise.resolve(void 0):this.draining&&command.type==="open_session"?Promise.resolve(error(command.id,command.type,"host_draining")):command.type==="warm"?answerWarm(command,{draining:this.draining,warm:this.registry.warm,cwd:this.defaults.cwd,hostContext:this.defaults.hostContext}):(this.activeRequests.set(sessionId,(this.activeRequests.get(sessionId)??0)+1),runWithSessionAttribution({sessionId},()=>this.dispatch(command)).finally(()=>{let remaining=(this.activeRequests.get(sessionId)??1)-1;if(remaining>0?this.activeRequests.set(sessionId,remaining):this.activeRequests.delete(sessionId),sessionId!==void 0)for(let listener of this.requestSettledListeners.get(sessionId)??[])listener();this.draining&&this.sweepDrain()}))}async dispatch(command){if(command.type==="get_protocol_info"){let capabilities=new Set(["multi_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,BROWSER_ENGINE_CAPABILITY,ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,...this.registry.warm?[WARM_CAPABILITY]:[],...this.connectionOptions?.capabilities??[]]);return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities:[...capabilities],mode:"multi",...protocolIdentity(),memory_pressure:this.memoryPressure}}}if(command.type==="list_sessions"){let withMemory=this.registry.list().map(row=>({...row,memory:this.sessionMemory(row.sessionId)})),sessions=command.include_workers===!0?withMemory:withMemory.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="open_session")return this.openWithBarrier(command);if(command.type==="close_session")return this.close(command);if(command.type==="release_session")return releaseSession({draining:()=>this.draining,hostInstance:this.defaults.hostContext?.host_instance,lookup:sessionId=>this.registry.getForCommand(sessionId,"release_session"),code:cause=>this.code(cause),otherRequests:sessionId=>Math.max(0,(this.activeRequests.get(sessionId)??1)-1),otherRequestsSettled:sessionId=>this.otherRequestsSettled(sessionId),pendingPrompts:sessionId=>this.bindings.get(sessionId)?.pendingPrompts?.()??[],tearDown:(sessionId,sessionPath)=>this.tearDownReleased(sessionId,sessionPath)},command);if(command.type==="set_client_info"&&!command.sessionId){let connection=this.writer.currentConnection();return connection!==void 0&&(this.pendingCapabilities.set(connection,command.capabilities??[]),this.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0}}if(!command.sessionId)return error(command.id,command.type,RPC_ERROR_MISSING_SESSION_ID);try{this.registry.getForCommand(command.sessionId,command.type);let binding=this.bindings.get(command.sessionId);if(!binding)return error(command.id,command.type,RPC_ERROR_UNKNOWN_SESSION);await binding.handle(command);return}catch(cause){return error(command.id,command.type,this.code(cause))}}async dispose(){this.drainExitRequested=!0,this.stopSweep(),this.drainTimer!==void 0&&clearInterval(this.drainTimer),await Promise.all([...this.bindings.entries()].map(async([sessionId,binding])=>{let claim=this.tryClaimClose(sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await this.finalizeClose(sessionId,binding,()=>this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId))})),this.bindings.clear()}sweepIdleSessions(){let now=this.idleNow(),idleEvictionMs=this.memoryPressure?this.idleEvictionMs/2:this.idleEvictionMs,verdicts=selectSweepEvictions(this.registry,now,idleEvictionMs);for(let sessionId of verdicts.orphaned)this.evictIdleSession(sessionId,"session_dir_removed");for(let sessionId of verdicts.idle)this.evictIdleSession(sessionId);Number.isFinite(this.emptyExitMs)&&(this.registry.size===0&&(this.canExitWhenEmpty?.()??!0)?this.emptySince===void 0?this.emptySince=now:now-this.emptySince>=this.emptyExitMs&&(this.stopSweep(),this.onEmptyExit?.()):this.emptySince=void 0)}async evictIdleSession(sessionId,reason){let retained=this.registry.peek(sessionId),parkedPath=retained?.retainOnDisconnect===!0||reason==="handoff_parked"?retained?.sessionPath:void 0,handoff=reason==="handoff_parked"||reason==="session_dir_removed"&&this.draining,owners=handoff?[...this.sessionsByConnection].filter(([,owned])=>owned.has(sessionId)).map(([connection])=>connection):[],claim=this.tryClaimClose(sessionId,{drainAttachments:!0});if(!claim)return;let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),handoff||this.forgetSessionOwnership(sessionId),claim.finalizer?await this.finalizeClose(sessionId,binding,()=>parkedPath!==void 0&&reason===void 0?this.writer.parkSession(sessionId,parkedPath):this.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},reason??"idle_evicted",reason==="handoff_parked"?parkedPath:void 0)):await this.finalizations.get(sessionId)?.promise,handoff&&(this.forgetSessionOwnership(sessionId),await this.onHandoffParked?.(owners.filter(connection=>!this.sessionsByConnection.has(connection)))),this.writer.forgetSession(sessionId)}otherRequestsSettled(sessionId){return new Promise(resolve=>{let listeners=this.requestSettledListeners.get(sessionId)??new Set,check=()=>{(this.activeRequests.get(sessionId)??0)>1||(listeners.delete(check),listeners.size===0&&this.requestSettledListeners.delete(sessionId),resolve())};listeners.add(check),this.requestSettledListeners.set(sessionId,listeners),check()})}async tearDownReleased(sessionId,sessionPath){let claim=this.tryClaimClose(sessionId,{drainAttachments:!0});if(!claim)return!1;let binding=this.bindings.get(sessionId);return binding?.cancelPendingExtensionUiRequests?.(),this.forgetSessionOwnership(sessionId),claim.finalizer?await this.finalizeClose(sessionId,binding,()=>this.writer.releaseSession(sessionId,sessionPath)):await this.finalizations.get(sessionId)?.promise,this.writer.forgetSession(sessionId),!0}forgetSessionOwnership(sessionId){for(let[connection,owned]of this.sessionsByConnection)owned.delete(sessionId),owned.size===0&&this.sessionsByConnection.delete(connection)}stopSweep(){this.sweepTimer!==void 0&&(clearInterval(this.sweepTimer),this.sweepTimer=void 0)}openWithBarrier(command){let owner=this.writer.currentConnection();if(owner===void 0)return this.open(command);let resolveBarrier,barrier=new Promise(resolve=>{resolveBarrier=resolve}),opens=this.opensByConnection.get(owner)??new Set,inFlight=0;for(let pending of this.opensByConnection.values())inFlight+=pending.size;return opens.add(barrier),this.opensByConnection.set(owner,opens),command.id!==void 0&&this.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight}),this.open(command,owner).finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&this.opensByConnection.delete(owner)})}async open(command,owner){let kindError=sessionKindError(command.kind);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let promptSurfaceError=sessionPromptSurfaceError(command.promptSurface);if(promptSurfaceError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${promptSurfaceError}`);let browserEngineError=sessionBrowserEngineError(command.browserEngine);if(browserEngineError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${browserEngineError}`);let opened;try{opened=await this.registry.openSession({cwd:command.cwd??this.defaults.cwd,sessionPath:command.sessionPath,permissionPreset:command.permissionPreset??this.defaults.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:this.defaults.creationModel,initialThinkingLevel:command.thinkingLevel??this.defaults.initialThinkingLevel,sessionKind:command.kind,sessionContext:this.defaults.hostContext?{...command.context,...this.defaults.hostContext}:command.context,...command.durableSessionId!==void 0?{durableSessionId:command.durableSessionId}:{},...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{},...command.promptSurface!==void 0?{promptSurface:command.promptSurface}:{},...command.browserEngine!==void 0?{browserEngine:command.browserEngine}:{}},{retainOnDisconnect:command.retain_on_disconnect===!0});let openedSession=opened,entry=this.registry.getForCommand(openedSession.sessionId,"open_session");if(this.writer.setSessionKind(openedSession.sessionId,entry.kind),this.writer.setSessionMedia(openedSession.sessionId,toolMediaPersister(()=>liveToolMediaScope(entry))),owner!==void 0&&(this.writer.hasRegisteredConnectionCapabilities(owner)||this.writer.setConnectionCapabilities(owner,this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]),this.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=this.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),this.sessionsByConnection.set(owner,owned)}if(!this.bindings.has(openedSession.sessionId)){this.bindings.set(openedSession.sessionId,await this.createBinding(openedSession.sessionId,entry,this.writer,()=>{this.close({type:"close_session",sessionId:openedSession.sessionId})},{...this.connectionOptions,capabilities:owner!==void 0?this.pendingCapabilities.get(owner)??this.connectionOptions?.capabilities??[]:this.connectionOptions?.capabilities,clientInfo:{setCapabilities:(connectionId,capabilities)=>{connectionId!==void 0&&(this.writer.setConnectionCapabilities(connectionId,capabilities),this.pendingCapabilities.set(connectionId,[...capabilities]))},connectionId:()=>this.writer.currentConnection()}})),entry.worker&&(entry.worker.bindingReady=!0);let settled=()=>{this.draining&&queueMicrotask(()=>this.sweepDrain())};typeof entry.worker?.subscribeSettled=="function"?entry.worker.subscribeSettled(settled):typeof entry.runtime?.session.subscribe=="function"&&entry.runtime.session.subscribe(event=>{(event.type==="agent_settled"||event.type==="agent_idle")&&settled()}),entry.worker&&entry.worker.exited.then(async()=>{await this.finalizations.get(openedSession.sessionId)?.promise,this.bindings.delete(openedSession.sessionId),this.forgetSessionOwnership(openedSession.sessionId),this.writer.forgetSession(openedSession.sessionId)})}!this.draining&&owner!==void 0&&this.releasedConnections.has(owner)&&(this.releaseOwnerAttachment(owner,openedSession.sessionId),await this.releaseOwnedSession(openedSession.sessionId));let state=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!state)throw new Error("Session state was not created");this.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened)try{await this.registry.close(opened.sessionId)}catch{}return error(command.id,"open_session",this.code(cause),this.detail(cause))}}async releaseConnection(connectionId){this.releasedConnections.add(connectionId),this.writer.clearConnectionCapabilities(connectionId);for(let sessionId of this.sessionsByConnection.get(connectionId)?.keys()??[])this.writer.detachConnectionFromSession(connectionId,sessionId);let opens=this.opensByConnection.get(connectionId),owned=this.sessionsByConnection.get(connectionId);if(this.sessionsByConnection.delete(connectionId),this.draining){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}if(owned===void 0){opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId);return}await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++){let live=this.registry.peek(sessionId),retained=live?.retainOnDisconnect===!0,session=live?.state==="open"?live.runtime?.session:void 0;if(!retained&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
|
|
8
|
+
`)})});continue}if(!retained&&session?.isStreaming){let released=!1,unsubscribe=session.subscribe(event=>{event.type!=="agent_settled"&&event.type!=="agent_idle"||released||(released=!0,unsubscribe(),this.releaseOwnedSession(sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred release for session ${sessionId} failed: ${String(cause)}
|
|
9
|
+
`)}))});continue}await this.releaseOwnedSession(sessionId)}})),opens&&await Promise.all([...opens]),this.releasedConnections.delete(connectionId)}async releaseOwnedSession(sessionId){let live=this.registry.peek(sessionId),parks=live?.state==="open"&&live.retainOnDisconnect===!0&&live.attachments===1,claim=this.tryClaimClose(sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){parks&&live.runtime&&(live.lifecycleMutex=live.lifecycleMutex.then(()=>live.runtime?.emitAttachmentEvent("session_parked")),await live.lifecycleMutex),await this.finalizations.get(sessionId)?.promise;return}let binding=this.bindings.get(sessionId);binding?.cancelPendingExtensionUiRequests?.(),await this.finalizeClose(sessionId,binding)}claimClose(sessionId,options){let finalizer=!0,onRole=isFinalizer=>{finalizer=isFinalizer,isFinalizer&&!this.finalizations.has(sessionId)&&this.finalizations.set(sessionId,this.createFinalization())},entry=this.registry.beginClose(sessionId,onRole,{detach:options.detach});for(;options.drainAttachments&&entry.state==="open";)entry=this.registry.beginClose(sessionId,onRole);return{finalizer:finalizer&&entry.state==="closing"}}tryClaimClose(sessionId,options){try{return this.claimClose(sessionId,options)}catch{return}}async close(command){let response={id:command.id,type:"response",command:"close_session",success:!0,data:{}},owner=this.writer.currentConnection();if(owner!==void 0&&this.sessionsByConnection.get(owner)?.has(command.sessionId)!==!0)return error(command.id,"close_session",RPC_ERROR_UNKNOWN_SESSION);let reply=this.writer.reserveCloseResponse(command.sessionId,response);if(!reply)return;let claim;try{claim=this.claimClose(command.sessionId,{drainAttachments:!1})}catch(cause){return reply.release(),error(command.id,"close_session",this.code(cause))}try{owner!==void 0&&this.releaseOwnerAttachment(owner,command.sessionId),claim.finalizer?await this.finalizeClose(command.sessionId,this.bindings.get(command.sessionId),()=>reply.complete(!0,"client_close")):(await this.finalizations.get(command.sessionId)?.promise,reply.complete(!1));return}finally{reply.release()}}releaseOwnerAttachment(owner,sessionId){this.writer.detachConnectionFromSession(owner,sessionId);let owned=this.sessionsByConnection.get(owner),count=owned?.get(sessionId);!owned||count===void 0||(count===1?owned.delete(sessionId):owned.set(sessionId,count-1),owned.size===0&&this.sessionsByConnection.delete(owner))}async finalizeClose(sessionId,binding,terminal){let finalization=this.finalizations.get(sessionId)??this.createFinalization();this.finalizations.set(sessionId,finalization);try{try{await binding?.dispose()}catch(cause){process.stderr.write(`senpi rpc binding dispose for session ${sessionId} failed: ${String(cause)}
|
|
10
|
+
`)}this.bindings.delete(sessionId);try{await this.registry.closeMarked(sessionId)}catch(cause){process.stderr.write(`senpi rpc close for session ${sessionId} failed: ${String(cause)}
|
|
11
|
+
`)}await this.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),this.finalizations.delete(sessionId)}}createFinalization(){let resolveFinalization;return{promise:new Promise(resolve=>{resolveFinalization=resolve}),resolve:()=>resolveFinalization?.()}}detail(cause){return cause instanceof RpcSessionRegistryError?cause.detail:void 0}code(cause){return cause instanceof RpcSessionRegistryError?cause.code===RPC_ERROR_OPEN_FAILED?cause.message:cause.code:cause instanceof Error&&[RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_SESSION_CLOSING].includes(cause.message)?cause.message:cause instanceof Error&&cause.message?`${RPC_ERROR_OPEN_FAILED}: ${cause.message}`:RPC_ERROR_UNKNOWN_SESSION}};import{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";var DEFAULT_QUEUE_BYTES=64*1024*1024,DEFAULT_STALL_MS=3e4,SocketEventQueueStallError=class extends Error{constructor(pendingBytes,stallMs){super(`socket event queue stalled: peer did not drain ${pendingBytes} queued bytes within ${stallMs}ms`),this.name="SocketEventQueueStallError",this.pendingBytes=pendingBytes,this.stallMs=stallMs}},SocketEventQueueOverflowError=class extends Error{constructor(queuedBytes,incomingBytes,maxQueueBytes,incomingPreview){super(`socket event queue overflow: ${queuedBytes} queued + ${incomingBytes} incoming > ${maxQueueBytes} (incoming: ${incomingPreview})`),this.name="SocketEventQueueOverflowError",this.queuedBytes=queuedBytes,this.incomingBytes=incomingBytes,this.maxQueueBytes=maxQueueBytes,this.incomingPreview=incomingPreview}},SocketEventSinkActor=class{constructor(sink,onFailure,maxQueueBytes=DEFAULT_QUEUE_BYTES,stallMs=DEFAULT_STALL_MS){this.queue=[],this.queuedBytes=0,this.closed=!1,this.sink=sink,this.onFailure=onFailure,this.maxQueueBytes=maxQueueBytes,this.stallMs=stallMs}enqueue(line,key,onWritten,demotedLine){if(this.closed)return;let bytes=Buffer.byteLength(line);if(key!==void 0){let existing=this.queue.find(entry=>entry.key===key);existing&&(existing.demotedLine!==void 0&&(this.queuedBytes-=existing.bytes,existing.line=existing.demotedLine,existing.bytes=Buffer.byteLength(existing.line),this.queuedBytes+=existing.bytes,existing.demotedLine=void 0),existing.key=void 0)}if(this.queuedBytes+bytes>this.maxQueueBytes){let overflow=new SocketEventQueueOverflowError(this.queuedBytes,bytes,this.maxQueueBytes,line.slice(0,120));this.closed=!0,this.queue.length=0,this.queuedBytes=0;try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"overflow, resync required"})}
|
|
12
|
+
`)}catch(cause){this.onFailure(cause)}this.onFailure(overflow);return}this.queue.push({line,bytes,key,demotedLine,onWritten}),this.queuedBytes+=bytes,this.drain()}async flush(){for(;this.draining;)await this.draining;if(this.failure!==void 0)throw this.failure}waitForAcceptance(){return Promise.resolve()}close(){this.closed=!0,this.queue.length=0,this.queuedBytes=0}waitForDrainOrStall(writtenBytes){return new Promise((resolve,reject)=>{let timer,blockedMark=loopBlockedMark(),onDeadline=()=>{let blockedMs=loopBlockedMsSince(blockedMark);if(blockedMs>0){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,Math.min(blockedMs,this.stallMs));return}let stall=new SocketEventQueueStallError(this.queuedBytes+writtenBytes,this.stallMs);try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"stalled, resync required"})}
|
|
13
|
+
`)}catch{}reject(stall)};timer=setTimeout(onDeadline,this.stallMs),this.sink.waitForBackpressure().then(()=>{clearTimeout(timer),resolve()},cause=>{clearTimeout(timer),reject(cause)})})}drain(){return this.draining?this.draining:(this.draining=(async()=>{try{for(;!this.closed&&this.queue.length>0;){let entry=this.queue.shift();this.queuedBytes-=entry.bytes,this.sink.writeRaw(entry.line),await this.waitForDrainOrStall(entry.bytes),entry.onWritten?.()}}catch(cause){this.failure=cause,this.closed=!0,this.queue.length=0,this.queuedBytes=0,this.onFailure(cause)}})().finally(()=>{this.draining=void 0,!this.closed&&this.queue.length>0&&this.drain()}),this.draining)}};var BROADCAST_LIFECYCLE_RECORDS=new Set(["agent_start","agent_settled","agent_idle","session_opened","session_closed"]);function snapshotPlaceholderLine(record){if(record.placeholderLine!==void 0)return record.placeholderLine;let redacted=record.source===void 0?void 0:omitInlineMedia(record.source);return record.placeholderLine=redacted===void 0||redacted===record.source?record.line:serializeJsonLine(redacted),record.placeholderLine}var SessionEventFanout=class{constructor(){this.connections=new Map,this.sessionSnapshots=new Map,this.pendingQuestions=new Map,this.connectionCapabilities=new Map,this.connectionSessions=new Map,this.registeredCapabilityConnections=new Set}registerConnection(id,connection,options={}){let actor=new SocketEventSinkActor(connection,cause=>{this.connections.get(id)?.actor===actor&&(this.connections.delete(id),this.connectionCapabilities.delete(id),this.connectionSessions.delete(id),this.registeredCapabilityConnections.delete(id)),process.stderr.write(`senpi rpc connection ${id} event queue failed; closing: ${cause instanceof Error?cause.message:String(cause)}
|
|
14
|
+
`),connection.close?.()},options.maxQueueBytes,options.stallMs);this.connections.set(id,{connection,actor}),this.connectionCapabilities.set(id,new Set),this.connectionSessions.set(id,new Set)}unregisterConnection(id){let registered=this.connections.get(id);registered&&(registered.actor.close(),this.connections.delete(id),this.connectionCapabilities.delete(id),this.connectionSessions.delete(id),this.registeredCapabilityConnections.delete(id))}attachConnectionToSession(id,sessionId){if(!this.connections.has(id))return;let sessions=this.connectionSessions.get(id)??new Set;if(!sessions.has(sessionId)){sessions.add(sessionId),this.connectionSessions.set(id,sessions),this.replaySnapshot(id,sessionId);for(let frame of this.pendingQuestions.get(sessionId)?.values()??[])this.connections.get(id)?.actor.enqueue(serializeJsonLine({...frame,remainingMs:typeof frame.deadlineAtMs=="number"?Math.max(0,frame.deadlineAtMs-Date.now()):0}))}}detachConnectionFromSession(id,sessionId){this.connectionSessions.get(id)?.delete(sessionId)}setConnectionCapabilities(id,capabilities){this.connections.get(id)&&(this.connectionCapabilities.set(id,new Set(capabilities)),this.registeredCapabilityConnections.add(id))}clearConnectionCapabilities(id){this.connections.has(id)&&(this.connectionCapabilities.set(id,new Set),this.registeredCapabilityConnections.delete(id))}hasRegisteredConnectionCapabilities(id){return this.registeredCapabilityConnections.has(id)}getConnectionCapabilities(id){if(this.registeredCapabilityConnections.has(id))return[...this.connectionCapabilities.get(id)??[]]}connectionHas(id,capability){return id===void 0?!1:this.connectionCapabilities.get(id)?.has(capability)??!1}targets(sessionId,targetId,isTargeted,recordType){return isTargeted?[targetId]:typeof recordType=="string"&&BROADCAST_LIFECYCLE_RECORDS.has(recordType)?this.connections.size>0?[...this.connections.keys()]:[void 0]:this.connections.size>0?[...this.connections.keys()].filter(id=>this.connectionSessions.get(id)?.has(sessionId)):[void 0]}get(id){return this.connections.get(id)}values(){return this.connections.values()}isEmpty(){return this.connections.size===0}broadcast(line){for(let{actor}of this.connections.values())actor.enqueue(line)}deliverToSession(sessionId,line){for(let[id,{actor}]of this.connections)this.connectionSessions.get(id)?.has(sessionId)&&actor.enqueue(line)}rememberSnapshot(sessionId,value,line,placeholderLine,source){if(value.type==="extension_ui_request"&&value.method==="question"&&typeof value.id=="string"){let pending=this.pendingQuestions.get(sessionId)??new Map;pending.set(value.id,{...value}),this.pendingQuestions.set(sessionId,pending);return}if(value.type==="question_resolved"&&typeof value.id=="string"){this.pendingQuestions.get(sessionId)?.delete(value.id);return}if(value.type==="question_updated"&&typeof value.id=="string"){let frame=this.pendingQuestions.get(sessionId)?.get(value.id);frame&&Object.assign(frame,{deadlineAtMs:value.deadlineAtMs,remainingMs:value.remainingMs});return}let event=value.assistantMessageEvent,record={line,placeholderLine,source};value.type==="message_start"||value.type==="message_update"&&event?.type==="text_start"?this.sessionSnapshots.set(sessionId,[record]):this.sessionSnapshots.has(sessionId)&&this.sessionSnapshots.get(sessionId)?.push(record),value.type==="message_end"&&this.sessionSnapshots.delete(sessionId)}forgetSession(sessionId){this.pendingQuestions.delete(sessionId),this.sessionSnapshots.delete(sessionId)}replaySnapshot(id,sessionId){let actor=this.connections.get(id)?.actor;if(!actor)return;let placeholders=this.connectionHas(id,MEDIA_PLACEHOLDERS_CAPABILITY);for(let record of this.sessionSnapshots.get(sessionId)??[])actor.enqueue(placeholders?snapshotPlaceholderLine(record):record.line)}};var SessionOpenTurns=class{constructor(){this.open=new Map}note(sessionId,type){if(type==="agent_start")this.open.set(sessionId,(this.open.get(sessionId)??0)+1);else if(type==="agent_settled"){let left=(this.open.get(sessionId)??0)-1;left>0?this.open.set(sessionId,left):this.open.delete(sessionId)}}take(sessionId){let owed=this.open.get(sessionId)??0;return this.open.delete(sessionId),owed}};var settleActors=actors=>Promise.all(actors.map(actor=>actor.flush().catch(()=>{}))).then(()=>{}),acceptActors=actors=>Promise.all(actors.map(actor=>actor.waitForAcceptance())).then(()=>{}),MAX_SHARED_STDIO_QUEUE_BYTES=64*1024*1024,MAX_SHARED_STDIO_QUEUE_RECORDS=4096,MESSAGE_KEY="message",COMPACT_DELTA_TYPES=new Set(["text_delta","thinking_delta","toolcall_delta"]);function compactDelta(value){if(value.type!=="message_update"||!Object.hasOwn(value,"message"))return;let event=value.assistantMessageEvent;if(typeof event!="object"||event===null)return;let typedEvent=event;if(!(typeof typedEvent.type!="string"||!COMPACT_DELTA_TYPES.has(typedEvent.type)||typeof typedEvent.contentIndex!="number"||typeof typedEvent.delta!="string"))return{type:typedEvent.type,contentIndex:typedEvent.contentIndex,delta:typedEvent.delta}}function demoteToDeltaOnly(value){let event=value.assistantMessageEvent;return{...value,message:null,assistantMessageEvent:{...event,partial:null}}}function toolUpdateKey(value){return value.type==="tool_execution_update"&&typeof value.toolCallId=="string"?`tool:${value.toolCallId}`:void 0}var SessionEventWriter=class{get pendingCloseRecordCount(){return this.reservedCloseRecords}get pendingCloseByteLength(){return this.reservedCloseBytes}constructor(writeRaw,waitOrSchedule,scheduleFlush){this.queues=new Map,this.fanout=new SessionEventFanout,this.connectionContext=new AsyncLocalStorage2,this.controlQueue={latestByKey:new Map,ready:!1},this.readyQueues=[],this.sealedSessions=new Set,this.workerSessions=new Set,this.openTurns=new SessionOpenTurns,this.mediaPersisters=new Map,this.flushScheduled=!1,this.controlOverflowReported=!1,this.closeOverflowReported=!1,this.closeOverflowActors=new WeakSet,this.reservedCloseRecords=0,this.reservedCloseBytes=0,this.writeRaw=writeRaw,waitOrSchedule&&scheduleFlush===void 0&&waitOrSchedule.length>0?this.scheduleFlush=waitOrSchedule:(this.waitForBackpressure=waitOrSchedule,this.scheduleFlush=scheduleFlush??(flush=>queueMicrotask(()=>{flush()})))}get bufferedRecordCount(){let count=this.inFlight?1:0;for(let queue of this.allQueues())for(let node=queue.head;node;node=node.next)count++;return count}get bufferedByteLength(){let bytes=this.inFlight?Buffer.byteLength(serializeJsonLine(this.inFlight.node.value)):0;for(let queue of this.allQueues())for(let node=queue.head;node;node=node.next)bytes+=Buffer.byteLength(serializeJsonLine(node.value));return bytes}registerConnection(id,connection,options={}){this.fanout.registerConnection(id,connection,options)}unregisterConnection(id){this.fanout.unregisterConnection(id)}attachConnectionToSession(id,sessionId){this.fanout.attachConnectionToSession(id,sessionId)}detachConnectionFromSession(id,sessionId){this.fanout.detachConnectionFromSession(id,sessionId)}setConnectionCapabilities(id,capabilities){this.fanout.setConnectionCapabilities(id,capabilities)}clearConnectionCapabilities(id){this.fanout.clearConnectionCapabilities(id)}hasRegisteredConnectionCapabilities(id){return this.fanout.hasRegisteredConnectionCapabilities(id)}getConnectionCapabilities(id){return this.fanout.getConnectionCapabilities(id)}setSessionMedia(sessionId,persister){persister===void 0?this.mediaPersisters.delete(sessionId):this.mediaPersisters.set(sessionId,persister)}setSessionKind(sessionId,kind){kind==="worker"?this.workerSessions.add(sessionId):this.workerSessions.delete(sessionId)}async flushConnection(id){let target=this.fanout.get(id);target&&await settleActors([target.actor])}withConnection(id,task){return this.connectionContext.run(id,task)}currentConnection(){return this.connectionContext.getStore()}enqueue(sessionId,value){if(this.sealedSessions.has(sessionId))return!1;let targetId=this.connectionContext.getStore(),record=value,isTargeted=record.type==="response"||record.type==="bash_execution_update"||record.type==="extension_ui_request"&&["select","confirm","input","editor"].includes(String(record.method)),tagged={...value,sessionId},line=serializeJsonLine(tagged);if(this.fanout.isEmpty()&&this.exceedsStdioCapacity(line))return this.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:"session_output_overflow, resync required"},"error"),!1;this.openTurns.note(sessionId,record.type);let targets=this.fanout.targets(sessionId,targetId,isTargeted,record.type),redacted=targets.some(target=>this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY))?omitInlineMedia(tagged,this.mediaPersisters.get(sessionId)):tagged,placeholderLine=redacted===tagged?void 0:serializeJsonLine(redacted);isTargeted||this.fanout.rememberSnapshot(sessionId,tagged,line,placeholderLine,tagged);for(let target of targets){if(target!==void 0&&!this.fanout.get(target))continue;let registered=target===void 0?void 0:this.fanout.get(target),wants=placeholderLine!==void 0&&this.fanout.connectionHas(target,MEDIA_PLACEHOLDERS_CAPABILITY);if(registered){let keyed=compactDelta(tagged)!==void 0&&tagged.message!==null;registered.actor.enqueue(wants?placeholderLine:line,keyed?MESSAGE_KEY:void 0,void 0,keyed?serializeJsonLine(demoteToDeltaOnly(tagged)):void 0)}else this.appendSessionRecord(sessionId,wants?redacted:tagged,target)}return this.requestFlush(),!0}waitForSessionBackpressure(sessionId){return this.fanout.isEmpty()?this.flush():acceptActors(this.sessionActors(sessionId))}sessionActors(sessionId){return[...new Set([...this.fanout.targets(sessionId,this.currentConnection(),!1,void 0),this.currentConnection()])].flatMap(target=>{let registered=target===void 0?void 0:this.fanout.get(target);return registered?[registered.actor]:[]})}enqueueControl(value){if(this.failure!==void 0)return Promise.reject(this.failure);let targetId=this.connectionContext.getStore(),registered=targetId===void 0?void 0:this.fanout.get(targetId);if(registered)return registered.actor.enqueue(serializeJsonLine(value)),Promise.resolve();if(this.exceedsStdioCapacity(serializeJsonLine(value)))return this.controlOverflowReported||(this.controlOverflowReported=!0,this.append(this.controlQueue,{type:"overflow",error:"rpc_control_output_overflow, resync required"}),this.markReady(this.controlQueue),this.requestFlush()),Promise.reject(new Error("rpc_control_output_overflow, resync required"));let queue=targetId===void 0?this.controlQueue:this.connectionQueue(targetId),completion=new Promise((resolve,reject)=>{this.append(queue,{...value},void 0,resolve,reject)});return this.markReady(queue),this.requestFlush(),completion}sendOpenQueued(connection,record){let wire={type:"queued",for_request:record.for_request,position:record.position,in_flight:record.in_flight},target=this.fanout.get(connection);target!==void 0&&(target.actor.enqueue(serializeJsonLine(wire)),this.requestFlush())}broadcastHostRecord(record){let wire;switch(record.type){case"host_superseded":wire={type:"host_superseded",instanceId:record.instanceId,generation:record.generation,successor:record.successor};break;case"host_stalled":wire={type:"host_stalled",driftMs:record.driftMs,...record.sessionId!==void 0?{sessionId:record.sessionId}:{},...record.tool!==void 0?{tool:record.tool}:{}};break;case"host_memory_pressure":wire={type:"host_memory_pressure",rssMb:record.rssMb,...record.footprintMb!==void 0?{footprintMb:record.footprintMb}:{},...record.measure!==void 0?{measure:record.measure}:{},sessions:record.sessions,...record.main!==void 0?{main:record.main}:{},...record.kernels!==void 0?{kernels:record.kernels}:{}};break;case"host_trimmed":wire={type:"host_trimmed",footprintBeforeMb:record.footprintBeforeMb,footprintAfterMb:record.footprintAfterMb,measure:record.measure,collected:record.collected};break;default:{let exhaustive=record;throw new Error(`unexpected host record ${exhaustive}`)}}this.fanout.isEmpty()?(this.append(this.controlQueue,wire),this.markReady(this.controlQueue)):this.fanout.broadcast(serializeJsonLine(wire)),this.requestFlush()}closeSession(sessionId,response,reason,sessionPath){if(!this.settleBeforeSeal(sessionId))return;this.sealedSessions.add(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId);let targetId=this.connectionContext.getStore(),lifecycle={type:"session_closed",sessionId,...reason&&{reason},...sessionPath&&{sessionPath}};this.fanout.isEmpty()?this.appendSessionRecord(sessionId,lifecycle):this.workerSessions.has(sessionId)?this.fanout.deliverToSession(sessionId,serializeJsonLine(lifecycle)):this.fanout.broadcast(serializeJsonLine(lifecycle));let taggedResponse={...response,sessionId},registered=targetId===void 0?void 0:this.fanout.get(targetId);registered?registered.actor.enqueue(serializeJsonLine(taggedResponse)):this.appendSessionRecord(sessionId,taggedResponse,targetId),this.requestFlush()}parkSession(sessionId,sessionPath){this.sealWithLifecycle(sessionId,{type:"session_parked",sessionId,sessionPath})}releaseSession(sessionId,sessionPath){this.sealWithLifecycle(sessionId,{type:"session_closed",sessionId,reason:"released",sessionPath})}sealWithLifecycle(sessionId,lifecycle){this.settleBeforeSeal(sessionId)&&(this.sealedSessions.add(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId),this.fanout.isEmpty()?this.appendSessionRecord(sessionId,lifecycle):this.workerSessions.has(sessionId)?this.fanout.deliverToSession(sessionId,serializeJsonLine(lifecycle)):this.fanout.broadcast(serializeJsonLine(lifecycle)),this.requestFlush())}reserveCloseResponse(sessionId,response,records=2){let bytes=Buffer.byteLength(serializeJsonLine({...response,sessionId}))+(records===2?Buffer.byteLength(serializeJsonLine({type:"session_closed",sessionId,reason:"client_close"})):0);if(this.bufferedRecordCount+this.reservedCloseRecords+records>MAX_SHARED_STDIO_QUEUE_RECORDS||this.bufferedByteLength+this.reservedCloseBytes+bytes>MAX_SHARED_STDIO_QUEUE_BYTES){let overflow={type:"overflow",command:"close_session",error:"rpc_close_output_overflow, resync required"},targetId=this.currentConnection();if(targetId!==void 0){let actor=this.fanout.get(targetId)?.actor;actor&&!this.closeOverflowActors.has(actor)&&(this.closeOverflowActors.add(actor),actor.enqueue(serializeJsonLine(overflow),void 0,()=>this.closeOverflowActors.delete(actor)))}else this.closeOverflowReported||(this.closeOverflowReported=!0,this.append(this.controlQueue,overflow),this.markReady(this.controlQueue),this.requestFlush());return}this.reservedCloseRecords+=records,this.reservedCloseBytes+=bytes;let active=!0,release=()=>{active&&(active=!1,this.reservedCloseRecords-=records,this.reservedCloseBytes-=bytes)};return{release,complete:(terminal,reason)=>{active&&(release(),terminal?this.closeSession(sessionId,response,reason):this.appendClosedResponse(sessionId,response))}}}enqueueClosedResponse(sessionId,response){this.reserveCloseResponse(sessionId,response,1)?.complete(!1)}appendClosedResponse(sessionId,response){let targetId=this.connectionContext.getStore(),taggedResponse={...response,sessionId},registered=targetId===void 0?void 0:this.fanout.get(targetId);registered?registered.actor.enqueue(serializeJsonLine(taggedResponse)):this.appendSessionRecord(sessionId,taggedResponse,targetId),this.requestFlush()}settleBeforeSeal(sessionId){if(this.sealedSessions.has(sessionId))return!1;for(let owed=this.openTurns.take(sessionId);owed>0;owed-=1)this.enqueue(sessionId,{type:"agent_settled",reason:"session_closed"});return!this.sealedSessions.has(sessionId)}forgetSession(sessionId){this.sealedSessions.delete(sessionId),this.openTurns.take(sessionId),this.workerSessions.delete(sessionId),this.fanout.forgetSession(sessionId),this.mediaPersisters.delete(sessionId)}flush(){if(this.failure!==void 0)return Promise.reject(this.failure);if(this.flushScheduled=!1,this.drainPromise)return this.drainPromise;if(this.readyQueues.length===0)return settleActors([...this.fanout.values()].map(({actor})=>actor));let resolveDrain,rejectDrain,drain=new Promise((resolve,reject)=>{resolveDrain=resolve,rejectDrain=reject});return this.drainPromise=drain,this.drainUntilEmpty().then(resolveDrain,rejectDrain),drain.then(()=>{this.drainPromise===drain&&(this.drainPromise=void 0),this.readyQueues.length>0&&this.requestFlush()},cause=>{this.drainPromise===drain&&(this.drainPromise=void 0),this.fail(cause)}),drain}async drainUntilEmpty(){do await this.drainReadyQueues();while(this.readyQueues.length>0);await settleActors([...this.fanout.values()].map(({actor})=>actor)),this.controlOverflowReported=!1,this.reservedCloseRecords===0&&(this.closeOverflowReported=!1)}async drainReadyQueues(){for(;this.readyQueues.length>0;){let queue=this.readyQueues.shift();queue.ready=!1;let node=queue.head;if(node){this.unlink(queue,node),this.inFlight={queue,node};try{let connection=queue.targetId?this.fanout.get(queue.targetId)?.connection:void 0,writeRaw=connection?.writeRaw??this.writeRaw,waitForBackpressure=connection?.waitForBackpressure??this.waitForBackpressure;!connection&&queue.targetId||(writeRaw(serializeJsonLine(node.value)),waitForBackpressure&&await waitForBackpressure()),node.resolve?.()}catch(cause){throw node.reject?.(cause),cause}finally{this.inFlight=void 0}if(queue.head)this.markReady(queue);else if(queue.sessionId||queue.targetId)for(let[key,candidate]of this.queues)candidate===queue&&this.queues.delete(key)}}}exceedsStdioCapacity(line){return this.bufferedRecordCount+this.reservedCloseRecords>=MAX_SHARED_STDIO_QUEUE_RECORDS||this.bufferedByteLength+this.reservedCloseBytes+Buffer.byteLength(line)>MAX_SHARED_STDIO_QUEUE_BYTES}connectionQueue(targetId){let key=`connection:${targetId}`,queue=this.queues.get(key);return queue||(queue={targetId,latestByKey:new Map,ready:!1},this.queues.set(key,queue)),queue}appendSessionRecord(sessionId,value,targetId){let key=`${targetId??"default"}:${sessionId}`,queue=this.queues.get(key);if(queue||(queue={sessionId,targetId,latestByKey:new Map,ready:!1},this.queues.set(key,queue)),compactDelta(value)){let previousFull=queue.latestByKey.get(MESSAGE_KEY);previousFull&&this.demoteAndMerge(queue,previousFull);let node=this.append(queue,value,MESSAGE_KEY);queue.latestByKey.set(MESSAGE_KEY,node),this.markReady(queue);return}let toolKey=toolUpdateKey(value);if(toolKey){let previous=queue.latestByKey.get(toolKey);previous&&this.unlink(queue,previous);let node=this.append(queue,value,toolKey);queue.latestByKey.set(toolKey,node),this.markReady(queue);return}queue.latestByKey.clear(),this.append(queue,value),this.markReady(queue)}demoteAndMerge(queue,node){node.value=demoteToDeltaOnly(node.value);let current=compactDelta(node.value),preceding=node.previous,previous=preceding?compactDelta(preceding.value):void 0;if(preceding&&previous&¤t&&preceding.value.message===null&&previous.type===current.type&&previous.contentIndex===current.contentIndex){let precedingEvent=preceding.value.assistantMessageEvent;preceding.value={...preceding.value,assistantMessageEvent:{...precedingEvent,delta:previous.delta+current.delta}},this.unlink(queue,node)}}append(queue,value,key,resolve,reject){let node={value,key,previous:queue.tail,resolve,reject};return queue.tail?queue.tail.next=node:queue.head=node,queue.tail=node,node}unlink(queue,node){node.previous?node.previous.next=node.next:queue.head=node.next,node.next?node.next.previous=node.previous:queue.tail=node.previous,node.key&&queue.latestByKey.get(node.key)===node&&queue.latestByKey.delete(node.key),node.previous=void 0,node.next=void 0}markReady(queue){queue.ready||this.inFlight?.queue===queue||!queue.head||(queue.ready=!0,this.readyQueues.push(queue))}requestFlush(){this.failure!==void 0||this.flushScheduled||this.drainPromise||(this.flushScheduled=!0,this.scheduleFlush(()=>this.flush()))}fail(cause){if(this.failure===void 0){this.failure=cause;for(let queue of this.allQueues())for(let node=queue.head;node;node=node.next)node.reject?.(cause)}}*allQueues(){yield*this.queues.values(),yield this.controlQueue}};function socketSink(socket){let needsDrain=!1,cut=!1;return{writeRaw(chunk){!cut&&!socket.destroyed&&(needsDrain=!socket.write(chunk))},close(){if(cut||(cut=!0,socket.destroyed))return;socket.end();let grace=setTimeout(()=>socket.destroy(),5e3);grace.unref(),socket.once("close",()=>clearTimeout(grace))},waitForBackpressure(){return socket.destroyed||!needsDrain?Promise.resolve():(needsDrain=!1,new Promise(resolve=>{let done=()=>{socket.off("drain",done),socket.off("close",done),resolve()};socket.once("drain",done),socket.once("close",done)}))}}}import{isAbsolute as isAbsolute3}from"node:path";var SESSION_WORKER_LIMITS={workers:20,requests:64,controlRequests:4,controlBytes:1048576,requestBytes:16777216,outputBytes:16777216,reservations:64,openMs:3e4,controlMs:5e3},WORKER_CREDIT_CODES={granted:1,conflict:2,limit:3};var RESERVATION_DENIAL_CODES={conflict:"session_path_in_use",limit:"session_reservation_limit"},SessionPathReservations=class{constructor(){this.owners=new Map}owner(path){return this.owners.get(path)}count(handle){let count=0;for(let owner of this.owners.values())owner===handle&&count++;return count}reserve(handle,path,live){let owner=this.owners.get(path);return owner?owner===handle?"granted":"conflict":this.count(handle)>=SESSION_WORKER_LIMITS.reservations&&(!live||(this.reconcile(handle,live),this.count(handle)>=SESSION_WORKER_LIMITS.reservations))?"limit":(this.owners.set(path,handle),"granted")}reconcile(handle,live){for(let[path,owner]of this.owners)owner!==handle||path===live.sessionPath||live.livePaths.includes(path)||this.owners.delete(path)}releaseAll(handle){for(let[path,owner]of this.owners)owner===handle&&this.owners.delete(path)}};import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var SessionWorkerRequests=class{constructor(send,timeout){this.pending=new Map,this.serial=0,this.closed=!1,this.send=send,this.timeout=timeout}remainingOpenMs(){let now=Date.now();return this.openingDeadline===void 0&&(this.openingDeadline=now+SESSION_WORKER_LIMITS.openMs),Math.max(0,this.openingDeadline-now)}get activeCount(){return this.pending.size}request(message){if(this.closed)return Promise.reject(new Error("session_closing"));let control=message.type==="command"&&"type"in message.command&&typeof message.command.type=="string"&&["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(message.command.type),bytes=Buffer.byteLength(JSON.stringify(message)),count=0,pendingBytes=0;for(let pending of this.pending.values())pending.control===control&&(count++,pendingBytes+=pending.bytes);let maxCount=control?SESSION_WORKER_LIMITS.controlRequests:SESSION_WORKER_LIMITS.requests,maxBytes=control?SESSION_WORKER_LIMITS.controlBytes:SESSION_WORKER_LIMITS.requestBytes;if(count>=maxCount||pendingBytes+bytes>maxBytes)return Promise.reject(new Error("session_worker_request_limit"));let request=++this.serial;return new Promise((resolve,reject)=>{let timer=message.type==="command"&&!control?void 0:setTimeout(this.timeout,control?SESSION_WORKER_LIMITS.controlMs:this.remainingOpenMs());this.pending.set(request,{resolve,reject,bytes,control,timer});try{this.send({...message,request})}catch(cause){this.pending.delete(request),clearTimeout(timer),reject(cause instanceof Error?cause:new Error(String(cause)))}})}receive(message){let pending=this.pending.get(message.request);pending&&(clearTimeout(pending.timer),this.pending.delete(message.request),message.type==="result"&&message.error?pending.reject(new Error(message.error)):pending.resolve(message))}close(error2){this.closed=!0;for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(error2);this.pending.clear()}};function acknowledgeGrant(signal,grant){let state=new Int32Array(signal);Atomics.store(state,0,WORKER_CREDIT_CODES[grant]),Atomics.notify(state,0)}function acknowledge(signal,granted){acknowledgeGrant(signal,granted?"granted":"conflict")}var compiledWorkerEntry=typeof SENPI_RPC_SESSION_WORKER_ENTRY=="string"?SENPI_RPC_SESSION_WORKER_ENTRY:"./src/modes/rpc/session-worker.ts",SessionWorkerClient=class{constructor(callbacks){this.webviewBroker=createWebViewBroker(),this.worker=new Worker(isBunBinary?fileURLToPath(new URL(compiledWorkerEntry,import.meta.url)).replaceAll("\\","/"):new URL(import.meta.url.endsWith(".ts")?"./session-worker.ts":"./session-worker.js",import.meta.url),this.webviewBroker?{workerData:{webviewBroker:this.webviewBroker.port},transferList:[this.webviewBroker.port]}:{}),this.bindingReady=!1,this.requests=new SessionWorkerRequests(message=>this.worker.postMessage(message),()=>this.fail("session_worker_request_timeout")),this.stopped=!1,this.options={},this.listeners=new Set,this.cancelUiPending=!1,this.callbacks=callbacks,this.exited=new Promise(resolve=>{this.worker.once("exit",()=>{!this.stopped&&!this.closeTimer&&this.fail("session_worker_exited"),this.stopped=!0,this.closeTimer&&clearTimeout(this.closeTimer),this.requests.close(new Error("session_worker_exited")),this.webviewBroker?.dispose(),this.listeners.clear(),callbacks.exit(),this.publishTerminalFailure(),resolve()})}),this.worker.on("message",message=>this.receive(message)),this.worker.on("error",error2=>this.fail(error2 instanceof Error?error2.message:String(error2)))}async prepare(configuration,profile){let result=await this.request({type:"prepare",configuration,profile});if(result.type!=="prepared")throw new Error("Invalid worker prepare response");return result.sessionPath}async setPromptSurface(surface){if((await this.request({type:"prompt_surface",surface})).type!=="result")throw new Error("Invalid worker prompt_surface response")}async setBrowserEngine(engine){if((await this.request({type:"browser_engine",engine})).type!=="result")throw new Error("Invalid worker browser_engine response")}async commit(){let result=await this.request({type:"commit"});if(result.type!=="ready")throw new Error("Invalid worker commit response");return this.snapshot=result.snapshot,result.snapshot}async bind(sessionId,writer,requestClose,options){return this.sessionId=sessionId,this.writer=writer,this.requestClose=requestClose,this.options=options,await this.request({type:"bind",sessionId,capabilities:options.capabilities??[],connection:writer.currentConnection()}),{handle:async command=>{await this.request({type:"command",command,connection:writer.currentConnection()})},cancelPendingExtensionUiRequests:()=>this.post({type:"cancel_ui"}),dispose:async()=>{this.post({type:"cancel_ui"})}}}get busy(){return this.requests.activeCount>0||this.snapshot?.busy===!0}get handoffBusy(){return this.requests.activeCount>0||(this.snapshot?.handoffBusy??this.snapshot?.busy)===!0}subscribeSettled(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}close(graceMs){return this.stopped||this.closeTimer?this.exited:(this.post({type:"close"}),this.closeTimer=setTimeout(()=>this.quarantine(),graceMs),this.exited)}quarantine(){this.stopped=!0,this.requests.close(new Error("session_closing")),this.worker.terminate()}request(message){return this.requests.request(message)}post(message){if(!this.stopped){if(message.type==="cancel_ui"){if(this.cancelUiPending)return;this.cancelUiPending=!0}this.worker.postMessage(message)}}receive(message){if(this.stopped){"signal"in message&&acknowledge(message.signal,!1);return}switch(message.type){case"prepared":case"ready":case"result":{this.requests.receive(message);return}case"reserve":acknowledgeGrant(message.signal,this.callbacks.reserve(message.path));return;case"snapshot":if(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths),acknowledge(message.signal,!0),message.settled)for(let listener of[...this.listeners])listener();return;case"control_done":this.cancelUiPending=!1;return;case"output":{let writer=this.writer,sessionId=this.sessionId;if(!writer||!sessionId||this.stopped){acknowledge(message.signal,!1);return}message.snapshot?(this.snapshot=message.snapshot,this.callbacks.reconcile(message.snapshot.liveSessionPaths)):this.snapshot&&(this.snapshot={...this.snapshot,...message.activity,state:{...this.snapshot.state,isStreaming:message.activity.streaming}});let enqueue=()=>writer.enqueue(sessionId,message.record)?writer.waitForSessionBackpressure(sessionId):(acknowledge(message.signal,!1),this.fail("session_output_overflow_or_closed"),Promise.reject(new Error("session_output_overflow_or_closed")));(message.connection===void 0?enqueue():writer.withConnection(message.connection,enqueue)).then(()=>acknowledge(message.signal,!0),cause=>{acknowledge(message.signal,!1),this.fail(cause instanceof Error?cause.message:String(cause))});return}case"capabilities":this.options.clientInfo?.setCapabilities(message.connection,message.capabilities),acknowledge(message.signal,!0);return;case"request_close":this.requestClose?.();return;case"failure":this.fail(message.error);return}}fail(error2){this.stopped||(this.callbacks.failure(error2),this.terminalFailure=error2,this.writer&&this.sessionId&&this.writer.enqueue(this.sessionId,{type:"session_error",error:error2}),this.quarantine())}publishTerminalFailure(){let error2=this.terminalFailure,writer=this.writer,sessionId=this.sessionId;error2===void 0||!writer||!sessionId||(this.terminalFailure=void 0,writer.closeSession(sessionId,{type:"response",command:"close_session",success:!1,error:error2},"error"))}};var WorkerSessionRegistry=class{constructor(options){this.entries=new Map,this.reservations=new SessionPathReservations,this.serial=0,this.options=options,this.closeGraceMs=options.closeGraceMs,this.now=options.now,this.createWorker=options.createWorker??(callbacks=>new SessionWorkerClient(callbacks))}get size(){return this.entries.size}async openSession(profile,options){if(!isAbsolute3(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute3(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");let requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){try{assertValidSessionId(requestedDurableId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}let requestedKey=profile.sessionPath?this.knownReservationKey(profile.sessionPath):void 0;for(let entry2 of this.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(requestedKey!==void 0&&entry2.reservationKey===requestedKey))throw new RpcSessionRegistryError("session_id_in_use")}if(profile.sessionPath){let key=this.knownReservationKey(profile.sessionPath),owner=key?this.reservations.owner(key):void 0;if(key&&owner)return this.attach(owner,key,options,profile)}if(this.size>=SESSION_WORKER_LIMITS.workers)throw new Error("too_many_sessions");let handle=`rpc-${++this.serial}`,storedProfile=frozenProfile(profile),entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),cwd:profile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:this.now(),lifecycleMutex:Promise.resolve(),...requestedDurableId!==void 0?{durableSessionId:requestedDurableId}:{}},workerFailure,worker=this.createWorker({reserve:path=>this.reserve(handle,path),reconcile:livePaths=>this.reconcile(handle,livePaths),exit:()=>{this.entries.get(handle)===entry&&(entry.state="closed",this.entries.delete(handle),this.reservations.releaseAll(handle),entry.closeResolve?.())},failure:error2=>{workerFailure=error2,entry.state="quarantined",process.stderr.write(`senpi rpc session ${handle} quarantined: ${error2}
|
|
15
|
+
`)}});entry.worker=worker,this.entries.set(handle,entry);try{let path=await worker.prepare(this.options.configuration,profile),owner=this.reservations.owner(path);if(owner){let attached=await this.attach(owner,path,options,profile);return entry.state="quarantined",worker.quarantine(),attached}let grant=this.reserve(handle,path);if(grant!=="granted")throw new RpcSessionRegistryError(RESERVATION_DENIAL_CODES[grant]);entry.reservationKey=path,entry.requestedPathKey=profile.sessionPath?path:void 0,entry.sessionPath=path;let snapshot=await worker.commit();if(entry.state!=="opening")throw workerFailure===void 0?new RpcSessionRegistryError("session_closing"):new RpcSessionRegistryError("open_failed",workerFailure);return entry.durableSessionId=snapshot.state.sessionId,entry.cwd=snapshot.state.cwd,entry.state="open",this.openResult(handle,entry)}catch(cause){throw entry.state="quarantined",worker.quarantine(),cause}}peek(handle){return this.entries.get(handle)}getForCommand(handle,command){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="quarantined"||entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return entry.lastCommandAt=this.now(),entry}beginClose(handle,onRole,options){let entry=this.entries.get(handle);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"||entry.state==="quarantined")return onRole?.(!1),entry;if(entry.state!=="open"&&entry.state!=="opening")throw new RpcSessionRegistryError("unknown_session");return entry.attachments--,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry):(entry.state="closing",entry.closeCompletion=new Promise(resolve=>{entry.closeResolve=resolve}),onRole?.(!0),entry)}close(handle){return this.beginClose(handle).state==="closing"?this.closeMarked(handle):Promise.resolve()}async closeMarked(handle){let entry=this.entries.get(handle);if(entry?.state!=="closing"||!entry.worker)throw new RpcSessionRegistryError("unknown_session");if(entry.closeStarted)return entry.closeCompletion;entry.closeStarted=!0;let timer;await Promise.race([entry.worker.close(this.closeGraceMs),new Promise(resolve=>{timer=setTimeout(()=>{entry.state!=="closed"&&(entry.state="quarantined"),resolve()},this.closeGraceMs)})]),timer&&clearTimeout(timer)}list(){return[...this.entries].map(([sessionId,entry])=>{let state=entry.worker?.snapshot?.state;return{sessionId,durableSessionId:state?.sessionId??entry.durableSessionId,sessionPath:state?.sessionFile??entry.sessionPath,cwd:state?.cwd??entry.cwd,name:state?.sessionName,kind:entry.kind,context:entry.context,attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state}})}knownReservationKey(path){if(this.reservations.owner(path))return path;for(let entry of this.entries.values()){if(entry.profile.sessionPath===path&&entry.requestedPathKey&&this.reservations.owner(entry.requestedPathKey))return entry.requestedPathKey;let snapshot=entry.worker?.snapshot;if(snapshot?.state.sessionFile===path)return snapshot.sessionPath}}async attach(owner,path,options,requested={cwd:""}){let{promptSurface,browserEngine}=requested,entry=this.entries.get(owner);if(entry?.state!=="open"||!entry.worker?.bindingReady||entry.worker.snapshot?.sessionPath!==path)throw new RpcSessionRegistryError("session_path_in_use");promptSurface!==void 0&&promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface}),await entry.worker.setPromptSurface(promptSurface)),browserEngine!==void 0&&browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine}),await entry.worker.setBrowserEngine(browserEngine));let result=this.openResult(owner,entry);return entry.attachments++,options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),entry.lastCommandAt=this.now(),{...result,attached:!0}}reservationCount(handle){return this.reservations.count(handle)}reserve(handle,path){let entry=this.entries.get(handle);return entry?this.reservations.owner(path)===handle?"granted":entry.state!=="opening"&&entry.state!=="open"?"conflict":this.reservations.reserve(handle,path,this.liveWorkerPaths(entry)):"conflict"}reconcile(handle,livePaths){let entry=this.entries.get(handle);if(entry?.state!=="open")return;let sessionPath=entry.worker?.snapshot?.sessionPath;this.reservations.reconcile(handle,{livePaths,sessionPath}),sessionPath&&(entry.reservationKey=sessionPath,entry.sessionPath=sessionPath)}liveWorkerPaths(entry){let snapshot=entry.state==="open"?entry.worker?.snapshot:void 0;if(snapshot)return{livePaths:snapshot.liveSessionPaths,sessionPath:snapshot.sessionPath}}openResult(handle,entry){let state=entry.worker?.snapshot?.state;if(!state)throw new RpcSessionRegistryError("open_failed");return{sessionId:handle,durableSessionId:state.sessionId,sessionPath:state.sessionFile}}};var WINDOWS_SHUTDOWN_HARD_EXIT_MS=2e3;async function runMultiSessionHost(options){return runAsHostGenerationProcess(()=>options.listen===void 0||options.listen==="stdio://"?runStdioHost(options):runSocketHost(options,resolveSocketPath(options.listen,options.agentDir)))}function createHostCore(options,writer,capabilities=parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),idle={},hostContext,hooks={}){let policy=resolveHostIdlePolicy(process.env,idle),registry=options.workerConfiguration?new WorkerSessionRegistry({configuration:options.workerConfiguration,now:policy.now,closeGraceMs:idle.closeGraceMs??parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV])??1e4}):new RpcSessionRegistry({agentDir:options.agentDir,createRuntime:options.createRuntime,mcpRegistry:new HostMcpRegistry,now:policy.now,closeGraceMs:idle.closeGraceMs??parseIdleExitMs(process.env[RPC_CLOSE_GRACE_MS_ENV])??1e4,...hooks.onSessionCountChange?{onSizeChange:hooks.onSessionCountChange}:{},pathReservations:createEndpointReservations({agentDir:options.agentDir,socket:listenSocketPath(options),instanceId:hostInstanceId(),onFailure:hostLog})}),router=new SessionCommandRouter(registry,writer,hostContext?{...options,hostContext}:options,options.createBinding,{capabilities},{now:policy.now,idleEvictionMs:policy.idleEvictionMs,emptyExitMs:policy.emptyExitMs,onEmptyExit:idle.onEmptyExit,onHandoffParked:idle.onHandoffParked,canExitWhenEmpty:idle.canExitWhenEmpty}),gate=new HostCoreGate(registry,command=>router.handle(command),hooks);return{router,handle:async line=>{let parsed;try{parsed=JSON.parse(line)}catch(cause){await writer.enqueueControl(parseError(`Failed to parse command: ${errorMessage(cause)}`));return}if(await gate.intercept(parsed,answer=>writer.enqueueControl(answer)))return;let shapeError=rpcCommandShapeError(parsed);if(shapeError){await writer.enqueueControl(parseError(shapeError));return}let response=await gate.dispatch(parsed);response&&await writer.enqueueControl(response)},handover:gate.handover,handoverAnswered:()=>gate.answered()}}async function runStdioHost(options){takeOverStdout();let sink={writeRaw:writeRawStdout,waitForBackpressure:waitForRawStdoutBackpressure},writer=new SessionEventWriter(sink.writeRaw,sink.waitForBackpressure),runtimeBuildId=await startupRuntimeBuildId(),trim=createZeroSessionTrim(writer,()=>router.sessionCount),{router,handle}=createHostCore(options,writer,void 0,{onEmptyExit:()=>{shutdown(0)}},void 0,{...runtimeBuildId===void 0?{}:{runtimeBuildId},onSessionCountChange:size=>trim.observe(size)}),observers=startHostObservers(router,writer,{trim}),shuttingDown=!1,shutdown=async(exitCode=0)=>{shuttingDown&&process.exit(exitCode),shuttingDown=!0,observers.stop(),detach(),await router.dispose(),await writer.flush(),await flushRawStdout(),process.exit(exitCode)},onEnd=()=>{shutdown()};process.stdin.on("end",onEnd);let reportInputFailure=cause=>{process.stderr.write(`senpi rpc stdio request failed: ${errorMessage(cause)}
|
|
16
|
+
`)},detachReader=attachJsonlLineReader(process.stdin,line=>{handle(line).catch(reportInputFailure)},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>{writer.enqueueControl(parseError(oversizedLineError())).catch(reportInputFailure)}}),detach=()=>{detachReader(),process.stdin.off("end",onEnd)};return registerShutdownSignals(shutdown),new Promise(()=>{})}async function runSocketHost(options,socketPath){await prepareSocketPath(socketPath);let writer=new SessionEventWriter(()=>{}),connections=new Map,occupancy=new ClientOccupancy(()=>{}),draining=!1,handoffAnnounced=!1,hostContext=hostSessionContext(socketPath),runtimeBuildId=await startupRuntimeBuildId(),expected=process.env[EXPECTED_RUNTIME_BUILD_ID_ENV];expected!==void 0&&expected!==runtimeBuildId&&(hostLog(`runtime ${runtimeBuildId??"unreadable"} is not the handover target ${expected}; exiting`),process.exit(1));let canHandOver=runtimeBuildId!==void 0&&process.platform!=="win32",trim=createZeroSessionTrim(writer,()=>router.sessionCount),{router,handle,handover,handoverAnswered}=createHostCore(options,writer,[...parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),GENERATION_HANDOFF_CAPABILITY,...canHandOver?[RUNTIME_IDENTITY_HANDOVER_CAPABILITY]:[]],{onEmptyExit:()=>{shutdown(0)},canExitWhenEmpty:()=>draining||occupancy.attachedCount===0&&occupancy.unclassifiedCount===0,onHandoffParked:async ids=>{await Promise.all(ids.map(async id=>{await writer.flushConnection(id),connections.get(id)?.close()}))}},hostContext,{onSessionCountChange:size=>trim.observe(size),...runtimeBuildId!==void 0&&{runtimeBuildId},...canHandOver&&{handover:{identity:()=>({instanceId:hostInstanceId(),generation:hostGeneration(process.env),runtimeBuildId}),perform:request=>performIdleHandover({request,socket:readHostWatchdogConfigFromBrandEnv()?.publicSocket??socketPath,agentDir:options.agentDir}),log:hostLog}}}),observers=startHostObservers(router,writer,{trim,onIdlePressure:({footprintMb,measure,rssMb})=>{hostLog(`memory pressure with no sessions: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb}`),endpointSuperseded().then(superseded=>{superseded&&drainForHandoff()},noop)}}),nextConnection=0,shuttingDown=!1,secret=process.platform==="win32"?await ensureSocketSecret(process.env[SOCKET_SECRET_FILE_ENV]??socketSecretPath(socketPath)):void 0,watchdogConfig=readHostWatchdogConfigFromBrandEnv(),crashCleanupPaths=[...watchdogConfig?.cleanupPaths??[]],supervisorPublicSocketPath=process.platform==="win32"||socketPath.startsWith("\0")?void 0:watchdogConfig?.publicSocket,supervisorPublicOwnerFile=supervisorPublicSocketPath&&watchdogConfig?.scratchDir?join(watchdogConfig.scratchDir,PUBLIC_SOCKET_IDENTITY_FILE):void 0,boundIdentity,supervisorPublicIdentity,server=createServer(socket=>{let accept=()=>{if(draining||shuttingDown){socket.destroy();return}let id=`socket-${++nextConnection}`,sink=socketSink(socket);writer.registerConnection(id,sink),occupancy.admit(socket);let detachReader=attachJsonlLineReader(socket,line=>{writer.withConnection(id,()=>handle(line)).catch(cause=>{process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}
|
|
17
|
+
`)})},{maxLineLength:MAX_RPC_LINE_CHARACTERS,onOversizedLine:()=>{writer.withConnection(id,()=>writer.enqueueControl(parseError(oversizedLineError()))).catch(cause=>process.stderr.write(`senpi rpc connection ${id} failed: ${errorMessage(cause)}
|
|
18
|
+
`))}}),detached=!1,detach=()=>{detached||(detached=!0,detachReader(),writer.unregisterConnection(id),connections.delete(id),occupancy.release(socket),router.releaseConnection(id).catch(cause=>{process.stderr.write(`senpi rpc connection ${id} release failed: ${errorMessage(cause)}
|
|
19
|
+
`)}))};connections.set(id,{id,sink,detach,close:()=>socket.destroy()}),socket.once("close",detach),socket.once("error",()=>detach())};secret?authenticateSocket(socket,secret,accept):accept()});server.on("error",cause=>{shuttingDown||process.stderr.write(`senpi rpc socket listener failed: ${errorMessage(cause)}
|
|
20
|
+
`)});let stopChildReaper=await startHostChildReaper(hostLog),shutdown=async(exitCode=0,watchdogCleanup)=>{shuttingDown&&process.exit(exitCode),shuttingDown=!0,observers.stop(),handover?.dispose(),stopChildReaper(),await handoverAnswered();try{await router.dispose(),await writer.flush();for(let connection of connections.values())connection.detach(),connection.close();await shieldSocketDuringClose(socketPath,()=>process.platform==="win32"?Promise.race([closeServer(server),delay(WINDOWS_SHUTDOWN_HARD_EXIT_MS)]):closeServer(server)),await unlinkOwnedSocket(socketPath,boundIdentity,hostLog),supervisorPublicSocketPath&&await unlinkOwnedSocket(supervisorPublicSocketPath,supervisorPublicIdentity,hostLog),watchdogCleanup&&await watchdogCleanup}finally{process.exit(exitCode)}},drainForHandoff=()=>{if(!shuttingDown){if(draining){handoffAnnounced&&router.beginDrain();return}draining=!0,crashCleanupPaths.length=0,hostLog("draining for a generation handoff"),endpointSuperseded().then(superseded=>{writer.broadcastHostRecord({type:"host_superseded",instanceId:hostInstanceId(),generation:hostGeneration(process.env),successor:superseded?{socket:supervisorPublicSocketPath??socketPath}:null})}).catch(cause=>{hostLog(`handoff announcement failed: ${String(cause)}`)}).finally(()=>{handoffAnnounced=!0,router.beginDrain()})}},endpointSuperseded=()=>supervisorPublicSocketPath===void 0?socketEntryReplaced(socketPath,boundIdentity):socketEntryReplaced(supervisorPublicSocketPath,supervisorPublicIdentity);registerShutdownSignals(shutdown),process.platform!=="win32"&&process.on("SIGUSR1",drainForHandoff);let watchdog=watchdogConfig&&supervisorPublicOwnerFile?{...watchdogConfig,cleanupPaths:crashCleanupPaths,beforeCleanup:async()=>{supervisorPublicIdentity??=await readSocketIdentityFile(supervisorPublicOwnerFile)}}:watchdogConfig&&{...watchdogConfig,cleanupPaths:crashCleanupPaths};return armHostWatchdog(watchdog,(reason,cleanup)=>{process.stderr.write(`senpi rpc host: ${reason}; shutting down
|
|
21
|
+
`),shutdown(0,cleanup),setImmediate(killTrackedDetachedChildren)}),boundIdentity=await listen(server,socketPath,secret),supervisorPublicOwnerFile&&(supervisorPublicIdentity=await waitForSocketIdentityFile(supervisorPublicOwnerFile)),process.stderr.write(`senpi rpc listening on ${formatSocketAddress(socketPath)}
|
|
22
|
+
`),new Promise(()=>{})}async function startupRuntimeBuildId(){try{return await computeRuntimeBuildId({profile:protocolIdentity().launch_profile.core})}catch(cause){hostLog(`runtime identity unreadable: ${errorMessage(cause)}`);return}}function delay(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function noop(){}function parseError(error2){return{type:"response",command:"parse",success:!1,error:error2}}function oversizedLineError(){return`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function hostSessionContext(socketPath){let supervised=readHostWatchdogConfigFromBrandEnv(),endpoint=supervised===void 0?socketPath:supervised.publicSocket;if(endpoint===void 0||endpoint.startsWith("\0"))return{host_instance:hostInstanceId()};let directory=canonicalSessionPath(dirname(endpoint));return{host_socket:join(directory,basename(endpoint)),host_instance:hostInstanceId()}}function listenSocketPath(options){if(!(options.listen===void 0||options.listen==="stdio://"))return resolveSocketPath(options.listen,options.agentDir)}function resolveSocketPath(value,agentDir){if(value==="unix://")return join(agentDir,"rpc","rpc.sock");if(value.startsWith("unix://")){let path=value.slice(7);return path.length===0?join(agentDir,"rpc","rpc.sock"):path.startsWith("@")&&process.platform==="linux"?`\0${path.slice(1)}`:path}return value}function formatSocketAddress(socketPath){return socketPath.startsWith("\0")?`unix://@${socketPath.slice(1)}`:`unix://${socketPath}`}async function prepareSocketPath(socketPath){if(!(process.platform==="win32"||socketPath.startsWith("\0"))){await mkdir(dirname(socketPath),{recursive:!0,mode:448});try{await access2(socketPath)}catch(cause){if(isNodeErrorCode(cause,"ENOENT"))return;throw cause}if(await probeSocket(socketPath))throw new Error(`${socketPath}: address already in use by a live server.`);await unlink(socketPath)}}function probeSocket(socketPath){return new Promise(resolve=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform)),settle=live=>{socket.destroy(),resolve(live)};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1)),socket.setTimeout(1e3,()=>settle(!1))})}function listen(server,socketPath,secret){return new Promise((resolve,reject)=>{server.once("error",reject),server.listen(resolveSocketTransportAddress(socketPath,process.platform,secret),async()=>{server.off("error",reject);try{if(process.platform!=="win32"&&!socketPath.startsWith("\0"))return await chmod(socketPath,384),resolve(await statSocketIdentity(socketPath));resolve(void 0)}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise((resolve,reject)=>{server.close(cause=>cause?reject(cause):resolve())})}function hostLog(message){process.stderr.write(`senpi rpc host: ${message}
|
|
23
|
+
`)}function isNodeErrorCode(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}function registerShutdownSignals(shutdown){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{killTrackedDetachedChildren(),shutdown(signal==="SIGHUP"?129:143)})}export{DEFAULT_HOST_EMPTY_EXIT_MS,DEFAULT_SESSION_IDLE_EVICTION_MS,RPC_HOST_EMPTY_EXIT_MS_ENV,RPC_SESSION_IDLE_EVICTION_MS_ENV,createHostCore,resolveHostIdlePolicy,runMultiSessionHost};
|
package/dist/bundle/chunks/{openai-completions-2DUKDEVN.js → openai-completions-VSH22FCN.js}
RENAMED
|
@@ -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{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{clampOpenAIPromptCacheKey}from"./chunk-AEJUOQ7U.js";import"./chunk-RFB5CBW7.js";import{awaitProviderTransport,formatGitHubCopilotToolLimitError,iterateProviderTransport,limitGitHubCopilotTools,openAICompatibleProviderDiagnosticFromError,recordGitHubCopilotToolLimit,withGitHubCopilotFailureNote}from"./chunk-U7CI2JGX.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-4Q6OS7LB.js";import{retryProviderStreamRequest}from"./chunk-KLBKUBDV.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-CWLCGRUS.js";import{getOpenAICompletionsCompat}from"./chunk-6WCOSBI7.js";import{sendWithForcedToolChoiceFallback}from"./chunk-LHYG7TK7.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-KRNXUTZJ.js";import{readProviderDiagnostic}from"./chunk-YOPVJDSU.js";import{appendGrammarToolInputJsonDelta,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-2WEI2XTZ.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getDeclaredTools,getSystemMessageText,inferOpenAIThinkingLevelMap,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,supportsMax,supportsXhigh}from"./chunk-XL5KIYQF.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var KIMI_K3_THINKING_LEVEL_MAP={off:null,minimal:null,low:"low",medium:null,high:"high",xhigh:null,max:"max"},DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"max",max:"max"},OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},MIMO_THINKING_LEVEL_MAP={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:null},OLLAMA_THINKING_LEVEL_MAP={off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:"high"};function getThinkingLevelMap(model,compat){let inferred=inferOpenAIThinkingLevelMap(model);if(inferred!==void 0)return inferred;let id=model.id.toLowerCase(),isKimiK3=id==="k3"||id.startsWith("k3-")||/(?:^|[/:-])kimi-k3(?:$|[/.:_-])/.test(id),isDeepSeek=id.includes("deepseek"),isMiMo=/\bmimo\b/.test(id),isGlm5x=/(?:^|[/:-])glm-5\.[23](?:$|[/.:_-])/.test(id);if(model.provider==="ollama")return OLLAMA_THINKING_LEVEL_MAP;if(isKimiK3)return KIMI_K3_THINKING_LEVEL_MAP;if(compat.thinkingFormat==="openrouter"&&isDeepSeek)return OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP;if((compat.thinkingFormat==="openai"||compat.thinkingFormat==="openrouter")&&isMiMo)return MIMO_THINKING_LEVEL_MAP;if(isDeepSeek)return DEEPSEEK_THINKING_LEVEL_MAP;if(isGlm5x)return compat.thinkingFormat==="zai"?DEEPSEEK_THINKING_LEVEL_MAP:compat.thinkingFormat==="openrouter"?{xhigh:"xhigh"}:{max:"max"}}function resolveReasoningEffort(thinkingLevelMap,effort){let mapped=thinkingLevelMap?.[effort];return mapped===void 0?effort:typeof mapped=="string"?mapped:void 0}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function resolveKimiDeferredTools(messages,compat){let deferred=new Map;if(compat.deferredToolsMode!=="kimi")return deferred;let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);for(let tool of getCurrentTools(messages))names.has(tool.name)&&deferred.set(tool.name,tool);return deferred}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isRecord(value){return typeof value=="object"&&value!==null}function getOpenRouterRawMetadata(error){if(!isRecord(error)||!isRecord(error.error)||!isRecord(error.error.metadata))return;let rawMetadata=error.error.metadata.raw;return typeof rawMetadata=="string"?rawMetadata:void 0}function isForcedOpenAICompletionsToolChoice(toolChoice){return toolChoice!==void 0&&toolChoice!=="auto"&&toolChoice!=="none"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}function toReplayableReasoningDetail(detail){let common={};switch(detail.id!==void 0&&(common.id=detail.id),detail.format!==void 0&&(common.format=detail.format),detail.type){case"reasoning.text":{let replayable={...common,type:"reasoning.text",text:detail.text};return detail.signature!==void 0&&(replayable.signature=detail.signature),replayable}case"reasoning.summary":return{...common,type:"reasoning.summary",summary:detail.summary};case"reasoning.encrypted":return{...common,type:"reasoning.encrypted",data:detail.data}}}function toReplayableReasoningDetails(details){return details.map(toReplayableReasoningDetail)}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(value){return OPENAI_COMPLETIONS_REASONING_FIELDS.some(field=>field===value)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getOpenAICompletionsCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:model.api,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()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let clientAuth=resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),compat=getOpenAICompletionsCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,normalizedContext,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,normalizedContext,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=normalizeRequestToolSchemas(params,compat);let limitedTools=limitGitHubCopilotTools(model.provider,params.tools,params.tool_choice);limitedTools.omittedCount>0&&(params={...params,tools:limitedTools.tools},recordGitHubCopilotToolLimit(output,limitedTools.omittedCount));let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},createChatCompletion=client.chat.completions.create.bind(client.chat.completions),createStream=async body=>{let{data,response}=await awaitProviderTransport(()=>createChatCompletion(body,requestOptions).withResponse(),openAICompatibleProviderDiagnosticFromError);return{data:iterateProviderTransport(data,openAICompatibleProviderDiagnosticFromError),response}},createRequest=async()=>{let sent=await sendWithForcedToolChoiceFallback({target:model,params,acceptsForcedToolChoice:compat.supportsForcedToolChoice!==!1,isForced:isForcedOpenAICompletionsToolChoice,send:createStream});return params=sent.params,sent.result},{stream:openaiStream}=await retryProviderStreamRequest(async()=>{let{data,response}=await createRequest();return await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),{stream:data,metadata:response}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,activeBlock=null,deferMixedEvents=!1,hasFinishReason=!1,deferredTextDeltas=[],deferredThinkingDeltas=[],deferredToolCallDeltas=new Map,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},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},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},finishActiveBlock=()=>{activeBlock&&(finishBlock(activeBlock),activeBlock=null)},ensureTextBlock=()=>(textBlock||(deferMixedEvents||(finishActiveBlock(),thinkingBlock=null),textBlock={type:"text",text:""},blocks.push(textBlock),deferMixedEvents||(activeBlock=textBlock,stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output}))),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(deferMixedEvents||(finishActiveBlock(),textBlock=null),thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),deferMixedEvents||(activeBlock=thinkingBlock,stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output}))),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){deferMixedEvents||(finishActiveBlock(),textBlock=null,thinkingBlock=null);let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),deferMixedEvents||(activeBlock=block,stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output}))}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block},flushDeferredBlocks=()=>{for(let block of blocks){let contentIndex=getContentIndex(block);if(block.type==="text"){stream2.push({type:"text_start",contentIndex,partial:output});for(let delta of deferredTextDeltas)stream2.push({type:"text_delta",contentIndex,delta,partial:output})}else if(block.type==="thinking"){stream2.push({type:"thinking_start",contentIndex,partial:output});for(let delta of deferredThinkingDeltas)stream2.push({type:"thinking_delta",contentIndex,delta,partial:output})}else{stream2.push({type:"toolcall_start",contentIndex,partial:output});for(let delta of deferredToolCallDeltas.get(block)??[])stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}finishBlock(block)}};for await(let chunk of openaiStream){if(await options?.onProviderStreamEvent?.(chunk,model),!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(!choice)continue;let choiceUsage=choice.usage;if(!chunk.usage&&choiceUsage&&(output.usage=parseChunkUsage(choiceUsage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let contentDelta=typeof choice.delta.content=="string"&&choice.delta.content.length>0?choice.delta.content:null,reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(blocks.length===0&&contentDelta&&foundReasoningField&&(deferMixedEvents=!0),contentDelta){let block=ensureTextBlock();block.text+=contentDelta,deferMixedEvents?deferredTextDeltas.push(contentDelta):stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:contentDelta,partial:output})}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,deferMixedEvents?deferredThinkingDeltas.push(delta):stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}if(deferMixedEvents){let deltas=deferredToolCallDeltas.get(block)??[];deltas.push(delta),deferredToolCallDeltas.set(block,deltas)}else stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails){if(!isOpenAIReasoningDetail(detail))continue;let block=ensureThinkingBlock(""),preservedDetails=parseOpenAIReasoningDetails(block.thinkingSignature)??[];appendOpenAIReasoningDetail(preservedDetails,detail),block.thinkingSignature=JSON.stringify(preservedDetails)}}}if(deferMixedEvents?flushDeferredBlocks():finishActiveBlock(),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error";let providerDiagnostic=output.stopReason==="error"?readProviderDiagnostic(error):void 0;providerDiagnostic!==void 0&&(output.providerDiagnostic=providerDiagnostic),output.errorMessage=withGitHubCopilotFailureNote(formatGitHubCopilotToolLimitError(output,formatProviderError(normalizeProviderError(error))),model.provider,error);let rawMetadata=getOpenRouterRawMetadata(error);rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
2
|
+
import{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{clampOpenAIPromptCacheKey}from"./chunk-AEJUOQ7U.js";import"./chunk-RFB5CBW7.js";import{awaitProviderTransport,formatGitHubCopilotToolLimitError,iterateProviderTransport,limitGitHubCopilotTools,openAICompatibleProviderDiagnosticFromError,recordGitHubCopilotToolLimit,withGitHubCopilotFailureNote}from"./chunk-U7CI2JGX.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-4Q6OS7LB.js";import{retryProviderStreamRequest}from"./chunk-KLBKUBDV.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-CWLCGRUS.js";import{getOpenAICompletionsCompat}from"./chunk-6WCOSBI7.js";import{sendWithForcedToolChoiceFallback}from"./chunk-YSPHACIN.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-KRNXUTZJ.js";import{readProviderDiagnostic}from"./chunk-YOPVJDSU.js";import{appendGrammarToolInputJsonDelta,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-2WEI2XTZ.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getDeclaredTools,getSystemMessageText,inferOpenAIThinkingLevelMap,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,supportsMax,supportsXhigh}from"./chunk-XL5KIYQF.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var KIMI_K3_THINKING_LEVEL_MAP={off:null,minimal:null,low:"low",medium:null,high:"high",xhigh:null,max:"max"},DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"max",max:"max"},OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP={minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},MIMO_THINKING_LEVEL_MAP={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"high",max:null},OLLAMA_THINKING_LEVEL_MAP={off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:"high"};function getThinkingLevelMap(model,compat){let inferred=inferOpenAIThinkingLevelMap(model);if(inferred!==void 0)return inferred;let id=model.id.toLowerCase(),isKimiK3=id==="k3"||id.startsWith("k3-")||/(?:^|[/:-])kimi-k3(?:$|[/.:_-])/.test(id),isDeepSeek=id.includes("deepseek"),isMiMo=/\bmimo\b/.test(id),isGlm5x=/(?:^|[/:-])glm-5\.[23](?:$|[/.:_-])/.test(id);if(model.provider==="ollama")return OLLAMA_THINKING_LEVEL_MAP;if(isKimiK3)return KIMI_K3_THINKING_LEVEL_MAP;if(compat.thinkingFormat==="openrouter"&&isDeepSeek)return OPENROUTER_DEEPSEEK_THINKING_LEVEL_MAP;if((compat.thinkingFormat==="openai"||compat.thinkingFormat==="openrouter")&&isMiMo)return MIMO_THINKING_LEVEL_MAP;if(isDeepSeek)return DEEPSEEK_THINKING_LEVEL_MAP;if(isGlm5x)return compat.thinkingFormat==="zai"?DEEPSEEK_THINKING_LEVEL_MAP:compat.thinkingFormat==="openrouter"?{xhigh:"xhigh"}:{max:"max"}}function resolveReasoningEffort(thinkingLevelMap,effort){let mapped=thinkingLevelMap?.[effort];return mapped===void 0?effort:typeof mapped=="string"?mapped:void 0}function hasToolHistory(messages){for(let msg of messages)if(msg.role==="toolResult"||msg.role==="assistant"&&msg.content.some(block=>block.type==="toolCall"))return!0;return!1}function resolveKimiDeferredTools(messages,compat){let deferred=new Map;if(compat.deferredToolsMode!=="kimi")return deferred;let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);for(let tool of getCurrentTools(messages))names.has(tool.name)&&deferred.set(tool.name,tool);return deferred}function isTextContentBlock(block){return block.type==="text"}function isThinkingContentBlock(block){return block.type==="thinking"}function isToolCallBlock(block){return block.type==="toolCall"}function isImageContentBlock(block){return block.type==="image"}function isRecord(value){return typeof value=="object"&&value!==null}function getOpenRouterRawMetadata(error){if(!isRecord(error)||!isRecord(error.error)||!isRecord(error.error.metadata))return;let rawMetadata=error.error.metadata.raw;return typeof rawMetadata=="string"?rawMetadata:void 0}function isForcedOpenAICompletionsToolChoice(toolChoice){return toolChoice!==void 0&&toolChoice!=="auto"&&toolChoice!=="none"}function isReasoningDetailObject(detail){return typeof detail=="object"&&detail!==null&&!Array.isArray(detail)}function hasValidCommonReasoningDetailFields(candidate){return(candidate.id===void 0||candidate.id===null||typeof candidate.id=="string")&&(candidate.format===void 0||typeof candidate.format=="string")&&(candidate.index===void 0||typeof candidate.index=="number")}function isOpenAIReasoningDetail(detail){if(!isReasoningDetailObject(detail)||!hasValidCommonReasoningDetailFields(detail))return!1;switch(detail.type){case"reasoning.summary":return typeof detail.summary=="string";case"reasoning.encrypted":return typeof detail.data=="string";case"reasoning.text":return typeof detail.text=="string"&&(detail.signature===void 0||detail.signature===null||typeof detail.signature=="string");default:return!1}}function parseOpenAIReasoningDetails(signature){if(signature)try{let parsed=JSON.parse(signature);return Array.isArray(parsed)&&parsed.length>0&&parsed.every(isOpenAIReasoningDetail)?parsed:void 0}catch{return}}function parseLegacyEncryptedReasoningDetail(signature){if(signature)try{let parsed=JSON.parse(signature);return isOpenAIReasoningDetail(parsed)&&parsed.type==="reasoning.encrypted"&&typeof parsed.id=="string"&&parsed.id.length>0&&parsed.data.length>0?parsed:void 0}catch{return}}function fillMissingCommonReasoningDetailFields(target,source){target.id??=source.id,target.format||=source.format,target.index??=source.index}function appendOpenAIReasoningDetail(details,detail){let lastDetail=details[details.length-1];if(detail.type==="reasoning.text"&&lastDetail?.type==="reasoning.text"){lastDetail.text+=detail.text,lastDetail.signature||=detail.signature,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}if(detail.type==="reasoning.summary"&&lastDetail?.type==="reasoning.summary"){lastDetail.summary+=detail.summary,fillMissingCommonReasoningDetailFields(lastDetail,detail);return}details.push({...detail})}function toReplayableReasoningDetail(detail){let common={};switch(detail.id!==void 0&&(common.id=detail.id),detail.format!==void 0&&(common.format=detail.format),detail.type){case"reasoning.text":{let replayable={...common,type:"reasoning.text",text:detail.text};return detail.signature!==void 0&&(replayable.signature=detail.signature),replayable}case"reasoning.summary":return{...common,type:"reasoning.summary",summary:detail.summary};case"reasoning.encrypted":return{...common,type:"reasoning.encrypted",data:detail.data}}}function toReplayableReasoningDetails(details){return details.map(toReplayableReasoningDetail)}var OPENAI_COMPLETIONS_REASONING_FIELDS=["reasoning","reasoning_content","reasoning_text"];function isOpenAICompletionsReasoningField(value){return OPENAI_COMPLETIONS_REASONING_FIELDS.some(field=>field===value)}function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getOpenAICompletionsCompat(model).supportsMidConvoSystemMessages);return(async()=>{let output={role:"assistant",content:[],api:model.api,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()},streamedReasoningDetails,applyStreamedReasoningDetails=block=>{streamedReasoningDetails!==void 0&&(block.thinkingSignature=JSON.stringify(streamedReasoningDetails))};try{let clientAuth=resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers),compat=getOpenAICompletionsCompat(model),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,normalizedContext,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,normalizedContext,options,compat,cacheRetention,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams),params=normalizeRequestToolSchemas(params,compat);let limitedTools=limitGitHubCopilotTools(model.provider,params.tools,params.tool_choice);limitedTools.omittedCount>0&&(params={...params,tools:limitedTools.tools},recordGitHubCopilotToolLimit(output,limitedTools.omittedCount));let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},createChatCompletion=client.chat.completions.create.bind(client.chat.completions),createStream=async body=>{let{data,response}=await awaitProviderTransport(()=>createChatCompletion(body,requestOptions).withResponse(),openAICompatibleProviderDiagnosticFromError);return{data:iterateProviderTransport(data,openAICompatibleProviderDiagnosticFromError),response}},createRequest=async()=>{let sent=await sendWithForcedToolChoiceFallback({target:model,params,acceptsForcedToolChoice:compat.supportsForcedToolChoice!==!1,isForced:isForcedOpenAICompletionsToolChoice,send:createStream});return params=sent.params,sent.result},{stream:openaiStream}=await retryProviderStreamRequest(async()=>{let{data,response}=await createRequest();return await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),{stream:data,metadata:response}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});stream2.push({type:"start",partial:output});let textBlock=null,thinkingBlock=null,activeBlock=null,deferMixedEvents=!1,hasFinishReason=!1,deferredTextDeltas=[],deferredThinkingDeltas=[],deferredToolCallDeltas=new Map,toolCallBlocksByIndex=new Map,toolCallBlocksById=new Map,blocks=output.content,getContentIndex=block=>blocks.indexOf(block),getCustomToolCallInput=block=>{let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""},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},finishBlock=block=>{let contentIndex=getContentIndex(block);if(contentIndex!==-1){if(block.type==="text")stream2.push({type:"text_end",contentIndex,content:block.text,partial:output});else if(block.type==="thinking")applyStreamedReasoningDetails(block),stream2.push({type:"thinking_end",contentIndex,content:block.thinking,partial:output});else if(block.type==="toolCall"){if(block.customInput){let delta=appendCustomToolCallInput(block,getCustomToolCallInput(block),!0);delta!==void 0&&stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}else block.arguments=parseStreamingJson(block.partialArgs);delete block.partialArgs,delete block.customInput,delete block.streamIndex,stream2.push({type:"toolcall_end",contentIndex,toolCall:block,partial:output})}}},finishActiveBlock=()=>{activeBlock&&(finishBlock(activeBlock),activeBlock=null)},ensureTextBlock=()=>(textBlock||(deferMixedEvents||(finishActiveBlock(),thinkingBlock=null),textBlock={type:"text",text:""},blocks.push(textBlock),deferMixedEvents||(activeBlock=textBlock,stream2.push({type:"text_start",contentIndex:getContentIndex(textBlock),partial:output}))),textBlock),ensureThinkingBlock=thinkingSignature=>(thinkingBlock||(deferMixedEvents||(finishActiveBlock(),textBlock=null),thinkingBlock={type:"thinking",thinking:"",thinkingSignature},blocks.push(thinkingBlock),deferMixedEvents||(activeBlock=thinkingBlock,stream2.push({type:"thinking_start",contentIndex:getContentIndex(thinkingBlock),partial:output}))),thinkingBlock),ensureToolCallBlock=toolCall=>{let streamIndex=typeof toolCall.index=="number"?toolCall.index:void 0,name=toolCall.function?.name??toolCall.custom?.name??"",block=streamIndex!==void 0?toolCallBlocksByIndex.get(streamIndex):void 0;if(!block&&toolCall.id&&(block=toolCallBlocksById.get(toolCall.id)),!block){deferMixedEvents||(finishActiveBlock(),textBlock=null,thinkingBlock=null);let customInputProperty=toolCall.custom&&!toolCall.function?grammarToolInputProperties.get(name)??"input":void 0,hasCustomInput=customInputProperty!==void 0;block={type:"toolCall",id:toolCall.id||"",name,arguments:hasCustomInput?{[customInputProperty]:""}:{},partialArgs:hasCustomInput?void 0:"",customInput:hasCustomInput?{property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex},streamIndex!==void 0&&toolCallBlocksByIndex.set(streamIndex,block),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),blocks.push(block),deferMixedEvents||(activeBlock=block,stream2.push({type:"toolcall_start",contentIndex:getContentIndex(block),partial:output}))}if(streamIndex!==void 0&&block.streamIndex===void 0&&(block.streamIndex=streamIndex,toolCallBlocksByIndex.set(streamIndex,block)),toolCall.id&&toolCallBlocksById.set(toolCall.id,block),!block.name&&name&&(block.name=name),toolCall.custom&&!toolCall.function&&!block.customInput){let customInputProperty=grammarToolInputProperties.get(block.name)??"input";block.arguments={[customInputProperty]:""},block.customInput={property:customInputProperty,jsonBuffer:{input:"",started:!1,closed:!1}},delete block.partialArgs}return block},flushDeferredBlocks=()=>{for(let block of blocks){let contentIndex=getContentIndex(block);if(block.type==="text"){stream2.push({type:"text_start",contentIndex,partial:output});for(let delta of deferredTextDeltas)stream2.push({type:"text_delta",contentIndex,delta,partial:output})}else if(block.type==="thinking"){stream2.push({type:"thinking_start",contentIndex,partial:output});for(let delta of deferredThinkingDeltas)stream2.push({type:"thinking_delta",contentIndex,delta,partial:output})}else{stream2.push({type:"toolcall_start",contentIndex,partial:output});for(let delta of deferredToolCallDeltas.get(block)??[])stream2.push({type:"toolcall_delta",contentIndex,delta,partial:output})}finishBlock(block)}};for await(let chunk of openaiStream){if(await options?.onProviderStreamEvent?.(chunk,model),!chunk||typeof chunk!="object")continue;output.responseId||=chunk.id,typeof chunk.model=="string"&&chunk.model.length>0&&chunk.model!==model.id&&(output.responseModel||=chunk.model),chunk.usage&&(output.usage=parseChunkUsage(chunk.usage,model));let choice=Array.isArray(chunk.choices)?chunk.choices[0]:void 0;if(!choice)continue;let choiceUsage=choice.usage;if(!chunk.usage&&choiceUsage&&(output.usage=parseChunkUsage(choiceUsage,model)),choice.finish_reason){output.rawStopReason=choice.finish_reason;let finishReasonResult=mapStopReason(choice.finish_reason);output.stopReason=finishReasonResult.stopReason,finishReasonResult.errorMessage&&(output.errorMessage=finishReasonResult.errorMessage),hasFinishReason=!0}if(choice.delta){let contentDelta=typeof choice.delta.content=="string"&&choice.delta.content.length>0?choice.delta.content:null,reasoningFields=["reasoning_content","reasoning","reasoning_text"],deltaFields=choice.delta,foundReasoningField=null;for(let field of reasoningFields){let value=deltaFields[field];if(typeof value=="string"&&value.length>0){foundReasoningField=field;break}}if(blocks.length===0&&contentDelta&&foundReasoningField&&(deferMixedEvents=!0),contentDelta){let block=ensureTextBlock();block.text+=contentDelta,deferMixedEvents?deferredTextDeltas.push(contentDelta):stream2.push({type:"text_delta",contentIndex:getContentIndex(block),delta:contentDelta,partial:output})}if(foundReasoningField){let delta=deltaFields[foundReasoningField];if(typeof delta=="string"&&delta.length>0){let thinkingSignature=model.provider==="opencode-go"&&foundReasoningField==="reasoning"?"reasoning_content":foundReasoningField,block=ensureThinkingBlock(thinkingSignature);block.thinking+=delta,deferMixedEvents?deferredThinkingDeltas.push(delta):stream2.push({type:"thinking_delta",contentIndex:getContentIndex(block),delta,partial:output})}}if(choice?.delta?.tool_calls)for(let toolCall of choice.delta.tool_calls){let block=ensureToolCallBlock(toolCall);!block.id&&toolCall.id&&(block.id=toolCall.id,toolCallBlocksById.set(toolCall.id,block));let name=toolCall.function?.name??toolCall.custom?.name;!block.name&&name&&(block.name=name);let delta="";if(toolCall.function?.arguments)delta=toolCall.function.arguments,block.partialArgs=(block.partialArgs??"")+toolCall.function.arguments,block.arguments=parseStreamingJson(block.partialArgs);else if(toolCall.custom?.input){let nextInput=getCustomToolCallInput(block)+toolCall.custom.input;delta=appendCustomToolCallInput(block,nextInput,!1)??""}if(deferMixedEvents){let deltas=deferredToolCallDeltas.get(block)??[];deltas.push(delta),deferredToolCallDeltas.set(block,deltas)}else stream2.push({type:"toolcall_delta",contentIndex:getContentIndex(block),delta,partial:output})}let reasoningDetails=choice.delta.reasoning_details;if(Array.isArray(reasoningDetails))for(let detail of reasoningDetails){if(!isOpenAIReasoningDetail(detail))continue;let block=ensureThinkingBlock(""),preservedDetails=parseOpenAIReasoningDetails(block.thinkingSignature)??[];appendOpenAIReasoningDetail(preservedDetails,detail),block.thinkingSignature=JSON.stringify(preservedDetails)}}}if(deferMixedEvents?flushDeferredBlocks():finishActiveBlock(),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="aborted")throw new Error("Request was aborted");if(!hasFinishReason&&!compat.supportsFinishReason&&(output.stopReason=output.content.some(block=>block.type==="toolCall")?"toolUse":"stop"),output.stopReason==="error")throw new Error(output.errorMessage||"Provider returned an error stop reason");if(compat.supportsFinishReason&&!hasFinishReason||output.stopReason==="pending")throw new Error("Stream ended without finish_reason");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)block.type==="thinking"&&applyStreamedReasoningDetails(block),delete block.index,delete block.partialArgs,delete block.customInput,delete block.streamIndex;output.stopReason=options?.signal?.aborted?"aborted":"error";let providerDiagnostic=output.stopReason==="error"?readProviderDiagnostic(error):void 0;providerDiagnostic!==void 0&&(output.providerDiagnostic=providerDiagnostic),output.errorMessage=withGitHubCopilotFailureNote(formatGitHubCopilotToolLimitError(output,formatProviderError(normalizeProviderError(error))),model.provider,error);let rawMetadata=getOpenRouterRawMetadata(error);rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
|
|
3
3
|
${rawMetadata}`),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{resolveOpenAIClientAuth(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice??options?.toolChoice},compat=getOpenAICompletionsCompat(model),thinkingLevelMap=getThinkingLevelMap(model,compat),thinkingModel=thinkingLevelMap===model.thinkingLevelMap?model:{...model,thinkingLevelMap},clampedReasoning=options?.reasoning?clampThinkingLevel(thinkingModel,options.reasoning):model.id.includes("gpt-6-astra")?"off":void 0,hasMappedOff=typeof thinkingLevelMap?.off=="string",normalizedReasoning=clampedReasoning==="off"&&model.id.includes("gpt-6-astra")&&!hasMappedOff?"low":clampedReasoning,reasoningEffort=normalizedReasoning==="off"?void 0:normalizedReasoning==="max"&&supportsMax(thinkingModel)?"max":clampMaxForOpenAI(normalizedReasoning,supportsXhigh(thinkingModel));return stream(model,context,{...base,reasoningEffort,thinkingBudgets:options?.thinkingBudgets})};function createClient(model,context,apiKey,optionsHeaders,fetch,sessionId,compat=getOpenAICompletionsCompat(model)){let headers={"User-Agent":getPiUserAgent(),...model.headers};if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(context.messages),copilotHeaders=buildCopilotDynamicHeaders({messages:context.messages,hasImages});Object.assign(headers,copilotHeaders)}return sessionId&&compat.sendSessionAffinityHeaders&&(compat.sessionAffinityFormat==="openrouter"?headers["x-session-id"]=sessionId:(compat.sessionAffinityFormat==="openai"&&(headers.session_id=sessionId),headers["x-client-request-id"]=sessionId,headers["x-session-affinity"]=sessionId)),optionsHeaders&&Object.assign(headers,optionsHeaders),new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:headers})}function buildParams(model,context,options,compat=getOpenAICompletionsCompat(model),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),compat.supportsOpenAIGrammarTools)){let transcriptTools=resolveTranscriptTools(context.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),kimiDeferredTools=resolveKimiDeferredTools(context.messages,compat),requestTools=transcriptTools.requestTools.filter(tool=>!kimiDeferredTools.has(tool.name)),messages=convertMessages(model,context,compat,{preserveThinking:options?.reasoningEffort!==void 0,grammarToolInputProperties}),cacheControl=getCompatCacheControl(compat,cacheRetention),thinkingLevelMap=getThinkingLevelMap(model,compat),params={model:model.id,messages,stream:!0,prompt_cache_key:cacheRetention!=="none"&&!(model.baseUrl.includes("api.openai.com")&&model.cost.cacheWrite>0)&&(model.baseUrl.includes("api.openai.com")||cacheRetention==="long"&&compat.supportsLongCacheRetention||compat.supportsPromptCacheKey)?clampOpenAIPromptCacheKey(options?.sessionId):void 0,prompt_cache_retention:cacheRetention==="long"&&compat.supportsLongCacheRetention?"24h":void 0,session_id:compat.sendSessionAffinityHeaders&&compat.sessionAffinityFormat==="openrouter"&&cacheRetention!=="none"?options?.sessionId:void 0};compat.supportsUsageInStreaming!==!1&&(params.stream_options={include_usage:!0}),compat.supportsStore&&(params.store=!1),options?.maxTokens&&(compat.maxTokensField==="max_tokens"?params.max_tokens=options.maxTokens:params.max_completion_tokens=options.maxTokens),options?.temperature!==void 0&&(params.temperature=options.temperature),requestTools.length>0?(params.tools=convertTools(requestTools,compat),compat.zaiToolStream&&(params.tool_stream=!0)):hasToolHistory(context.messages)&&(params.tools=[]),cacheControl&&applyAnthropicCacheControl(messages,params.tools,cacheControl),options?.toolChoice&&(params.tool_choice=options.toolChoice),compat.vllmPriority!==void 0&&(params.priority=compat.vllmPriority);let thinkingTokenBudgetField=resolveThinkingTokenBudgetField(compat),thinkingBudget=resolveClampedThinkingBudget(model,options,params);if(compat.thinkingFormat==="zai"&&model.reasoning){let isGlm53=/(?:^|[/:-])glm-5\.3(?:-(?:flash|highspeed))?(?:$|[/.:_])/.test(model.id.toLowerCase()),zaiParams=params;if(zaiParams.thinking=options?.reasoningEffort||isGlm53?{type:"enabled",clear_thinking:!1}:{type:"disabled"},options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(zaiParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen"&&model.reasoning){if(params.enable_thinking=!!options?.reasoningEffort,options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}}else if(compat.thinkingFormat==="qwen-chat-template"&&model.reasoning)params.chat_template_kwargs={enable_thinking:!!options?.reasoningEffort,preserve_thinking:!0};else if(compat.thinkingFormat==="chat-template"&&model.reasoning){let chatTemplateKwargs=buildChatTemplateValues(model,options,compat,compat.chatTemplateKwargs,thinkingBudget);chatTemplateKwargs&&(params.chat_template_kwargs=chatTemplateKwargs)}else if(compat.thinkingFormat==="baseten"&&model.reasoning){let basetenParams=params,chatTemplateArgs=buildChatTemplateValues(model,options,compat,compat.chatTemplateArgs??{},thinkingBudget);if(chatTemplateArgs&&(basetenParams.chat_template_args=chatTemplateArgs),compat.supportsReasoningEffort){let requestedEffort=options?.reasoningEffort,mappedEffort=requestedEffort?thinkingLevelMap?.[requestedEffort]:thinkingLevelMap?.off,effort=mappedEffort===void 0?requestedEffort:mappedEffort;typeof effort=="string"&&(basetenParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="deepseek"&&model.reasoning)if(options?.reasoningEffort){if(params.thinking={type:"enabled"},compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}}else compat.supportsDisabledThinking!==!1&&thinkingLevelMap?.off!==null&&(params.thinking={type:"disabled"});else if(compat.thinkingFormat==="openrouter"&&model.reasoning){let openRouterParams=params;if(options?.reasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(openRouterParams.reasoning={effort})}else thinkingLevelMap?.off!==null&&(openRouterParams.reasoning={effort:thinkingLevelMap?.off??"none"})}else if(compat.thinkingFormat==="ant-ling"&&model.reasoning&&options?.reasoningEffort){let effort=thinkingLevelMap?.[options.reasoningEffort];typeof effort=="string"&&(params.reasoning={effort})}else if(compat.thinkingFormat==="together"&&model.reasoning){let togetherParams=params;if(togetherParams.reasoning={enabled:!!options?.reasoningEffort},options?.reasoningEffort&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(togetherParams.reasoning_effort=effort)}}else if(compat.thinkingFormat==="string-thinking"&&model.reasoning)if(options?.reasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.thinking=effort)}else thinkingLevelMap?.off!==null&&(params.thinking=thinkingLevelMap?.off??"none");else if(options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let effort=resolveReasoningEffort(thinkingLevelMap,options.reasoningEffort);effort!==void 0&&(params.reasoning_effort=effort)}else if(!options?.reasoningEffort&&model.reasoning&&compat.supportsReasoningEffort){let offValue=thinkingLevelMap?.off;typeof offValue=="string"&&(params.reasoning_effort=offValue)}if(thinkingTokenBudgetField&&thinkingBudget!==void 0&&Object.assign(params,{[thinkingTokenBudgetField]:thinkingBudget}),model.compat?.openRouterRouting&&(params.provider=model.compat.openRouterRouting),model.compat?.veniceParameters&&(params.venice_parameters=model.compat.veniceParameters),model.compat?.vercelGatewayRouting){let routing=model.compat.vercelGatewayRouting;if(routing.only||routing.order){let gatewayOptions={};routing.only&&(gatewayOptions.only=routing.only),routing.order&&(gatewayOptions.order=routing.order),params.providerOptions={gateway:gatewayOptions}}}return applyExtraBody(params,options?.extraBody,OPENAI_COMPLETIONS_RESERVED_BODY_KEYS),Object.assign(params,model.samplingParams,options?.samplingParams),params}function resolveThinkingTokenBudgetField(compat){if(compat.thinkingTokenBudgetField)return compat.thinkingTokenBudgetField;if(compat.supportsThinkingTokenBudget)return"thinking_token_budget"}function resolveClampedThinkingBudget(model,options,params){if(!options?.reasoningEffort||!model.reasoning)return;let ceiling=params.max_tokens??params.max_completion_tokens??model.maxTokens,budget=clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort,options.thinkingBudgets),ceiling);return budget>0?budget:void 0}function buildChatTemplateValues(model,options,compat,values,thinkingBudget){let resolvedValues={};for(let[key,value]of Object.entries(values)){let resolved=resolveChatTemplateKwargValue(model,options,compat,value,thinkingBudget);resolved!==void 0&&(resolvedValues[key]=resolved)}return Object.keys(resolvedValues).length>0?resolvedValues:void 0}function resolveChatTemplateKwargValue(model,options,compat,value,thinkingBudget){if(typeof value!="object"||value===null)return value;let reasoningEffort=options?.reasoningEffort;if(!reasoningEffort&&value.omitWhenOff)return;if(value.$var==="thinking.enabled")return!!reasoningEffort;if(value.$var==="thinking.budget")return thinkingBudget;let thinkingLevelMap=getThinkingLevelMap(model,compat),mappedValue=reasoningEffort?thinkingLevelMap?.[reasoningEffort]:thinkingLevelMap?.off;return mappedValue===void 0?reasoningEffort:typeof mappedValue=="string"?mappedValue:void 0}function getCompatCacheControl(compat,cacheRetention){if(compat.cacheControlFormat!=="anthropic"||cacheRetention==="none")return;let ttl=cacheRetention==="long"&&compat.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...ttl?{ttl}:{}}}function applyAnthropicCacheControl(messages,tools,cacheControl){addCacheControlToSystemPrompt(messages,cacheControl),addCacheControlToLastTool(tools,cacheControl),addCacheControlToLastConversationMessage(messages,cacheControl)}function addCacheControlToSystemPrompt(messages,cacheControl){for(let message of messages)if(message.role==="system"||message.role==="developer"){addCacheControlToInstructionMessage(message,cacheControl);return}}function addCacheControlToLastConversationMessage(messages,cacheControl){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if((message.role==="user"||message.role==="assistant"||message.role==="tool")&&addCacheControlToMessage(message,cacheControl))return}}function addCacheControlToLastTool(tools,cacheControl){if(!tools||tools.length===0)return;let lastTool=tools[tools.length-1];lastTool.cache_control=cacheControl}function addCacheControlToInstructionMessage(message,cacheControl){return addCacheControlToTextContent(message,cacheControl)}function addCacheControlToMessage(message,cacheControl){return message.role==="user"||message.role==="assistant"||message.role==="tool"?addCacheControlToTextContent(message,cacheControl):!1}function addCacheControlToTextContent(message,cacheControl){let content=message.content;if(typeof content=="string")return content.length===0?!1:(message.content=[{type:"text",text:content,cache_control:cacheControl}],!0);if(!Array.isArray(content))return!1;for(let i=content.length-1;i>=0;i--){let part=content[i];if(part?.type==="text"){let textPart=part;return textPart.cache_control=cacheControl,!0}}return!1}function appendUserMessage(params,content,mergeAdjacentUserMessages){let previous=params[params.length-1];if(!mergeAdjacentUserMessages||previous?.role!=="user"){params.push({role:"user",content});return}let previousContent=typeof previous.content=="string"?[{type:"text",text:previous.content}]:previous.content,currentContent=typeof content=="string"?[{type:"text",text:content}]:content;previous.content=[...previousContent,...currentContent]}function convertMessages(model,context,compat,options={}){let normalizedContext=resolveTranscript(context,compat.supportsMidConvoSystemMessages),params=[],normalizeToolCallId=id=>{if(id.includes("|")){let separatorIndex=id.indexOf("|"),callId=id.slice(0,separatorIndex).replace(/[^a-zA-Z0-9_-]/g,"_"),itemId=id.slice(separatorIndex+1).replace(/[^a-zA-Z0-9_-]/g,"_"),combinedId=itemId.length>0?`${callId}_${itemId}`:callId;if(combinedId.length<=40)return combinedId;let hash2=shortHash(id).slice(0,8);return`${callId.slice(0,Math.max(1,40-hash2.length-1))}_${hash2}`}let sanitizedId=id.replace(/[^a-zA-Z0-9_-]/g,"_")||"tool_call";if(sanitizedId===id&&sanitizedId.length<=40)return id;let hash=shortHash(id).slice(0,8);return`${sanitizedId.slice(0,Math.max(1,40-hash.length-1))}_${hash}`},transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeToolCallId(id),{preserveThinking:options.preserveThinking,normalizeSameModelToolCallIds:!0}),mergeAdjacentUserMessages=!model.baseUrl.includes("api.openai.com"),transcriptTools=resolveTranscriptTools(normalizedContext.messages,compat.supportsMidConvoSystemMessages===!0&&compat.supportsMidConvoToolAdditions===!0),kimiDeferredTools=resolveKimiDeferredTools(normalizedContext.messages,compat),loadedToolNames=new Set,instructionRole=model.reasoning&&compat.supportsDeveloperRole?"developer":"system",lastRole=null;for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(compat.requiresAssistantAfterToolResult&&lastRole==="toolResult"&&msg.role==="user"&¶ms.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="system"){let addedTools=i>0&&transcriptTools.anchorsAdditions?(msg.toolsAdded??[]).filter(tool=>!loadedToolNames.has(tool.name)):[];for(let tool of addedTools)loadedToolNames.add(tool.name);if(addedTools.length>0){let kimiToolMessage={role:"system",tools:convertTools(addedTools,compat)};params.push(kimiToolMessage)}let text=i===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&¶ms.push({role:instructionRole,content:sanitizeSurrogates(text)})}else if(msg.role==="user")if(typeof msg.content=="string")appendUserMessage(params,sanitizeSurrogates(msg.content),mergeAdjacentUserMessages);else{let content=msg.content.filter(item=>item.type!=="text"||item.text.length>0).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});if(content.length===0)continue;appendUserMessage(params,content,mergeAdjacentUserMessages)}else if(msg.role==="assistant"){let assistantMsg={role:"assistant",content:compat.requiresAssistantAfterToolResult?"":null},assistantTextParts=msg.content.filter(isTextContentBlock).filter(block=>block.text.trim().length>0).map(block=>({type:"text",text:sanitizeSurrogates(block.text)})),assistantText=assistantTextParts.map(part=>part.text).join(""),thinkingBlocks=msg.content.filter(isThinkingContentBlock),toolCalls=msg.content.filter(isToolCallBlock),signedReasoningDetails=thinkingBlocks.map(block=>parseOpenAIReasoningDetails(block.thinkingSignature)).find(details=>details!==void 0),legacyReasoningDetails=toolCalls.map(toolCall=>parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter(detail=>detail!==void 0),preservedReasoningDetails=signedReasoningDetails??(legacyReasoningDetails.length>0?legacyReasoningDetails:void 0),nonEmptyThinkingBlocks=thinkingBlocks.filter(block=>block.thinking.trim().length>0);if(nonEmptyThinkingBlocks.length>0)if(compat.requiresThinkingAsText){let thinkingText=nonEmptyThinkingBlocks.map(block=>sanitizeSurrogates(block.thinking)).join(`
|
|
4
4
|
|
|
5
5
|
`);assistantMsg.content=[{type:"text",text:thinkingText},...assistantTextParts]}else{assistantText.length>0&&(assistantMsg.content=assistantText);let signature=nonEmptyThinkingBlocks[0].thinkingSignature;model.provider==="opencode-go"&&signature==="reasoning"&&(signature="reasoning_content"),signature!==void 0&&isOpenAICompletionsReasoningField(signature)&&Object.assign(assistantMsg,{[signature]:nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
|