@code-yeongyu/senpi 2026.9.29-5 → 2026.9.30
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 +32 -0
- package/dist/bundle/chunks/{anthropic-messages-HEVKB3PL.js → anthropic-messages-ADSIWAJ5.js} +1 -1
- package/dist/bundle/chunks/{app-server-command-32AFWZEH.js → app-server-command-B3ZYM2WN.js} +1 -1
- package/dist/bundle/chunks/{chunk-2WAKOPNA.js → chunk-4P4DUW66.js} +1 -1
- package/dist/bundle/chunks/{chunk-7RVWDN5Z.js → chunk-6GV3L3GZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-OUG6SDT7.js → chunk-6JZQLUAJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-MJQWYN2W.js → chunk-7MKMDWHC.js} +2 -2
- package/dist/bundle/chunks/{chunk-XBGO2JZD.js → chunk-A7AQSA6R.js} +1 -1
- package/dist/bundle/chunks/{chunk-BJICJY47.js → chunk-DVVROXLZ.js} +1 -1
- package/dist/bundle/chunks/chunk-EIG6K5U3.js +6 -0
- package/dist/bundle/chunks/chunk-FAWC2EIR.js +2 -0
- package/dist/bundle/chunks/{chunk-WCAKUCN3.js → chunk-FNCILR4E.js} +1 -1
- package/dist/bundle/chunks/{chunk-XHEMQA2T.js → chunk-HPESFBMB.js} +2 -2
- package/dist/bundle/chunks/{chunk-BBNWT72C.js → chunk-HVBFDRP4.js} +1 -1
- package/dist/bundle/chunks/{chunk-63QHOG5A.js → chunk-I77ENHCQ.js} +81 -74
- package/dist/bundle/chunks/{chunk-UMLU3I2G.js → chunk-ITXF6FAM.js} +1 -1
- package/dist/bundle/chunks/{chunk-77AUUH3Z.js → chunk-IXONH7ML.js} +2 -2
- package/dist/bundle/chunks/{chunk-K2SHQNAA.js → chunk-JX2CSKLG.js} +1 -1
- package/dist/bundle/chunks/{chunk-4VWWEMCJ.js → chunk-JXZ5LDJP.js} +1 -1
- package/dist/bundle/chunks/{chunk-VLTMFAWQ.js → chunk-KWI3KUF2.js} +1 -1
- package/dist/bundle/chunks/{chunk-7CQX3QFV.js → chunk-L4QGZJKQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-AGVPQLIU.js → chunk-MDXUQDGF.js} +1 -1
- package/dist/bundle/chunks/{chunk-2N3BZ5DV.js → chunk-OOA6OL42.js} +1 -1
- package/dist/bundle/chunks/{chunk-2POUJCWM.js → chunk-OVGH7VP3.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZDNR3YVJ.js → chunk-RMVQ5YRX.js} +1 -1
- package/dist/bundle/chunks/{chunk-SH6VUPE4.js → chunk-T5MOQDGL.js} +1 -1
- package/dist/bundle/chunks/{chunk-CNYWF72S.js → chunk-VKECIIYV.js} +1 -1
- package/dist/bundle/chunks/{chunk-U7BNOE23.js → chunk-VNYUGCC7.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZPMJIPQC.js → chunk-YSNNL5HU.js} +1 -1
- package/dist/bundle/chunks/cli-main-F6WNYPUT.js +3 -0
- package/dist/bundle/chunks/{help-fast-path-ZUNFOE53.js → help-fast-path-34Z6I2PH.js} +1 -1
- package/dist/bundle/chunks/{host-command-V2LDNNXB.js → host-command-PUOIPEBI.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-PFLJRXEN.js → host-lifecycle-4VJUHV5U.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +1 -1
- package/dist/bundle/chunks/{interactive-mode-J6KGDRR7.js → interactive-mode-KM454JPC.js} +1 -1
- package/dist/bundle/chunks/{list-tips-ASETMEFS.js → list-tips-GWRRD5UC.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-IBVJ3WN7.js → multi-session-host-ZFT6RM2S.js} +2 -2
- package/dist/bundle/chunks/{native-loader-WM7NDPEO.js → native-loader-HW7GQYPY.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-SA2UJW7Q.js → openai-completions-32RTG3Q4.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-JJ5R7UWV.js → package-manager-cli-LNQOWI3A.js} +1 -1
- package/dist/bundle/chunks/{rg-engine-G2YTYL2T.js → rg-engine-LWZA7TRH.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-EX7PWQ4S.js → rotation-stream-DIKK7U57.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-ITND2BVC.js → rpc-mode-H7QGQI4P.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-D6JNRP3D.js → schedule-command-BUFJOM5L.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-QIIA6MFR.js +3 -0
- package/dist/bundle/chunks/{session-picker-K5FIKV6C.js → session-picker-P53MTWTS.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +110 -103
- package/dist/bundle/chunks/{state-store-IIQL55GC.js → state-store-QGLITAI4.js} +1 -1
- package/dist/bundle/cli.js +2 -2
- 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/cli.js +1 -1
- package/dist/core/dynamic-prompt/build.d.ts +4 -3
- package/dist/core/dynamic-prompt/build.js +4 -2
- package/dist/core/dynamic-prompt/handoff.d.ts +9 -1
- package/dist/core/dynamic-prompt/handoff.js +11 -1
- package/dist/core/dynamic-prompt/intent-gate.js +1 -1
- package/dist/core/dynamic-prompt/style.js +4 -2
- package/dist/core/dynamic-prompt/types.d.ts +7 -1
- package/dist/core/dynamic-prompt/types.js +3 -1
- package/dist/core/dynamic-prompt/verification.d.ts +1 -1
- package/dist/core/dynamic-prompt/verification.js +2 -1
- package/dist/core/extensions/builtin/anthropic-subscription/stream-protocol.d.ts +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/tools.d.ts +9 -2
- package/dist/core/extensions/builtin/anthropic-subscription/tools.js +9 -4
- package/dist/core/extensions/builtin/ask-user/resume.js +20 -9
- package/dist/core/extensions/builtin/ask-user/tool.d.ts +9 -0
- package/dist/core/extensions/builtin/ask-user/tool.js +1 -1
- package/dist/core/extensions/builtin/cache-keepalive/index.js +17 -4
- package/dist/core/extensions/builtin/chat-reply-scrub/index.d.ts +16 -0
- package/dist/core/extensions/builtin/chat-reply-scrub/index.js +39 -0
- package/dist/core/extensions/builtin/chat-reply-scrub/scaffold-strip.d.ts +7 -0
- package/dist/core/extensions/builtin/chat-reply-scrub/scaffold-strip.js +125 -0
- package/dist/core/extensions/builtin/index.js +3 -0
- package/dist/core/extensions/builtin/permission-system/cli.js +1 -0
- package/dist/core/extensions/builtin/permission-system/config.d.ts +1 -0
- package/dist/core/extensions/builtin/permission-system/config.js +10 -0
- package/dist/core/extensions/builtin/permission-system/index.js +2 -2
- package/dist/core/extensions/builtin/permission-system/settings.js +1 -1
- package/dist/core/extensions/builtin/permission-system/types.d.ts +1 -1
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +5 -5
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +6 -6
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5-5.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/claude-sonnet-5-5.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.5.js +9 -6
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +10 -7
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +15 -6
- package/dist/core/extensions/builtin/prompt-preset/gpt-surface.d.ts +2 -2
- package/dist/core/extensions/builtin/prompt-preset/grok-4.5.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/grok-4.7.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-6.js +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.js +1 -1
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +6 -6
- package/dist/core/extensions/builtin/recommended-models/index.d.ts +1 -1
- package/dist/core/extensions/builtin/recommended-models/index.js +1 -1
- package/dist/core/extensions/builtin/todotools/first-turn.d.ts +6 -4
- package/dist/core/extensions/builtin/todotools/first-turn.js +17 -5
- package/dist/core/extensions/builtin/todotools/todo-ask.d.ts +1 -0
- package/dist/core/extensions/builtin/todotools/todo-ask.js +1 -1
- package/dist/core/extensions/builtin/todotools/tools/todo.js +4 -1
- package/dist/core/resource-loader.js +7 -3
- package/dist/modes/interactive/components/ask-user-async-widget.d.ts +2 -0
- package/dist/modes/interactive/components/ask-user-async-widget.js +10 -0
- package/dist/modes/interactive/components/ask-user-question-state.js +3 -1
- package/dist/modes/interactive/interactive-mode.js +7 -1
- package/dist/modes/interactive/session-control-commands.d.ts +2 -1
- package/dist/modes/interactive/session-control-commands.js +15 -6
- package/dist/modes/rpc/connection-question-bridge.js +5 -5
- package/dist/modes/rpc/custom-capability.d.ts +6 -0
- package/dist/modes/rpc/custom-capability.js +6 -0
- package/dist/modes/rpc/extension-ui-response.d.ts +11 -0
- package/dist/modes/rpc/extension-ui-response.js +18 -0
- package/dist/modes/rpc/host-lifecycle.d.ts +5 -2
- package/dist/modes/rpc/host-lifecycle.js +14 -8
- package/dist/modes/rpc/rpc-client.d.ts +1 -1
- package/dist/modes/rpc/rpc-input-validation.d.ts +1 -1
- package/dist/modes/rpc/rpc-input-validation.js +3 -3
- package/dist/modes/rpc/rpc-mode.d.ts +3 -2
- package/dist/modes/rpc/rpc-mode.js +3 -2
- package/dist/modes/rpc/rpc-types.d.ts +4 -3
- package/dist/modes/rpc/session-command-router.js +4 -1
- package/dist/runtime-snapshot/enter.d.ts +1 -1
- package/dist/runtime-snapshot/enter.js +17 -7
- package/dist/runtime-snapshot/file-copier.d.ts +24 -0
- package/dist/runtime-snapshot/file-copier.js +76 -0
- package/dist/runtime-snapshot/layout.d.ts +8 -4
- package/dist/runtime-snapshot/layout.js +137 -70
- package/dist/runtime-snapshot/registry.d.ts +7 -0
- package/dist/runtime-snapshot/registry.js +63 -1
- package/dist/senpi +1 -1
- package/docs/providers.md +1 -1
- package/docs/rpc.md +34 -11
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-AWEAVBCR.js +0 -2
- package/dist/bundle/chunks/chunk-YLQTKWEC.js +0 -6
- package/dist/bundle/chunks/cli-main-ZPMYM3A3.js +0 -3
- package/dist/bundle/chunks/session-control-endpoint-UJJGG4WI.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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-I77ENHCQ.js";import"./chunk-JX2CSKLG.js";import"./chunk-YSNNL5HU.js";import"./chunk-OVGH7VP3.js";import"./chunk-KWI3KUF2.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import"./chunk-EIG6K5U3.js";import{configureHttpDispatcher}from"./chunk-RMVQ5YRX.js";import"./chunk-HEKLJWA4.js";import"./chunk-HPESFBMB.js";import"./chunk-JABBHOD5.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-OOA6OL42.js";import"./chunk-VKECIIYV.js";import"./chunk-FAWC2EIR.js";import"./chunk-7MKMDWHC.js";import"./chunk-ITXF6FAM.js";import"./chunk-CIRZTP7W.js";import"./chunk-MDXUQDGF.js";import"./chunk-A7AQSA6R.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VNYUGCC7.js";import"./chunk-4P4DUW66.js";import"./chunk-T5MOQDGL.js";import"./chunk-6GV3L3GZ.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-HVBFDRP4.js";import"./chunk-6JZQLUAJ.js";import"./chunk-L4QGZJKQ.js";import"./chunk-26UBFF6N.js";import"./chunk-IXONH7ML.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-JXZ5LDJP.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-X4Q5YSTE.js";import"./chunk-CWLCGRUS.js";import"./chunk-DVVROXLZ.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.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-
|
|
2
|
+
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-HVBFDRP4.js";import"./chunk-6JZQLUAJ.js";import"./chunk-L4QGZJKQ.js";import"./chunk-26UBFF6N.js";import"./chunk-IXONH7ML.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-DVVROXLZ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.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-OOA6OL42.js";import"./chunk-VKECIIYV.js";import"./chunk-FAWC2EIR.js";import"./chunk-7MKMDWHC.js";import"./chunk-ITXF6FAM.js";import"./chunk-CIRZTP7W.js";import"./chunk-MDXUQDGF.js";import"./chunk-L4QGZJKQ.js";import"./chunk-26UBFF6N.js";import"./chunk-IXONH7ML.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-DVVROXLZ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,runHostCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
3
|
-
import{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch}from"./chunk-
|
|
3
|
+
import{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch}from"./chunk-7MKMDWHC.js";import"./chunk-ITXF6FAM.js";import"./chunk-CIRZTP7W.js";import"./chunk-MDXUQDGF.js";import"./chunk-U3VOXCGP.js";import"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";export{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch};
|
|
@@ -19,6 +19,6 @@ renameSync(temporary, launcher);
|
|
|
19
19
|
`,{mode:CRASH_RECORD_FILE_MODE})}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}function noteChildExit(daemonDir,code,signal,childStartedAt,now=Date.now()){classifyChildExit(code,signal).exitCode!==0&&recordHostCrash(daemonDir,{at:new Date(now).toISOString(),...signal===null?{code:code??void 0}:{signal},uptimeMs:Math.max(0,now-childStartedAt),kind:"rpc-host",detection:"supervisor",...crashingRuntimeVersions()})}var OBSERVE_REQUEST_FIELD="observe",OBSERVING_COMMANDS=new Set(["get_protocol_info","list_sessions"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}var MAX_CLASSIFIED_LINE_BYTES=64*1024,NEWLINE=10,ClientOccupancy=class{constructor(onAttach){this.clients=new Set,this.observers=new Set,this.attached=new Set,this.onAttach=onAttach}get attachedCount(){return this.attached.size}get unclassifiedCount(){return this.clients.size-this.observers.size-this.attached.size}admit(client){this.clients.add(client);let pending=Buffer.alloc(0),attach=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.attached.add(client),this.onAttach()},classify=chunk=>{pending=Buffer.concat([pending,chunk]);for(let newline=pending.indexOf(NEWLINE);newline!==-1;newline=pending.indexOf(NEWLINE)){let line=pending.subarray(0,newline).toString("utf8");if(pending=pending.subarray(newline+1),!isObservingRequest(line)){attach();return}this.observers.add(client)}pending.length>MAX_CLASSIFIED_LINE_BYTES&&attach()};client.on("data",classify)}release(client){this.clients.delete(client),this.observers.delete(client),this.attached.delete(client)}destroyAll(){for(let client of this.clients)client.destroy()}};var HOST_COLD_START_ENV="SENPI_RPC_HOST_COLD_START",HOST_IDLE_EXIT_MS_ENV="SENPI_RPC_HOST_IDLE_EXIT_MS",DEFAULT_HOST_IDLE_EXIT_MS=9e5,HANDOFF_GRACE_MS_ENV="SENPI_RPC_HANDOFF_GRACE_MS",DEFAULT_HANDOFF_GRACE_MS=6e5;function parseColdStart(value){return value==="transient"||value==="persistent"?value:void 0}function parseIdleExitMs(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveHostPolicy(settings,env){let record=isRecord2(settings)?settings:{},coldStart=parseColdStart(env[HOST_COLD_START_ENV])??parseColdStart(asOptionalString(record.coldStart))??"transient",idleExitMs=parseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV])??parseIdleExitMs(asOptionalString(record.idleExitMs))??9e5;return{coldStart,idleExitMs}}var IdleExitDecider=class{constructor(idleExitMs,now=Date.now){this.idleExitMs=idleExitMs,this.now=now}update(activity){return activity.connections>0||activity.activeTurns>0?(this.idleSince=void 0,"active"):this.idleExitMs===Number.POSITIVE_INFINITY?"idle":this.idleSince===void 0?(this.idleSince=this.now(),"idle"):this.now()-this.idleSince>=this.idleExitMs?"exit":"idle"}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function asOptionalString(value){return typeof value=="string"?value:typeof value=="number"?String(value):void 0}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{createHash,randomUUID}from"node:crypto";import{basename as basename3,dirname as dirname4,join as join6,win32 as win322}from"node:path";import{existsSync as existsSync2,realpathSync as realpathSync2}from"node:fs";import{basename as basename2,dirname as dirname3,join as join5,resolve as resolve2}from"node:path";function canonicalSessionPath(path){let absolutePath=resolve2(path),missing=[],existing=absolutePath;for(;!existsSync2(existing);){let parent=dirname3(existing);if(parent===existing)return absolutePath;missing.unshift(basename2(existing)),existing=parent}try{return join5(realpathSync2(existing),...missing)}catch{return absolutePath}}var HOST_DAEMON_DIR_ENV="SENPI_RPC_HOST_DAEMON_DIR";function canonicalEndpointPath(socket,platform=process.platform){return platform==="win32"?win322.normalize(socket).toLowerCase():socket.startsWith("\0")?socket:join6(canonicalSessionPath(dirname4(socket)),basename3(socket))}function daemonDirectoryName(socket,platform=process.platform){return directoryNameOf(canonicalEndpointPath(socket,platform))}function directoryNameOf(endpoint){return createHash("sha256").update(endpoint,"utf8").digest("hex").slice(0,16)}function createHostDaemonPaths(target){let flatDir=join6(target.agentDir??getAgentDir(),"rpc-host-daemon");return{socket:target.socket,flatDir,layoutMarker:join6(flatDir,"layout.json"),legacyPidFile:join6(flatDir,"host.pid"),...hostDaemonDirectoryPaths(join6(flatDir,daemonDirectoryName(target.socket)))}}function hostDaemonDirectoryPaths(dir){return{dir,endpointFile:join6(dir,"endpoint.json"),pointerFile:join6(dir,"host.pid"),lockFile:join6(dir,"daemon.lock"),settingsFile:join6(dir,"settings.json"),stderrLog:join6(dir,"stderr.log"),generationsDir:join6(dir,"generations"),reservationsDir:join6(dir,"reservations")}}function generationPaths(paths,instanceId){let dir=join6(paths.generationsDir,instanceId);return{dir,relativeDir:`generations/${instanceId}`,pidFile:join6(dir,"host.pid"),settingsFile:join6(dir,"settings.json"),scratchDir:join6(dir,"scratch")}}import{rename,rm}from"node:fs/promises";var CALVER=/^(\d+)\.(\d+)\.(\d+)(?:-(\d+))?/;function engineBuildIdentityFrom(build){let match=CALVER.exec(build.version),epoch=Number.isSafeInteger(build.epoch)&&build.epoch!==void 0&&build.epoch>0?build.epoch:0,sha7=build.sha7??"";return{text:epoch===0?build.version:`${build.version}+${epoch}${sha7===""?"":`.${sha7}`}`,ordinal:[match?Number(match[1]):0,match?Number(match[2]):0,match?Number(match[3]):0,match?.[4]?Number(match[4]):0,epoch],scheme:epoch===0?"nodef":"epoch"}}var BUILT=engineBuildIdentityFrom({version:VERSION,epoch:typeof SENPI_BUILD_EPOCH=="number"?SENPI_BUILD_EPOCH:0,sha7:typeof SENPI_BUILD_SHA7=="string"?SENPI_BUILD_SHA7:""});import{readFile,writeFile}from"node:fs/promises";async function readFileOrUndefined(path){try{return await readFile(path,"utf8")}catch(error){if(isNodeErrorCode2(error,"ENOENT")||isNodeErrorCode2(error,"ENOTDIR"))return;throw error}}function parseJson(text){if(text!==void 0)try{let parsed=JSON.parse(text);return isRecord3(parsed)?parsed:void 0}catch{return}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode2(error,code){return error instanceof Error&&"code"in error&&error.code===code}var TABLE_START_BYTES=1<<20,TABLE_MAX_BYTES=32<<20;async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId),record=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record!==void 0&&record.pid!==owner.pid)return;let ownsPointer=parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId;ownsPointer&&await rm(paths.settingsFile,{force:!0}),await rm(generation.dir,{recursive:!0,force:!0}),ownsPointer&&await rm(paths.pointerFile,{force:!0})}var HOST_INSTANCE_ID_ENV="SENPI_RPC_HOST_INSTANCE_ID";import{mkdir,readFile as readFile2,rename as rename2,stat,unlink,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname5}from"node:path";var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner";var MAX_SOCKET_PATH_BYTES=103;function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}async function statSocketIdentity(socketPath){try{let{dev,ino}=await stat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}}async function classifyEndpointOwnership(socketPath,identity){if(identity===void 0||process.platform==="win32"||socketPath.startsWith("\0"))return"unknown";let current;try{current=await statSocketIdentity(socketPath)}catch{return"unknown"}return current===void 0?"absent":sameSocketIdentity(current,identity)?"held":"replaced"}async function writeSocketIdentityFile(path,identity){await mkdir(dirname5(path),{recursive:!0,mode:448});let tmpPath=`${path}.${process.pid}.tmp`;await writeFile2(tmpPath,`${JSON.stringify(identity)}
|
|
20
20
|
`,{mode:384}),await rename2(tmpPath,path)}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink(socketPath)}catch(cause){isNodeErrorCode3(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename2(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename2(shieldPath,socketPath)}catch{}}}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode3(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0||process.platform==="win32")return()=>{};let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function ignore(){}var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID";var HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";import{StringDecoder}from"node:string_decoder";var MAX_RPC_LINE_CHARACTERS=16*1024*1024;function attachJsonlLineReader(stream,onLine,options={}){let decoder=new StringDecoder("utf8"),maxLineLength=options.maxLineLength??Number.POSITIVE_INFINITY;if(!(maxLineLength>0))throw new Error("maxLineLength must be greater than zero.");let buffer="",discardingOversizedLine=!1,consume=text=>{let offset=0;for(;offset<text.length;){if(discardingOversizedLine){let newlineIndex2=text.indexOf(`
|
|
21
21
|
`,offset);if(newlineIndex2===-1)return;discardingOversizedLine=!1,offset=newlineIndex2+1;continue}let newlineIndex=text.indexOf(`
|
|
22
|
-
`,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}import{createHash as createHash2,randomBytes,timingSafeEqual}from"node:crypto";import{chmod,mkdir as mkdir2,readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname6,win32 as win323}from"node:path";var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){try{let existing=await readFile3(path);if(existing.length===SOCKET_SECRET_BYTES)return existing}catch(error){if(!isNodeErrorCode4(error,"ENOENT"))throw error}return createSocketSecret(path)}async function createSocketSecret(path){await mkdir2(dirname6(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile3(path,secret,{mode:384}),await chmod(path,384),secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win323.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash2("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode4(error,code){return error instanceof Error&&"code"in error&&error.code===code}var CHILD_STOP_TIMEOUT_MS=5e3,WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3,CHILD_WATCH_FD=3;async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join7(baseDir,`internal-${randomUUID2()}`);return await mkdir3(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID2()}`,dir:dir2,secretPath:join7(dir2,"secret")}}let dir=join7(tmpdir(),`senpi-rpc-host-internal-${randomUUID2().slice(0,8)}`);return await mkdir3(dir,{recursive:!1,mode:448}),await writeFile4(join7(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join7(dir,"host.sock"),dir,secretPath:join7(dir,".secret")}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,bindSocket,replaceIdentity}}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveCliMainPath(){let modulePath=fileURLToPath3(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve3(dirname7(modulePath),"..","..",`cli-main${extension}`);return existsSync3(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname7(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve3(dir,"package.json");if(existsSync3(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve3(dir,candidate);if(existsSync3(entry))return entry}}catch{}return}let parent=dirname7(dir);if(parent===dir)return;dir=parent}}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...process.execArgv,resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID2(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,internal=await createInternalSocketPath(paths.dir),internalSocket=internal.socket,internalSecretPath=internal.secretPath??socketSecretPath(internalSocket),internalSecret=process.platform==="win32"?await createSocketSecret(internalSecretPath):void 0,clients=new ClientOccupancy(()=>decider.update(currentActivity())),busySessions=new Map,observerSocket,observerLink=createObserverLink({open:async()=>{let secret=internalSecret,next=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,secret));return secret&&sendSocketHandshake(next,secret),await waitForConnect(next,5e3),observerSocket=next,attachJsonlLineReader(next,observeHostEvent,{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{next.once("close",handler),next.once("error",handler)}}},settled:()=>shuttingDown,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}}),childExitWatchTimer,stopSupersessionWatch,shuttingDown=!1,draining=!1,handoffGraceTimer,shutdownPromise,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:paths.dir,[HOST_INSTANCE_ID_ENV]:instanceId,[HOST_WATCH_FD_ENV]:String(CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},...internalSecret?{[SOCKET_SECRET_FILE_ENV]:internalSecretPath}:{},[HOST_CLEANUP_PATHS_ENV]:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:!!successor,platform:process.platform}).join(`
|
|
22
|
+
`,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}import{createHash as createHash2,randomBytes,timingSafeEqual}from"node:crypto";import{chmod,mkdir as mkdir2,readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{dirname as dirname6,win32 as win323}from"node:path";var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){try{let existing=await readFile3(path);if(existing.length===SOCKET_SECRET_BYTES)return existing}catch(error){if(!isNodeErrorCode4(error,"ENOENT"))throw error}return createSocketSecret(path)}async function createSocketSecret(path){await mkdir2(dirname6(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile3(path,secret,{mode:384}),await chmod(path,384),secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win323.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash2("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode4(error,code){return error instanceof Error&&"code"in error&&error.code===code}var CHILD_STOP_TIMEOUT_MS=5e3,WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3,CHILD_WATCH_FD=3;async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join7(baseDir,`internal-${randomUUID2()}`);return await mkdir3(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID2()}`,dir:dir2,secretPath:join7(dir2,"secret")}}let dir=join7(tmpdir(),`senpi-rpc-host-internal-${randomUUID2().slice(0,8)}`);return await mkdir3(dir,{recursive:!1,mode:448}),await writeFile4(join7(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join7(dir,"host.sock"),dir,secretPath:join7(dir,".secret")}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,bindSocket,replaceIdentity}}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveCliMainPath(modulePath=fileURLToPath3(import.meta.url),bundled=isBundledNode){let declared=bundled?resolveDeclaredCliEntry(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve3(dirname7(modulePath),"..","..",`cli-main${extension}`);return existsSync3(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname7(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve3(dir,"package.json");if(existsSync3(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve3(dir,candidate);if(existsSync3(entry))return entry}}catch{}return}let parent=dirname7(dir);if(parent===dir)return;dir=parent}}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...process.execArgv,resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID2(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,internal=await createInternalSocketPath(paths.dir),internalSocket=internal.socket,internalSecretPath=internal.secretPath??socketSecretPath(internalSocket),internalSecret=process.platform==="win32"?await createSocketSecret(internalSecretPath):void 0,clients=new ClientOccupancy(()=>decider.update(currentActivity())),busySessions=new Map,observerSocket,observerLink=createObserverLink({open:async()=>{let secret=internalSecret,next=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,secret));return secret&&sendSocketHandshake(next,secret),await waitForConnect(next,5e3),observerSocket=next,attachJsonlLineReader(next,observeHostEvent,{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{next.once("close",handler),next.once("error",handler)}}},settled:()=>shuttingDown,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}}),childExitWatchTimer,stopSupersessionWatch,shuttingDown=!1,draining=!1,handoffGraceTimer,shutdownPromise,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:paths.dir,[HOST_INSTANCE_ID_ENV]:instanceId,[HOST_WATCH_FD_ENV]:String(CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},...internalSecret?{[SOCKET_SECRET_FILE_ENV]:internalSecretPath}:{},[HOST_CLEANUP_PATHS_ENV]:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:!!successor,platform:process.platform}).join(`
|
|
23
23
|
`),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:["ignore","ignore","inherit","pipe"],windowsHide:!0}),childStartedAt=Date.now();child.stdio[CHILD_WATCH_FD]?.on("error",()=>{}),child.once("exit",(code,signal)=>{if(shuttingDown)return;let{reason,exitCode}=classifyChildExit(code,signal);noteChildExit(paths.dir,code,signal,childStartedAt),shutdown(reason,exitCode)});let server=createServer(client=>{let accept=()=>{if(shuttingDown||draining){client.destroy();return}let internal2=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,internalSecret));internalSecret&&sendSocketHandshake(internal2,internalSecret),clients.admit(client);let detach=()=>{clients.release(client),decider.update(currentActivity()),internal2.destroy(),client.destroy()};client.pipe(internal2),internal2.pipe(client),client.once("close",detach),client.once("error",detach),internal2.once("end",()=>client.end(()=>client.destroy())),internal2.once("close",()=>{internal2.readableEnded||detach()}),internal2.once("error",detach)};publicSecret?authenticateSocket(client,publicSecret,accept):accept()});server.once("error",cause=>{shuttingDown||shutdown(`public socket listener failed: ${errorMessage2(cause)}`,1)});let decider=new IdleExitDecider(policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs),tickIntervalMs=Math.max(20,Math.min(1e3,policy.idleExitMs/4)),ticker=setInterval(()=>{!draining&&decider.update(currentActivity())==="exit"&&clients.unclassifiedCount===0&&shutdown("idle",0)},tickIntervalMs);function currentActivity(){return{connections:clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:observerLink.healthy(),unhealthySince:observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:decider.idleExitMs,observedBusy:countBusySessions()})}}function countBusySessions(){let busy=0;for(let count of busySessions.values())count>0&&busy++;return busy}function observeHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId}=event;if(typeof sessionId=="string"){if(type==="agent_start")busySessions.set(sessionId,(busySessions.get(sessionId)??0)+1);else if(type==="agent_settled")busySessions.set(sessionId,Math.max(0,(busySessions.get(sessionId)??1)-1));else return;decider.update(currentActivity())}}async function shutdown(reason,exitCode){return shutdownPromise??=performShutdown(reason,exitCode),shutdownPromise}async function performShutdown(reason,exitCode){shuttingDown&&process.exit(exitCode),shuttingDown=!0,clearInterval(ticker),handoffGraceTimer&&clearTimeout(handoffGraceTimer),childExitWatchTimer&&clearInterval(childExitWatchTimer),stopSupersessionWatch?.();let hardExit=process.platform==="win32"?setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS):void 0;try{writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`),clients.destroyAll(),draining||await shieldSocketDuringClose(publicSocket,()=>closeServer(server)),internal.dir&&await rm2(internal.dir,{recursive:!0,force:!0}),await stopChild(child),observerLink.stop(),observerSocket?.destroy(),publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedSocket(publicSocket,publicSocketIdentity,supervisorLog),await releaseGeneration(paths,{instanceId,pid:process.pid})}finally{hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}let publicSocketOwned=!1,publicSocketIdentity;function supervisorLog(message){writeStderrLine(`senpi rpc host supervisor: ${message}`)}function drainForHandoff(){if(draining||shuttingDown)return;draining=!0,supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;handoffGraceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),requestChildDrain()},graceMs),handoffGraceTimer.unref(),requestChildDrain()}function requestChildDrain(){if(child.pid!==void 0&&child.exitCode===null&&child.signalCode===null)try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage2(cause)}`)}}registerSupervisorSignals(shutdown,drainForHandoff);try{await waitForListener(internalSocket,3e4,internalSecret),await observerLink.open(),await prepareSocketPath(bindSocket),await listen(server,bindSocket,publicSecret),publicSocketOwned=!0,successor&&await adoptPublicSocket(bindSocket,publicSocket,launch.replaceIdentity),publicSocketIdentity=await statSocketIdentity(publicSocket),publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join7(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),publicSocketIdentity),stopSupersessionWatch=watchForSupersession({path:publicSocket,identity:publicSocketIdentity,settled:()=>shuttingDown||draining},loss=>{supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drainForHandoff()})}catch(cause){await shutdown(`startup failed: ${errorMessage2(cause)}`,1)}if(process.platform==="win32"&&child.pid!==void 0){let childStartTime=await readProcessStartTime(child.pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checkingChildIdentity=!1;childExitWatchTimer=setInterval(()=>{shuttingDown||checkingChildIdentity||child.exitCode!==null||child.signalCode!==null||(checkingChildIdentity=!0,readProcessStartTime(child.pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(child.pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&¤tStartTime!==void 0&¤tStartTime!==childStartTime||missingIdentityChecks>=2)&&shutdown("rpc host child exit observed by identity watchdog",0)}).catch(()=>{}).finally(()=>{checkingChildIdentity=!1}))},500),childExitWatchTimer.unref?.()}writeStderrLine(`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${policy.coldStart==="persistent"?"never":String(policy.idleExitMs)})`),await new Promise(()=>{})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename3(bindSocket,publicSocket)}async function ensurePublicSocketSecret(publicSocket){let secretPath=socketSecretPath(publicSocket);try{return await ensureSocketSecret(secretPath)}catch(cause){throw new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`,{cause})}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile4(settingsFile,"utf8"))}catch{return}}async function stopChild(child){if(!(child.exitCode!==null||child.signalCode!==null)){try{child.kill("SIGTERM")}catch{return}if(!await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)){try{child.kill("SIGKILL")}catch{return}await waitForChildExit(child,2e3)}}}function waitForChildExit(child,timeoutMs){return child.exitCode!==null||child.signalCode!==null?Promise.resolve(!0):new Promise(resolve4=>{let timer=setTimeout(()=>{child.off("exit",onExit2),resolve4(!1)},timeoutMs),onExit2=()=>{clearTimeout(timer),resolve4(!0)};child.once("exit",onExit2)})}async function waitForListener(socketPath,timeoutMs,secret){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await canConnect(socketPath,secret))return;await delay(50)}throw new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`)}function canConnect(socketPath,secret){return new Promise(resolve4=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret));secret&&sendSocketHandshake(socket,secret);let settle=value=>{socket.destroy(),resolve4(value)};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1))})}function waitForConnect(socket,timeoutMs){return new Promise((resolve4,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve4()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}async function prepareSocketPath(socketPath){if(process.platform!=="win32"){if(Buffer.byteLength(socketPath)>MAX_SOCKET_PATH_BYTES)throw new Error(`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`);await mkdir3(dirname7(socketPath),{recursive:!0,mode:448});try{await access(socketPath)}catch(cause){if(isNodeErrorCode5(cause,"ENOENT"))return;throw cause}if(await canConnect(socketPath))throw new Error(`${socketPath}: address already in use by a live server.`);await unlink2(socketPath)}}function listen(server,socketPath,secret){return new Promise((resolve4,reject)=>{server.once("error",reject),server.listen({path:resolveSocketTransportAddress(socketPath,process.platform,secret),readableAll:!1,writableAll:!1},async()=>{server.off("error",reject);try{process.platform!=="win32"&&!socketPath.startsWith("\0")&&await chmod2(socketPath,384),resolve4()}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise(resolve4=>{server.close(()=>resolve4())})}function writeStderrLine(text){try{writeSync(2,`${text}
|
|
24
24
|
`)}catch{}}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode5(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}function isEntryScript(){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath3(import.meta.url)===realpathSync3(entry)}catch{return!1}}if(!isBundledNode&&isEntryScript()){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}export{DEFAULT_HANDOFF_GRACE_MS,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,INTERNAL_SUPERVISOR_FLAG,IdleExitDecider,classifyChildExit,createInternalSocketPath,findInternalSupervisorArgs,parseColdStart,parseIdleExitMs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,resolveHostPolicy,runHostSupervisor,spawnableChildLaunch};
|
|
@@ -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,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-I77ENHCQ.js";import"./chunk-JX2CSKLG.js";import"./chunk-YSNNL5HU.js";import"./chunk-OVGH7VP3.js";import"./chunk-KWI3KUF2.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import{isApiKeyLoginProvider}from"./chunk-EIG6K5U3.js";import"./chunk-RMVQ5YRX.js";import"./chunk-HEKLJWA4.js";import"./chunk-HPESFBMB.js";import"./chunk-JABBHOD5.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-OOA6OL42.js";import"./chunk-VKECIIYV.js";import"./chunk-FAWC2EIR.js";import"./chunk-7MKMDWHC.js";import"./chunk-ITXF6FAM.js";import"./chunk-CIRZTP7W.js";import"./chunk-MDXUQDGF.js";import"./chunk-A7AQSA6R.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VNYUGCC7.js";import"./chunk-4P4DUW66.js";import"./chunk-T5MOQDGL.js";import"./chunk-6GV3L3GZ.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-HVBFDRP4.js";import"./chunk-6JZQLUAJ.js";import"./chunk-L4QGZJKQ.js";import"./chunk-26UBFF6N.js";import"./chunk-IXONH7ML.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-JXZ5LDJP.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-X4Q5YSTE.js";import"./chunk-CWLCGRUS.js";import"./chunk-DVVROXLZ.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
|
|
@@ -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{TIP_DEFINITIONS}from"./chunk-
|
|
2
|
+
import{TIP_DEFINITIONS}from"./chunk-OVGH7VP3.js";import{KeybindingsManager}from"./chunk-KWI3KUF2.js";import"./chunk-HEKLJWA4.js";import"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";function collectTips(){let keybindings=new KeybindingsManager,keys=binding=>keybindings.getKeys(binding).join("/");return TIP_DEFINITIONS.map(tip=>{let text=tip.render(keys);return tip.requiresCommand!==void 0?{id:tip.id,text,requiresCommand:tip.requiresCommand}:{id:tip.id,text}})}function listTips(){console.log(JSON.stringify(collectTips(),null,2))}export{collectTips,listTips};
|
package/dist/bundle/chunks/{multi-session-host-IBVJ3WN7.js → multi-session-host-ZFT6RM2S.js}
RENAMED
|
@@ -1,12 +1,12 @@
|
|
|
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{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,SessionManager,assertValidSessionId,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,isSessionBusySnapshot,readOwnFootprint,runWithProviderScope,startHostChildReaper}from"./chunk-
|
|
2
|
+
import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,SessionManager,assertValidSessionId,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,isSessionBusySnapshot,readOwnFootprint,runWithProviderScope,startHostChildReaper}from"./chunk-I77ENHCQ.js";import"./chunk-JX2CSKLG.js";import"./chunk-YSNNL5HU.js";import"./chunk-OVGH7VP3.js";import"./chunk-KWI3KUF2.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import{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}from"./chunk-EIG6K5U3.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-RMVQ5YRX.js";import"./chunk-HEKLJWA4.js";import{buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError,sessionPromptSurfaceError}from"./chunk-HPESFBMB.js";import"./chunk-JABBHOD5.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import{GENERATION_HANDOFF_CAPABILITY,runAsHostGenerationProcess}from"./chunk-OOA6OL42.js";import"./chunk-VKECIIYV.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_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-FAWC2EIR.js";import{ClientOccupancy,armHostWatchdog,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-7MKMDWHC.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-ITXF6FAM.js";import"./chunk-CIRZTP7W.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-MDXUQDGF.js";import"./chunk-A7AQSA6R.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-VNYUGCC7.js";import"./chunk-4P4DUW66.js";import{killTrackedDetachedChildren}from"./chunk-T5MOQDGL.js";import"./chunk-6GV3L3GZ.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-HVBFDRP4.js";import"./chunk-6JZQLUAJ.js";import"./chunk-L4QGZJKQ.js";import"./chunk-26UBFF6N.js";import"./chunk-IXONH7ML.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-JXZ5LDJP.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-X4Q5YSTE.js";import"./chunk-CWLCGRUS.js";import"./chunk-DVVROXLZ.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.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 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.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)};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});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
3
|
`))}};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
4
|
`))}};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
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()))}}function isHandoffBusy(snapshot){return isSessionBusySnapshot({...snapshot,hasActiveWakeSource:!1})}function selectDrainVerdicts(registry,inFlight,unreadable){let park=[],gone=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open"||inFlight(sessionId))continue;let entry=registry.peek(sessionId);!entry||handoffBusy(entry,sessionId,unreadable)||(sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)?gone.push(sessionId):park.push(sessionId))}return{park,gone}}function handoffBusy(entry,sessionId,unreadable){try{let snapshot=entry.runtime?.session.activitySnapshot;return entry.worker?.handoffBusy===!0||snapshot!==void 0&&isHandoffBusy(snapshot)}catch(cause){return unreadable(sessionId,cause),!1}}function readDrainVerdicts(registry,inFlight){try{return selectDrainVerdicts(registry,inFlight,(sessionId,cause)=>{process.stderr.write(`senpi rpc handoff activity of ${sessionId} unreadable, parking: ${String(cause)}
|
|
6
6
|
`)})}catch(cause){process.stderr.write(`senpi rpc handoff drain pass failed, retrying: ${String(cause)}
|
|
7
7
|
`);return}}import{existsSync}from"node:fs";import{isAbsolute as isAbsolute2}from"node:path";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)}
|
|
8
8
|
`)}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 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}}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=>this.entries.delete(handle),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 this.settleClosingReservation(sessionPath),sessionPath&&this.reservations.has(sessionPath)){let existing=[...this.entries].find(([,entry3])=>entry3.reservationKey===sessionPath&&entry3.state==="open");if(!existing)throw new RpcSessionRegistryError("session_path_in_use");let[handle2,entry2]=existing,wasParked=entry2.retainOnDisconnect===!0&&entry2.attachments===0;if(entry2.attachments+=1,this.options.pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry2.retainOnDisconnect=!0),!entry2.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return profile.promptSurface!==void 0&&profile.promptSurface!==entry2.profile.promptSurface&&(entry2.profile=frozenProfile({...entry2.profile,promptSurface:profile.promptSurface}),entry2.runtime?.setPromptSurface(profile.promptSurface)),entry2.lastCommandAt=this.now(),wasParked&&(entry2.lifecycleMutex=entry2.lifecycleMutex.then(()=>entry2.runtime?.emitAttachmentEvent("session_resumed")),await entry2.lifecycleMutex),{sessionId:handle2,durableSessionId:entry2.durableSessionId,sessionPath:entry2.sessionPath,attached:!0}}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=(sessionPath2,options2)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options2?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath2,options2);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,this.options.createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),runtime.releaseSessionHold(),entry.runtime=replacement,this.syncRuntimeMetadata(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation},requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),this.entries.set(handle,entry);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),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)}}async settleClosingReservation(sessionPath){let closing=[...this.entries.values()].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,this.closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}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(){for(let entry of this.entries.values()){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&&(this.reservations.delete(entry.reservationKey),this.options.pathReservations?.release(entry.reservationKey)),currentKey&&(this.reservations.add(currentKey),this.options.pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}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}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)}
|
|
9
|
-
`)}).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,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,PROMPT_SURFACE_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 rows=this.registry.list(),sessions=command.include_workers===!0?rows:rows.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 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}:{}},{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),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)}
|
|
9
|
+
`)}).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,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,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 rows=this.registry.list(),sessions=command.include_workers===!0?rows:rows.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 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}:{}},{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),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)}
|
|
10
10
|
`)})});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)}
|
|
11
11
|
`)}))});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)}
|
|
12
12
|
`)}this.bindings.delete(sessionId);try{await this.registry.closeMarked(sessionId)}catch(cause){process.stderr.write(`senpi rpc close for session ${sessionId} failed: ${String(cause)}
|
|
@@ -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{getPackageDir}from"./chunk-
|
|
2
|
+
import{getPackageDir}from"./chunk-FNCILR4E.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";import{createRequire}from"node:module";import{dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{isQuarantinedNativeFile,QUARANTINE_ATTRIBUTE}from"@earendil-works/pi-pty";var NATIVE_GREP_ABI_VERSION="1",NativeGrepSentinelMismatchError=class extends Error{constructor(modulePath){super(`Native grep ABI mismatch in ${modulePath}: expected __senpiGrepAbi1() === "1" and a grep function`),this.code="native-sentinel-mismatch",this.name="NativeGrepSentinelMismatchError",this.modulePath=modulePath}};function getNativeGrepCandidatePaths(options={}){let env=options.env??process.env;if(env.SENPI_GREP_NATIVE_PATH)return[env.SENPI_GREP_NATIVE_PATH];let host=`${options.platform??process.platform}-${options.arch??process.arch}`,file=`senpi_grep.${host}.node`,packageDir=options.packageDir??(env.SENPI_PACKAGE_DIR||getPackageDir()),moduleDir=options.moduleDir??dirname(fileURLToPath(import.meta.url)),execPath=options.execPath??process.execPath;return[join(packageDir,"native/prebuilds",host,file),join(moduleDir,"../../../../native/prebuilds",host,file),join(dirname(execPath),"native/prebuilds",host,file)]}function loadNativeGrep(options={}){let attemptedPaths=getNativeGrepCandidatePaths(options),platform=options.platform??process.platform,host=`${platform}-${options.arch??process.arch}`,requireBinding=options.requireBinding??createRequire(import.meta.url),isQuarantined=options.isQuarantined??(path=>isQuarantinedNativeFile(path,platform)),causes=[];for(let modulePath of attemptedPaths){if(isQuarantined(modulePath)){causes.push(`${modulePath}: blocked because ${QUARANTINE_ATTRIBUTE} is present (macOS Gatekeeper)`);continue}try{let native=requireBinding(modulePath);return assertNativeGrepBinding(native,modulePath),{native,diagnostic:null}}catch(error){if(error instanceof NativeGrepSentinelMismatchError)throw error;causes.push(`${modulePath}: ${error instanceof Error?error.message:String(error)}`)}}return{native:null,diagnostic:{code:"native-unavailable",host,attemptedPaths,message:`No native grep prebuild is available for ${host}.`,cause:causes.join("; ")}}}function assertNativeGrepBinding(value,modulePath){if(typeof value!="object"||value===null||!("grep"in value)||typeof value.grep!="function"||!("__senpiGrepAbi1"in value)||typeof value.__senpiGrepAbi1!="function"||value.__senpiGrepAbi1()!==NATIVE_GREP_ABI_VERSION)throw new NativeGrepSentinelMismatchError(modulePath)}export{NATIVE_GREP_ABI_VERSION,NativeGrepSentinelMismatchError,getNativeGrepCandidatePaths,loadNativeGrep};
|
package/dist/bundle/chunks/{openai-completions-SA2UJW7Q.js → openai-completions-32RTG3Q4.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-XO7VCMY6.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{retryProviderStreamRequest}from"./chunk-KLBKUBDV.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-7MUTNWPO.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-CWLCGRUS.js";import{getOpenAICompletionsCompat}from"./chunk-BJICJY47.js";import{sendWithForcedToolChoiceFallback}from"./chunk-LHYG7TK7.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-KRNXUTZJ.js";import{readProviderDiagnostic}from"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{appendGrammarToolInputJsonDelta,calculateCost,clampThinkingLevel,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,inferOpenAIThinkingLevelMap,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsMax,supportsXhigh,transformMessages}from"./chunk-Z2N5372Y.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.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 getDeferredToolNames(messages){let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);return names}function getToolsByName(tools,names){if(!tools)return[];let toolsByName=new Map(tools.map(tool=>[tool.name,tool]));return Array.from(names).map(name=>toolsByName.get(name)).filter(tool=>tool!==void 0)}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;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(context.tools,compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,context,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,context,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(!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-XO7VCMY6.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{retryProviderStreamRequest}from"./chunk-KLBKUBDV.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-7MUTNWPO.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-CWLCGRUS.js";import{getOpenAICompletionsCompat}from"./chunk-DVVROXLZ.js";import{sendWithForcedToolChoiceFallback}from"./chunk-LHYG7TK7.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-KRNXUTZJ.js";import{readProviderDiagnostic}from"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{appendGrammarToolInputJsonDelta,calculateCost,clampThinkingLevel,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,inferOpenAIThinkingLevelMap,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsMax,supportsXhigh,transformMessages}from"./chunk-Z2N5372Y.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.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 getDeferredToolNames(messages){let names=new Set;for(let message of messages)if(message.role==="toolResult")for(let name of message.addedToolNames??[])names.add(name);return names}function getToolsByName(tools,names){if(!tools)return[];let toolsByName=new Map(tools.map(tool=>[tool.name,tool]));return Array.from(names).map(name=>toolsByName.get(name)).filter(tool=>tool!==void 0)}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;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(context.tools,compat.supportsOpenAIGrammarTools),cacheRetention=resolveCacheRetention(options?.cacheRetention??model.cacheRetention,options?.env),cacheSessionId=cacheRetention==="none"?void 0:options?.sessionId,client=createClient(model,context,clientAuth.apiKey,clientAuth.headers,options?.fetch,cacheSessionId,compat),params=buildParams(model,context,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(!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(context.tools,compat.supportsOpenAIGrammarTools)){let 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);let deferredToolNames=compat.deferredToolsMode==="kimi"?getDeferredToolNames(context.messages):new Set,activeTools=context.tools?.filter(tool=>!deferredToolNames.has(tool.name));activeTools&&activeTools.length>0?(params.tools=convertTools(activeTools,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),options?.samplingParams&&Object.assign(params,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 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(context.messages,model,id=>normalizeToolCallId(id),{preserveThinking:options.preserveThinking,normalizeSameModelToolCallIds:!0}),mergeAdjacentUserMessages=!model.baseUrl.includes("api.openai.com");if(context.systemPrompt){let role=model.reasoning&&compat.supportsDeveloperRole?"developer":"system";params.push({role,content:sanitizeSurrogates(context.systemPrompt)})}let 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==="user")if(typeof msg.content=="string")appendUserMessage(params,sanitizeSurrogates(msg.content),mergeAdjacentUserMessages);else{let content=msg.content.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(`
|