@code-yeongyu/senpi 2026.9.18-2 → 2026.9.18-3

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.
Files changed (86) hide show
  1. package/CHANGELOG.md +27 -2
  2. package/dist/bundle/chunks/{anthropic-messages-ZEJ3DPCP.js → anthropic-messages-WZCFP6BT.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-NFZDKQOY.js → app-server-command-SXMDPCO3.js} +1 -1
  4. package/dist/bundle/chunks/bun-extension-importer-JIWSA22V.js +10 -0
  5. package/dist/bundle/chunks/{chunk-XJUVWITG.js → chunk-3FRTRCR6.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-VRAYXSST.js → chunk-FDLVINNY.js} +2 -2
  7. package/dist/bundle/chunks/{chunk-PJ5U4M7M.js → chunk-FYFLULRU.js} +5 -5
  8. package/dist/bundle/chunks/chunk-IXAUDPOK.js +2 -0
  9. package/dist/bundle/chunks/chunk-MA3Z67LK.js +8 -0
  10. package/dist/bundle/chunks/{chunk-ANTGWIGI.js → chunk-MUC3MZTV.js} +1 -1
  11. package/dist/bundle/chunks/chunk-NQAVM5XL.js +2 -0
  12. package/dist/bundle/chunks/{chunk-4C7LNOHI.js → chunk-PLZK7ABD.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-CKNRCW35.js → chunk-RLRLQRI2.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-NBUMCMS4.js → chunk-VRDDXZF3.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-QROWINIH.js → chunk-XK24AFYU.js} +1 -1
  16. package/dist/bundle/chunks/cli-main-ACDTRT2W.js +3 -0
  17. package/dist/bundle/chunks/{interactive-host-runtime-LMJRUOPI.js → interactive-host-runtime-FAKC3LHA.js} +1 -1
  18. package/dist/bundle/chunks/interactive-mode-4YCBGS3E.js +2 -0
  19. package/dist/bundle/chunks/{multi-session-host-G5EQB6ED.js → multi-session-host-HBY64KFU.js} +1 -1
  20. package/dist/bundle/chunks/{openai-completions-2RS3VSPV.js → openai-completions-TOWYKX2U.js} +1 -1
  21. package/dist/bundle/chunks/{package-manager-cli-OE6ZSJ6C.js → package-manager-cli-23TYIHVC.js} +1 -1
  22. package/dist/bundle/chunks/{rotation-stream-EBOPFJMX.js → rotation-stream-KDLA7K6X.js} +1 -1
  23. package/dist/bundle/chunks/rpc-mode-ARUKMUCA.js +2 -0
  24. package/dist/bundle/chunks/{session-picker-BUHK3FCS.js → session-picker-DXCITGLS.js} +1 -1
  25. package/dist/bundle/chunks/session-worker.js +25 -25
  26. package/dist/bundle/cli.js +1 -1
  27. package/dist/bundle/index.js +1 -1
  28. package/dist/bundle/rpc-entry.js +1 -1
  29. package/dist/core/extensions/bun-extension-registry.d.ts +4 -0
  30. package/dist/core/extensions/bun-extension-registry.d.ts.map +1 -1
  31. package/dist/core/extensions/bun-extension-registry.js +59 -11
  32. package/dist/core/extensions/bun-extension-registry.js.map +1 -1
  33. package/dist/core/extensions/extension-runtime-module.d.ts +5 -0
  34. package/dist/core/extensions/extension-runtime-module.d.ts.map +1 -0
  35. package/dist/core/extensions/extension-runtime-module.js +6 -0
  36. package/dist/core/extensions/extension-runtime-module.js.map +1 -0
  37. package/dist/core/model-resolver.d.ts.map +1 -1
  38. package/dist/core/model-resolver.js +1 -0
  39. package/dist/core/model-resolver.js.map +1 -1
  40. package/docs/providers.md +30 -0
  41. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
  42. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  43. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  44. package/node_modules/@earendil-works/pi-ai/README.md +9 -0
  45. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  46. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +1 -0
  47. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  48. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts +2 -0
  49. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts.map +1 -1
  50. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js +2 -0
  51. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js.map +1 -1
  52. package/node_modules/@earendil-works/pi-ai/dist/providers/all.d.ts.map +1 -1
  53. package/node_modules/@earendil-works/pi-ai/dist/providers/all.js +2 -0
  54. package/node_modules/@earendil-works/pi-ai/dist/providers/all.js.map +1 -1
  55. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.d.ts +13 -0
  56. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.d.ts.map +1 -0
  57. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.js +55 -0
  58. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.js.map +1 -0
  59. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.d.ts +11 -0
  60. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.d.ts.map +1 -0
  61. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.js +94 -0
  62. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.js.map +1 -0
  63. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.d.ts +4 -0
  64. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.d.ts.map +1 -0
  65. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.js +6 -0
  66. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.js.map +1 -0
  67. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  68. package/node_modules/@earendil-works/pi-ai/dist/providers/data/bai.json +1 -0
  69. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  70. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  71. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  72. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  73. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -1
  74. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  75. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  76. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  77. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  78. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  79. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  80. package/package.json +7 -7
  81. package/dist/bundle/chunks/bun-extension-importer-SW7XGNSG.js +0 -10
  82. package/dist/bundle/chunks/chunk-63UWBQCO.js +0 -8
  83. package/dist/bundle/chunks/chunk-AGXZF7RF.js +0 -2
  84. package/dist/bundle/chunks/cli-main-IAO3GSNA.js +0 -3
  85. package/dist/bundle/chunks/interactive-mode-YOXSSB5S.js +0 -2
  86. package/dist/bundle/chunks/rpc-mode-2IA6LPSI.js +0 -2
@@ -1,4 +1,4 @@
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{RpcClient,SessionManager,executeBashWithOperations,isTransportGoneError}from"./chunk-NBUMCMS4.js";import{SettingsManager}from"./chunk-4C7LNOHI.js";import{ensureHost}from"./chunk-2LSXWYT5.js";import{QUESTION_CAPABILITY,RENDERED_COMPONENTS_CAPABILITY}from"./chunk-U6Z6OBX4.js";import"./chunk-RA3P6BWS.js";import"./chunk-HSH674C6.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-VRAYXSST.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{randomUUID}from"node:crypto";import{rm}from"node:fs/promises";var HOST_CLIENT_CAPABILITIES=[RENDERED_COMPONENTS_CAPABILITY,QUESTION_CAPABILITY],INTERACTIVE_HOST_FALLBACK_WARNING="Warning: shared interactive host unavailable; continuing locally",INTERACTIVE_HOST_RECONNECTING_WARNING="Warning: shared interactive host connection lost; reconnecting";async function createInteractiveHostRuntime(localRuntime,options){let sessionPath=localRuntime.session.sessionFile;if(!sessionPath)return localRuntime;let startHost=options.ensureHost??(hostOptions=>ensureHost(hostOptions)),remoteSession,remoteRuntime,reconnecting,disconnectQueued=!1,disposed=!1,fallbackWarned=!1,reconnectWarningShown=!1,warnReconnect=cause=>{reconnectWarningShown||(reconnectWarningShown=!0,options.onWarning?.({type:"interactive_host_action_failed",message:INTERACTIVE_HOST_RECONNECTING_WARNING,cause}))},warnFallback=cause=>{fallbackWarned||(fallbackWarned=!0,options.onWarning?.({type:"interactive_host_fallback",message:INTERACTIVE_HOST_FALLBACK_WARNING,cause}))},scheduleReconnect=()=>{},client=new RpcClient({socketPath:options.socket,onDisconnect:()=>{disconnectQueued=!0,scheduleReconnect()}});scheduleReconnect=()=>{!remoteSession||reconnecting||disposed||remoteRuntime?.isFallback||(remoteRuntime?.enterReconnecting(),reconnecting=(async()=>{let cause;for(let attempt=0;attempt<3;attempt++){if(disposed)return;disconnectQueued=!1;try{if(await startHost({socket:options.socket,agentDir:options.agentDir}),disposed||(await client.start(),disposed)||(await client.openSession({sessionPath,cwd:localRuntime.cwd}),disposed)||(remoteRuntime&&await remoteRuntime.reRegisterClientInfo(),disposed)||(await remoteSession.refresh(),disposed))return;fallbackWarned=!1,reconnectWarningShown=!1,remoteRuntime?.enterConnected();return}catch(error){if(cause=error,await client.stop().catch(()=>{}),disposed)return}}disposed||(await remoteRuntime?.enterFallback(),warnFallback(cause))})().finally(()=>{reconnecting=void 0,disconnectQueued&&!disposed&&!remoteRuntime?.isFallback&&scheduleReconnect()}))};try{await startHost({socket:options.socket,agentDir:options.agentDir}),await client.start(),await client.setClientInfo(80,[...HOST_CLIENT_CAPABILITIES]);let startupEvents=[],stopBuffering=client.onEvent(event=>startupEvents.push(event)),opened=await client.openSession({sessionPath,cwd:localRuntime.cwd,provider:localRuntime.session.model?.provider,modelId:localRuntime.session.model?.id,thinkingLevel:localRuntime.session.thinkingLevel});return remoteSession=createRemoteSessionProxy(localRuntime.session,localRuntime.services.agentDir,client,opened.state,options.onWarning,cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},startupEvents.filter(event=>!("sessionId"in event)||event.sessionId===opened.sessionId)),stopBuffering(),opened.state.isBashRunning&&!opened.attached&&await client.abortBash().catch(()=>{}),opened.attached&&await remoteSession.refresh(),remoteRuntime=new RemoteInteractiveRuntime(localRuntime,remoteSession,client,{onTransportGone:cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},get reconnecting(){return reconnecting},dispose:()=>{disposed=!0}}),remoteRuntime}catch(cause){return await client.stop().catch(()=>{}),warnFallback(cause),localRuntime}}var RemoteInteractiveRuntime=class{#local;#remoteSession;#client;#lifecycle;#onTransportGone;#rebindSession;#beforeSessionInvalidate;#state="connected";#fallbackHandoff;get isReconnecting(){return this.#state==="reconnecting"}get isFallback(){return this.#state==="fallback"}constructor(local,remoteSession,client,lifecycle){this.#local=local,this.#remoteSession=remoteSession,this.#client=client,this.#lifecycle=lifecycle,this.#onTransportGone=lifecycle?.onTransportGone??(()=>{})}async#call(call){try{return await call()}catch(error){if(isTransportGoneError(error))return this.#onTransportGone(error),{cancelled:!0};throw error}}enterConnected(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="connected")}enterReconnecting(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="reconnecting")}async enterFallback(){if(this.#state==="disposed"||this.#state==="fallback")return;this.#state="fallback",this.#beforeSessionInvalidate?.();let rebind=this.#rebindSession?.();rebind&&(this.#fallbackHandoff=rebind.catch(error=>{this.#onTransportGone(error)}),await this.#fallbackHandoff)}get session(){return this.#state==="fallback"||this.#state==="disposed"?this.#local.session:this.#remoteSession.session}get services(){return this.#local.services}get cwd(){return this.session.sessionManager.getCwd()}get diagnostics(){return this.#local.diagnostics}get modelFallbackMessage(){return this.#local.modelFallbackMessage}get launchProfile(){return this.#local.launchProfile}setBeforeSessionInvalidate(callback){this.#beforeSessionInvalidate=callback,this.#local.setBeforeSessionInvalidate(callback)}setRebindSession(callback){this.#rebindSession=callback,this.#local.setRebindSession(callback),callback&&this.#state==="fallback"&&!this.#fallbackHandoff&&(this.#fallbackHandoff=callback().catch(error=>{this.#onTransportGone(error)}))}setHostUiHandler(callback){this.#remoteSession.setHostUiHandler(callback)}sendHostUiProgress(record){this.#client.sendExtensionUIProgress(record).catch(()=>{})}#clientInfoSent=!1;#lastClientWidth=80;setClientInfo(width){this.#lastClientWidth=width;let capabilities=this.#clientInfoSent?void 0:[...HOST_CLIENT_CAPABILITIES];this.#clientInfoSent=!0,this.#client.setClientInfo(width,capabilities).catch(()=>{})}async reRegisterClientInfo(){await this.#client.setClientInfo(this.#lastClientWidth,[...HOST_CLIENT_CAPABILITIES])}async dispose(){if(this.#state==="disposed")return;this.#state="disposed",this.#lifecycle?.dispose(),await this.#lifecycle?.reconnecting?.catch(()=>{}),await this.#fallbackHandoff?.catch(()=>{});let errors=[];for(let cleanup of[()=>this.#remoteSession.abortLocalBash(),()=>this.#client.closeSession(),()=>this.#client.stop(),()=>this.#local.dispose()])try{await cleanup()}catch(error){errors.push(error)}if(errors.length>0)throw errors[0]}async newSession(options){return this.#state==="fallback"?this.#local.newSession(options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.newSession(options?.parentSession));if(!result.cancelled){if(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),options?.setup){let capture=SessionManager.inMemory(this.#remoteSession.session.sessionManager.getCwd());await options.setup(capture);for(let entry of capture.getEntries())await this.#client.appendSessionEntry(entry);await this.#remoteSession.refresh()}await this.#rebindSession?.(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())}return result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async switchSession(sessionPath,options){return this.#state==="fallback"?this.#local.switchSession(sessionPath,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.switchSession(sessionPath,options?.cwdOverride===void 0?void 0:{cwdOverride:options.cwdOverride}));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),await this.#rebindSession?.(),options?.projectTrustContextFactory?.(this.#remoteSession.session.sessionManager.getCwd()),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async fork(entryId,options){return this.#state==="fallback"?this.#local.fork(entryId,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.fork(entryId,options));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),{cancelled:result.cancelled,selectedText:result.text}}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async importFromJsonl(inputPath,cwdOverride){return this.#state==="fallback"?this.#local.importFromJsonl(inputPath,cwdOverride):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.importJsonl(inputPath,cwdOverride));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind()),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async#refreshAndRebind(){await this.#remoteSession.refresh(),await this.#rebindSession?.()}};function createRemoteSessionProxy(local,agentDir,client,initialState,onWarning,onTransportGone,startupEvents=[]){let reportActionFailure=action=>error=>{isTransportGoneError(error)?onTransportGone?.(error):onWarning?.({type:"interactive_host_action_failed",message:`Warning: shared interactive host ${action} failed: ${error instanceof Error?error.message:String(error)}`,cause:error})},transportCall=async(action,call,cancelledValue)=>{try{return await call()}catch(error){if(!isTransportGoneError(error))throw error;return reportActionFailure(action)(error),cancelledValue}},state={...initialState},waitForBashCallbacks=async(promises,allowAbandonment)=>{if(promises.size===0)return!0;let settled=Promise.allSettled([...promises]).then(()=>!0),timeout,bounded=new Promise(resolve=>{timeout=setTimeout(resolve,allowAbandonment?100:5e3,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},executionNamespace=randomUUID(),cleanupRemoteBashOutput=async path=>{let cleanupTimeout;try{await Promise.race([client.cleanupBashOutput(path),new Promise((_,reject)=>{cleanupTimeout=setTimeout(()=>reject(new Error("RPC cleanup timed out")),1e3)})]);return}catch(transportError){try{await rm(path,{force:!0});return}catch(localError){onWarning?.({type:"interactive_host_action_failed",message:`Warning: failed to clean up shared bash output spill: ${localError instanceof Error?localError.message:String(localError)}`,cause:new AggregateError([transportError,localError])})}}finally{cleanupTimeout&&clearTimeout(cleanupTimeout)}},nextBashExecutionId=0,bashExecutions=new Map,hostUiHandler,pendingUiRequests=[],localBashAbortController,localBashRunning=!1,hostBashRunning=initialState.isBashRunning,nextQueuedInputOrder=Math.max(0,...initialState.ordered.map(item=>item.enqueueOrder)),sessionManager=local.sessionManager,settingsManager=SettingsManager.create(initialState.cwd,agentDir,{projectTrusted:initialState.projectTrusted}),updateBashState=()=>{state={...state,isBashRunning:localBashRunning||hostBashRunning}},remoteSessionManager=new Proxy({},{get(_target,property,_receiver){if(property==="appendLabelChange")return(entryId,label)=>{client.setLabel(entryId,label).catch(reportActionFailure("appendLabelChange"))};if(property==="getCwd")return()=>state.cwd;if(property==="getSessionName")return()=>state.sessionName;if(property==="getUsageTotals")return()=>state.usageTotals;let value=Reflect.get(sessionManager,property,sessionManager);return typeof value=="function"?value.bind(sessionManager):value}}),streamingAssistant,mirroredCurrentAssistantUsage=!1,localReplacementDepth=0,listeners=new Set,handleWireEvent=wireEvent=>{if(wireEvent.type==="extension_ui_request"){let request=wireEvent;hostUiHandler?Promise.resolve(hostUiHandler(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response")):pendingUiRequests.push(request);return}if(wireEvent.type==="session_replaced"){localReplacementDepth===0&&refresh().catch(reportActionFailure("session refresh after replacement"));return}if(wireEvent.type==="agent_settled"&&(state={...state,isStreaming:!1,retryAttempt:0}),wireEvent.type==="bash_start"&&(hostBashRunning=!0,updateBashState()),wireEvent.type==="bash_end"&&(hostBashRunning=!1,updateBashState()),wireEvent.type==="bash_execution_update"&&wireEvent.id){let execution=bashExecutions.get(wireEvent.id);if(execution?.chunk&&!execution.hasError)try{let callbackPromise=Promise.resolve(execution.chunk(wireEvent.delta)).catch(error=>{throw execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{})),error});execution.promises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>execution.promises.delete(callbackPromise))}catch(error){execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{}))}}if(wireEvent.type==="agent_start"&&(state={...state,isStreaming:!0}),wireEvent.type==="compaction_start"&&(state={...state,isCompacting:!0}),wireEvent.type==="compaction_end"&&(state={...state,isCompacting:!1}),wireEvent.type==="auto_retry_start"&&(state={...state,retryAttempt:wireEvent.attempt}),wireEvent.type==="auto_retry_end"&&(state={...state,retryAttempt:0}),wireEvent.type==="queue_update"&&(nextQueuedInputOrder=Math.max(nextQueuedInputOrder,...wireEvent.ordered.map(item=>item.enqueueOrder)),state={...state,steering:[...wireEvent.steering],followUp:[...wireEvent.followUp],ordered:[...wireEvent.ordered],pendingMessageCount:wireEvent.steering.length+wireEvent.followUp.length}),wireEvent.type==="model_changed"&&(state={...state,model:wireEvent.model,thinkingLevel:wireEvent.thinkingLevel}),wireEvent.type==="thinking_level_changed"&&(state={...state,thinkingLevel:wireEvent.level}),wireEvent.type==="service_tier_changed"&&(state={...state,serviceTier:wireEvent.tier,fastMode:wireEvent.fastMode}),wireEvent.type==="session_settings_changed"&&(state={...state,steeringMode:wireEvent.steeringMode,followUpMode:wireEvent.followUpMode,autoCompactionEnabled:wireEvent.autoCompactionEnabled}),wireEvent.type==="entry_appended")try{sessionManager.appendEntry(wireEvent.entry),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}if(wireEvent.type==="session_info_changed"&&(state={...state,sessionName:wireEvent.name}),wireEvent.type==="message_start"&&(wireEvent.message.role==="assistant"&&(streamingAssistant=structuredClone(wireEvent.message),mirroredCurrentAssistantUsage=!1),local.agent.state.messages.push(structuredClone(wireEvent.message))),wireEvent.type==="message_end"){if(wireEvent.message.role==="assistant"){streamingAssistant=structuredClone(wireEvent.message);let usage=wireEvent.message.usage;if(usage&&!mirroredCurrentAssistantUsage){mirroredCurrentAssistantUsage=!0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite,contextWindow=state.model?.contextWindow??0,contextTokens=usage.input+usage.cacheRead+usage.cacheWrite;state={...state,contextUsage:contextWindow>0?{tokens:contextTokens,contextWindow,percent:contextTokens/contextWindow*100}:void 0,usageTotals:{...state.usageTotals,input:state.usageTotals.input+usage.input,output:state.usageTotals.output+usage.output,cacheRead:state.usageTotals.cacheRead+usage.cacheRead,cacheWrite:state.usageTotals.cacheWrite+usage.cacheWrite,cost:state.usageTotals.cost+(usage.cost?.total??0),latestCacheHitRate:latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}}}}let messages=local.agent.state.messages;messages.at(-1)?.role===wireEvent.message.role&&(messages[messages.length-1]=structuredClone(wireEvent.message))}if(wireEvent.type==="compaction_end"&&wireEvent.accepted&&!wireEvent.aborted)try{local.sessionManager.reloadFromDisk?.(),sessionManager!==local.sessionManager&&sessionManager.reloadFromDisk?.(),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}let event=hydrateMessageUpdate(wireEvent,streamingAssistant);for(let listener of listeners)listener(event)};client.onEvent(handleWireEvent);for(let event of startupEvents)handleWireEvent(event);let performRefresh=async()=>{let idsAtRefreshStart=new Set(sessionManager.getEntries().map(entry=>entry.id)),nextState=await transportCall("refresh",()=>client.getState());if(!nextState)return;state={...nextState},nextQueuedInputOrder=Math.max(0,...nextState.ordered.map(item=>item.enqueueOrder));let messages;if(settingsManager=SettingsManager.create(nextState.cwd,agentDir,{projectTrusted:nextState.projectTrusted}),nextState.sessionFile){sessionManager.getSessionFile()===nextState.sessionFile?sessionManager.reloadFromDisk?.():sessionManager=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);let authoritative=nextState.entries;if(authoritative?.length){let mirror=sessionManager.getEntries();if(!(mirror.length===authoritative.length&&mirror.every((entry,index)=>entry.id===authoritative[index]?.id))){let rebuilt=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);for(let entry of authoritative)rebuilt.appendEntry(entry);let authoritativeIds=new Set(authoritative.map(entry=>entry.id));for(let entry of mirror)!idsAtRefreshStart.has(entry.id)&&!authoritativeIds.has(entry.id)&&rebuilt.appendEntry(entry);sessionManager=rebuilt}}messages=sessionManager.buildSessionContext().messages}else messages=await transportCall("refresh",()=>client.getMessages(),[]);local.agent.state.messages.splice(0,local.agent.state.messages.length,...structuredClone(messages)),streamingAssistant=void 0},refreshChain=Promise.resolve(),refresh=()=>{let next=refreshChain.then(performRefresh,performRefresh);return refreshChain=next.then(()=>{},()=>{}),next};return{session:new Proxy(local,{get(target,property,receiver){if(property==="prompt")return async(message,options)=>{try{await client.prompt(message,{...options?.images?{images:options.images}:{},...options?.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options?.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options?.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options?.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{},...options?.promptDisposition?{promptDisposition:options.promptDisposition}:{},...options?.preflightResult?{preflightResult:options.preflightResult}:{}})}catch(error){if(!isTransportGoneError(error))throw error;reportActionFailure("prompt")(error)}};if(property==="abort")return()=>client.abort();if(property==="abortCompaction")return()=>{client.abortCompaction().catch(reportActionFailure("abortCompaction"))};if(property==="steer")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,steering:[...state.steering,message],ordered:[...state.ordered,{text:message,mode:"steer",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("steer",()=>client.steer(message,images,{...recovery,enqueueOrder}))};if(property==="followUp")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,followUp:[...state.followUp,message],ordered:[...state.ordered,{text:message,mode:"followUp",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("followUp",()=>client.followUp(message,images,{...recovery,enqueueOrder}))};if(property==="waitForIdle")return()=>client.waitForIdle();if(property==="getLastAssistantText")return()=>target.getLastAssistantText();if(property==="setModel"||property==="setSessionModel")return async model=>{let next=await transportCall("setModel",()=>client.setModel(model.provider,model.id),void 0);return next?{systemPromptName:next.systemPromptName,model:next}:void 0};if(property==="setSessionThinkingLevel")return level=>{client.setThinkingLevel(level,{scope:"turn"}).catch(reportActionFailure("setSessionThinkingLevel"))};if(property==="setSessionFastMode")return enabled=>{client.setFastMode(enabled).catch(reportActionFailure("setSessionFastMode"))};if(property==="abortRetry")return()=>{client.abortRetry().catch(reportActionFailure("abortRetry"))};if(property==="setAutoRetryEnabled")return enabled=>{client.setAutoRetry(enabled).catch(reportActionFailure("setAutoRetryEnabled"))};if(property==="reserveQueuedInputOrder")return()=>++nextQueuedInputOrder;if(property==="setFavoriteModels")return models=>{state={...state,favoriteModels:[...models]},client.setFavoriteModels(models).catch(reportActionFailure("setFavoriteModels"))};if(property==="setScopedModels")return models=>{state={...state,scopedModels:[...models]},client.setScopedModels(models).catch(reportActionFailure("setScopedModels"))};if(property==="cycleModel")return direction=>transportCall("cycleModel",()=>client.cycleModel(direction),void 0);if(property==="setThinkingLevel")return level=>{client.setThinkingLevel(level).catch(reportActionFailure("setThinkingLevel"))};if(property==="cycleThinkingLevel")return()=>transportCall("cycleThinkingLevel",()=>client.cycleThinkingLevel(),void 0).then(result=>result?.level);if(property==="getAvailableThinkingLevels")return()=>transportCall("getAvailableThinkingLevels",()=>client.getAvailableThinkingLevels(),[]);if(property==="setSteeringMode")return mode=>{client.setSteeringMode(mode).catch(reportActionFailure("setSteeringMode"))};if(property==="setFollowUpMode")return mode=>{client.setFollowUpMode(mode).catch(reportActionFailure("setFollowUpMode"))};if(property==="compact")return instructions=>transportCall("compact",()=>client.compact(instructions));if(property==="setAutoCompactionEnabled")return enabled=>{client.setAutoCompaction(enabled).catch(reportActionFailure("setAutoCompaction"))};if(property==="executeBash")return async(command,onChunk,options)=>{if(options?.operations&&typeof options.operations.exec=="function"){let abortController=new AbortController;localBashAbortController=abortController,localBashRunning=!0,updateBashState();let sessionAtStart=state.sessionId,prefix=settingsManager.getShellCommandPrefix(),resolvedCommand=prefix?`${prefix}
2
+ import{RpcClient,SessionManager,executeBashWithOperations,isTransportGoneError}from"./chunk-VRDDXZF3.js";import{SettingsManager}from"./chunk-PLZK7ABD.js";import{ensureHost}from"./chunk-2LSXWYT5.js";import{QUESTION_CAPABILITY,RENDERED_COMPONENTS_CAPABILITY}from"./chunk-U6Z6OBX4.js";import"./chunk-RA3P6BWS.js";import"./chunk-HSH674C6.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{randomUUID}from"node:crypto";import{rm}from"node:fs/promises";var HOST_CLIENT_CAPABILITIES=[RENDERED_COMPONENTS_CAPABILITY,QUESTION_CAPABILITY],INTERACTIVE_HOST_FALLBACK_WARNING="Warning: shared interactive host unavailable; continuing locally",INTERACTIVE_HOST_RECONNECTING_WARNING="Warning: shared interactive host connection lost; reconnecting";async function createInteractiveHostRuntime(localRuntime,options){let sessionPath=localRuntime.session.sessionFile;if(!sessionPath)return localRuntime;let startHost=options.ensureHost??(hostOptions=>ensureHost(hostOptions)),remoteSession,remoteRuntime,reconnecting,disconnectQueued=!1,disposed=!1,fallbackWarned=!1,reconnectWarningShown=!1,warnReconnect=cause=>{reconnectWarningShown||(reconnectWarningShown=!0,options.onWarning?.({type:"interactive_host_action_failed",message:INTERACTIVE_HOST_RECONNECTING_WARNING,cause}))},warnFallback=cause=>{fallbackWarned||(fallbackWarned=!0,options.onWarning?.({type:"interactive_host_fallback",message:INTERACTIVE_HOST_FALLBACK_WARNING,cause}))},scheduleReconnect=()=>{},client=new RpcClient({socketPath:options.socket,onDisconnect:()=>{disconnectQueued=!0,scheduleReconnect()}});scheduleReconnect=()=>{!remoteSession||reconnecting||disposed||remoteRuntime?.isFallback||(remoteRuntime?.enterReconnecting(),reconnecting=(async()=>{let cause;for(let attempt=0;attempt<3;attempt++){if(disposed)return;disconnectQueued=!1;try{if(await startHost({socket:options.socket,agentDir:options.agentDir}),disposed||(await client.start(),disposed)||(await client.openSession({sessionPath,cwd:localRuntime.cwd}),disposed)||(remoteRuntime&&await remoteRuntime.reRegisterClientInfo(),disposed)||(await remoteSession.refresh(),disposed))return;fallbackWarned=!1,reconnectWarningShown=!1,remoteRuntime?.enterConnected();return}catch(error){if(cause=error,await client.stop().catch(()=>{}),disposed)return}}disposed||(await remoteRuntime?.enterFallback(),warnFallback(cause))})().finally(()=>{reconnecting=void 0,disconnectQueued&&!disposed&&!remoteRuntime?.isFallback&&scheduleReconnect()}))};try{await startHost({socket:options.socket,agentDir:options.agentDir}),await client.start(),await client.setClientInfo(80,[...HOST_CLIENT_CAPABILITIES]);let startupEvents=[],stopBuffering=client.onEvent(event=>startupEvents.push(event)),opened=await client.openSession({sessionPath,cwd:localRuntime.cwd,provider:localRuntime.session.model?.provider,modelId:localRuntime.session.model?.id,thinkingLevel:localRuntime.session.thinkingLevel});return remoteSession=createRemoteSessionProxy(localRuntime.session,localRuntime.services.agentDir,client,opened.state,options.onWarning,cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},startupEvents.filter(event=>!("sessionId"in event)||event.sessionId===opened.sessionId)),stopBuffering(),opened.state.isBashRunning&&!opened.attached&&await client.abortBash().catch(()=>{}),opened.attached&&await remoteSession.refresh(),remoteRuntime=new RemoteInteractiveRuntime(localRuntime,remoteSession,client,{onTransportGone:cause=>{remoteRuntime?.isReconnecting?warnReconnect(cause):warnFallback(cause)},get reconnecting(){return reconnecting},dispose:()=>{disposed=!0}}),remoteRuntime}catch(cause){return await client.stop().catch(()=>{}),warnFallback(cause),localRuntime}}var RemoteInteractiveRuntime=class{#local;#remoteSession;#client;#lifecycle;#onTransportGone;#rebindSession;#beforeSessionInvalidate;#state="connected";#fallbackHandoff;get isReconnecting(){return this.#state==="reconnecting"}get isFallback(){return this.#state==="fallback"}constructor(local,remoteSession,client,lifecycle){this.#local=local,this.#remoteSession=remoteSession,this.#client=client,this.#lifecycle=lifecycle,this.#onTransportGone=lifecycle?.onTransportGone??(()=>{})}async#call(call){try{return await call()}catch(error){if(isTransportGoneError(error))return this.#onTransportGone(error),{cancelled:!0};throw error}}enterConnected(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="connected")}enterReconnecting(){this.#state!=="disposed"&&this.#state!=="fallback"&&(this.#state="reconnecting")}async enterFallback(){if(this.#state==="disposed"||this.#state==="fallback")return;this.#state="fallback",this.#beforeSessionInvalidate?.();let rebind=this.#rebindSession?.();rebind&&(this.#fallbackHandoff=rebind.catch(error=>{this.#onTransportGone(error)}),await this.#fallbackHandoff)}get session(){return this.#state==="fallback"||this.#state==="disposed"?this.#local.session:this.#remoteSession.session}get services(){return this.#local.services}get cwd(){return this.session.sessionManager.getCwd()}get diagnostics(){return this.#local.diagnostics}get modelFallbackMessage(){return this.#local.modelFallbackMessage}get launchProfile(){return this.#local.launchProfile}setBeforeSessionInvalidate(callback){this.#beforeSessionInvalidate=callback,this.#local.setBeforeSessionInvalidate(callback)}setRebindSession(callback){this.#rebindSession=callback,this.#local.setRebindSession(callback),callback&&this.#state==="fallback"&&!this.#fallbackHandoff&&(this.#fallbackHandoff=callback().catch(error=>{this.#onTransportGone(error)}))}setHostUiHandler(callback){this.#remoteSession.setHostUiHandler(callback)}sendHostUiProgress(record){this.#client.sendExtensionUIProgress(record).catch(()=>{})}#clientInfoSent=!1;#lastClientWidth=80;setClientInfo(width){this.#lastClientWidth=width;let capabilities=this.#clientInfoSent?void 0:[...HOST_CLIENT_CAPABILITIES];this.#clientInfoSent=!0,this.#client.setClientInfo(width,capabilities).catch(()=>{})}async reRegisterClientInfo(){await this.#client.setClientInfo(this.#lastClientWidth,[...HOST_CLIENT_CAPABILITIES])}async dispose(){if(this.#state==="disposed")return;this.#state="disposed",this.#lifecycle?.dispose(),await this.#lifecycle?.reconnecting?.catch(()=>{}),await this.#fallbackHandoff?.catch(()=>{});let errors=[];for(let cleanup of[()=>this.#remoteSession.abortLocalBash(),()=>this.#client.closeSession(),()=>this.#client.stop(),()=>this.#local.dispose()])try{await cleanup()}catch(error){errors.push(error)}if(errors.length>0)throw errors[0]}async newSession(options){return this.#state==="fallback"?this.#local.newSession(options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.newSession(options?.parentSession));if(!result.cancelled){if(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),options?.setup){let capture=SessionManager.inMemory(this.#remoteSession.session.sessionManager.getCwd());await options.setup(capture);for(let entry of capture.getEntries())await this.#client.appendSessionEntry(entry);await this.#remoteSession.refresh()}await this.#rebindSession?.(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())}return result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async switchSession(sessionPath,options){return this.#state==="fallback"?this.#local.switchSession(sessionPath,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.switchSession(sessionPath,options?.cwdOverride===void 0?void 0:{cwdOverride:options.cwdOverride}));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#remoteSession.refresh(),await this.#rebindSession?.(),options?.projectTrustContextFactory?.(this.#remoteSession.session.sessionManager.getCwd()),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async fork(entryId,options){return this.#state==="fallback"?this.#local.fork(entryId,options):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.fork(entryId,options));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind(),options?.withSession&&await options.withSession(this.#remoteSession.createReplacedSessionContext())),{cancelled:result.cancelled,selectedText:result.text}}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async importFromJsonl(inputPath,cwdOverride){return this.#state==="fallback"?this.#local.importFromJsonl(inputPath,cwdOverride):this.#remoteSession.aroundLocalReplacement(async()=>{let result=await this.#call(()=>this.#client.importJsonl(inputPath,cwdOverride));return result.cancelled||(this.#beforeSessionInvalidate?.(),this.#remoteSession.abortLocalBash(),await this.#refreshAndRebind()),result}).catch(error=>{if(isTransportGoneError(error))return{cancelled:!0};throw error})}async#refreshAndRebind(){await this.#remoteSession.refresh(),await this.#rebindSession?.()}};function createRemoteSessionProxy(local,agentDir,client,initialState,onWarning,onTransportGone,startupEvents=[]){let reportActionFailure=action=>error=>{isTransportGoneError(error)?onTransportGone?.(error):onWarning?.({type:"interactive_host_action_failed",message:`Warning: shared interactive host ${action} failed: ${error instanceof Error?error.message:String(error)}`,cause:error})},transportCall=async(action,call,cancelledValue)=>{try{return await call()}catch(error){if(!isTransportGoneError(error))throw error;return reportActionFailure(action)(error),cancelledValue}},state={...initialState},waitForBashCallbacks=async(promises,allowAbandonment)=>{if(promises.size===0)return!0;let settled=Promise.allSettled([...promises]).then(()=>!0),timeout,bounded=new Promise(resolve=>{timeout=setTimeout(resolve,allowAbandonment?100:5e3,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},executionNamespace=randomUUID(),cleanupRemoteBashOutput=async path=>{let cleanupTimeout;try{await Promise.race([client.cleanupBashOutput(path),new Promise((_,reject)=>{cleanupTimeout=setTimeout(()=>reject(new Error("RPC cleanup timed out")),1e3)})]);return}catch(transportError){try{await rm(path,{force:!0});return}catch(localError){onWarning?.({type:"interactive_host_action_failed",message:`Warning: failed to clean up shared bash output spill: ${localError instanceof Error?localError.message:String(localError)}`,cause:new AggregateError([transportError,localError])})}}finally{cleanupTimeout&&clearTimeout(cleanupTimeout)}},nextBashExecutionId=0,bashExecutions=new Map,hostUiHandler,pendingUiRequests=[],localBashAbortController,localBashRunning=!1,hostBashRunning=initialState.isBashRunning,nextQueuedInputOrder=Math.max(0,...initialState.ordered.map(item=>item.enqueueOrder)),sessionManager=local.sessionManager,settingsManager=SettingsManager.create(initialState.cwd,agentDir,{projectTrusted:initialState.projectTrusted}),updateBashState=()=>{state={...state,isBashRunning:localBashRunning||hostBashRunning}},remoteSessionManager=new Proxy({},{get(_target,property,_receiver){if(property==="appendLabelChange")return(entryId,label)=>{client.setLabel(entryId,label).catch(reportActionFailure("appendLabelChange"))};if(property==="getCwd")return()=>state.cwd;if(property==="getSessionName")return()=>state.sessionName;if(property==="getUsageTotals")return()=>state.usageTotals;let value=Reflect.get(sessionManager,property,sessionManager);return typeof value=="function"?value.bind(sessionManager):value}}),streamingAssistant,mirroredCurrentAssistantUsage=!1,localReplacementDepth=0,listeners=new Set,handleWireEvent=wireEvent=>{if(wireEvent.type==="extension_ui_request"){let request=wireEvent;hostUiHandler?Promise.resolve(hostUiHandler(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response")):pendingUiRequests.push(request);return}if(wireEvent.type==="session_replaced"){localReplacementDepth===0&&refresh().catch(reportActionFailure("session refresh after replacement"));return}if(wireEvent.type==="agent_settled"&&(state={...state,isStreaming:!1,retryAttempt:0}),wireEvent.type==="bash_start"&&(hostBashRunning=!0,updateBashState()),wireEvent.type==="bash_end"&&(hostBashRunning=!1,updateBashState()),wireEvent.type==="bash_execution_update"&&wireEvent.id){let execution=bashExecutions.get(wireEvent.id);if(execution?.chunk&&!execution.hasError)try{let callbackPromise=Promise.resolve(execution.chunk(wireEvent.delta)).catch(error=>{throw execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{})),error});execution.promises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>execution.promises.delete(callbackPromise))}catch(error){execution.hasError||(execution.error=error,execution.hasError=!0,client.abortBash().catch(()=>{}))}}if(wireEvent.type==="agent_start"&&(state={...state,isStreaming:!0}),wireEvent.type==="compaction_start"&&(state={...state,isCompacting:!0}),wireEvent.type==="compaction_end"&&(state={...state,isCompacting:!1}),wireEvent.type==="auto_retry_start"&&(state={...state,retryAttempt:wireEvent.attempt}),wireEvent.type==="auto_retry_end"&&(state={...state,retryAttempt:0}),wireEvent.type==="queue_update"&&(nextQueuedInputOrder=Math.max(nextQueuedInputOrder,...wireEvent.ordered.map(item=>item.enqueueOrder)),state={...state,steering:[...wireEvent.steering],followUp:[...wireEvent.followUp],ordered:[...wireEvent.ordered],pendingMessageCount:wireEvent.steering.length+wireEvent.followUp.length}),wireEvent.type==="model_changed"&&(state={...state,model:wireEvent.model,thinkingLevel:wireEvent.thinkingLevel}),wireEvent.type==="thinking_level_changed"&&(state={...state,thinkingLevel:wireEvent.level}),wireEvent.type==="service_tier_changed"&&(state={...state,serviceTier:wireEvent.tier,fastMode:wireEvent.fastMode}),wireEvent.type==="session_settings_changed"&&(state={...state,steeringMode:wireEvent.steeringMode,followUpMode:wireEvent.followUpMode,autoCompactionEnabled:wireEvent.autoCompactionEnabled}),wireEvent.type==="entry_appended")try{sessionManager.appendEntry(wireEvent.entry),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}if(wireEvent.type==="session_info_changed"&&(state={...state,sessionName:wireEvent.name}),wireEvent.type==="message_start"&&(wireEvent.message.role==="assistant"&&(streamingAssistant=structuredClone(wireEvent.message),mirroredCurrentAssistantUsage=!1),local.agent.state.messages.push(structuredClone(wireEvent.message))),wireEvent.type==="message_end"){if(wireEvent.message.role==="assistant"){streamingAssistant=structuredClone(wireEvent.message);let usage=wireEvent.message.usage;if(usage&&!mirroredCurrentAssistantUsage){mirroredCurrentAssistantUsage=!0;let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite,contextWindow=state.model?.contextWindow??0,contextTokens=usage.input+usage.cacheRead+usage.cacheWrite;state={...state,contextUsage:contextWindow>0?{tokens:contextTokens,contextWindow,percent:contextTokens/contextWindow*100}:void 0,usageTotals:{...state.usageTotals,input:state.usageTotals.input+usage.input,output:state.usageTotals.output+usage.output,cacheRead:state.usageTotals.cacheRead+usage.cacheRead,cacheWrite:state.usageTotals.cacheWrite+usage.cacheWrite,cost:state.usageTotals.cost+(usage.cost?.total??0),latestCacheHitRate:latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}}}}let messages=local.agent.state.messages;messages.at(-1)?.role===wireEvent.message.role&&(messages[messages.length-1]=structuredClone(wireEvent.message))}if(wireEvent.type==="compaction_end"&&wireEvent.accepted&&!wireEvent.aborted)try{local.sessionManager.reloadFromDisk?.(),sessionManager!==local.sessionManager&&sessionManager.reloadFromDisk?.(),local.agent.state.messages=sessionManager.buildSessionContext().messages}catch{}let event=hydrateMessageUpdate(wireEvent,streamingAssistant);for(let listener of listeners)listener(event)};client.onEvent(handleWireEvent);for(let event of startupEvents)handleWireEvent(event);let performRefresh=async()=>{let idsAtRefreshStart=new Set(sessionManager.getEntries().map(entry=>entry.id)),nextState=await transportCall("refresh",()=>client.getState());if(!nextState)return;state={...nextState},nextQueuedInputOrder=Math.max(0,...nextState.ordered.map(item=>item.enqueueOrder));let messages;if(settingsManager=SettingsManager.create(nextState.cwd,agentDir,{projectTrusted:nextState.projectTrusted}),nextState.sessionFile){sessionManager.getSessionFile()===nextState.sessionFile?sessionManager.reloadFromDisk?.():sessionManager=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);let authoritative=nextState.entries;if(authoritative?.length){let mirror=sessionManager.getEntries();if(!(mirror.length===authoritative.length&&mirror.every((entry,index)=>entry.id===authoritative[index]?.id))){let rebuilt=SessionManager.open(nextState.sessionFile,void 0,nextState.cwd);for(let entry of authoritative)rebuilt.appendEntry(entry);let authoritativeIds=new Set(authoritative.map(entry=>entry.id));for(let entry of mirror)!idsAtRefreshStart.has(entry.id)&&!authoritativeIds.has(entry.id)&&rebuilt.appendEntry(entry);sessionManager=rebuilt}}messages=sessionManager.buildSessionContext().messages}else messages=await transportCall("refresh",()=>client.getMessages(),[]);local.agent.state.messages.splice(0,local.agent.state.messages.length,...structuredClone(messages)),streamingAssistant=void 0},refreshChain=Promise.resolve(),refresh=()=>{let next=refreshChain.then(performRefresh,performRefresh);return refreshChain=next.then(()=>{},()=>{}),next};return{session:new Proxy(local,{get(target,property,receiver){if(property==="prompt")return async(message,options)=>{try{await client.prompt(message,{...options?.images?{images:options.images}:{},...options?.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options?.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options?.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options?.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{},...options?.promptDisposition?{promptDisposition:options.promptDisposition}:{},...options?.preflightResult?{preflightResult:options.preflightResult}:{}})}catch(error){if(!isTransportGoneError(error))throw error;reportActionFailure("prompt")(error)}};if(property==="abort")return()=>client.abort();if(property==="abortCompaction")return()=>{client.abortCompaction().catch(reportActionFailure("abortCompaction"))};if(property==="steer")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,steering:[...state.steering,message],ordered:[...state.ordered,{text:message,mode:"steer",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("steer",()=>client.steer(message,images,{...recovery,enqueueOrder}))};if(property==="followUp")return(message,images,recovery)=>{let enqueueOrder=recovery?.enqueueOrder??Math.max(0,...state.ordered.map(item=>item.enqueueOrder))+1;return state={...state,followUp:[...state.followUp,message],ordered:[...state.ordered,{text:message,mode:"followUp",enqueueOrder}],pendingMessageCount:state.pendingMessageCount+1},transportCall("followUp",()=>client.followUp(message,images,{...recovery,enqueueOrder}))};if(property==="waitForIdle")return()=>client.waitForIdle();if(property==="getLastAssistantText")return()=>target.getLastAssistantText();if(property==="setModel"||property==="setSessionModel")return async model=>{let next=await transportCall("setModel",()=>client.setModel(model.provider,model.id),void 0);return next?{systemPromptName:next.systemPromptName,model:next}:void 0};if(property==="setSessionThinkingLevel")return level=>{client.setThinkingLevel(level,{scope:"turn"}).catch(reportActionFailure("setSessionThinkingLevel"))};if(property==="setSessionFastMode")return enabled=>{client.setFastMode(enabled).catch(reportActionFailure("setSessionFastMode"))};if(property==="abortRetry")return()=>{client.abortRetry().catch(reportActionFailure("abortRetry"))};if(property==="setAutoRetryEnabled")return enabled=>{client.setAutoRetry(enabled).catch(reportActionFailure("setAutoRetryEnabled"))};if(property==="reserveQueuedInputOrder")return()=>++nextQueuedInputOrder;if(property==="setFavoriteModels")return models=>{state={...state,favoriteModels:[...models]},client.setFavoriteModels(models).catch(reportActionFailure("setFavoriteModels"))};if(property==="setScopedModels")return models=>{state={...state,scopedModels:[...models]},client.setScopedModels(models).catch(reportActionFailure("setScopedModels"))};if(property==="cycleModel")return direction=>transportCall("cycleModel",()=>client.cycleModel(direction),void 0);if(property==="setThinkingLevel")return level=>{client.setThinkingLevel(level).catch(reportActionFailure("setThinkingLevel"))};if(property==="cycleThinkingLevel")return()=>transportCall("cycleThinkingLevel",()=>client.cycleThinkingLevel(),void 0).then(result=>result?.level);if(property==="getAvailableThinkingLevels")return()=>transportCall("getAvailableThinkingLevels",()=>client.getAvailableThinkingLevels(),[]);if(property==="setSteeringMode")return mode=>{client.setSteeringMode(mode).catch(reportActionFailure("setSteeringMode"))};if(property==="setFollowUpMode")return mode=>{client.setFollowUpMode(mode).catch(reportActionFailure("setFollowUpMode"))};if(property==="compact")return instructions=>transportCall("compact",()=>client.compact(instructions));if(property==="setAutoCompactionEnabled")return enabled=>{client.setAutoCompaction(enabled).catch(reportActionFailure("setAutoCompaction"))};if(property==="executeBash")return async(command,onChunk,options)=>{if(options?.operations&&typeof options.operations.exec=="function"){let abortController=new AbortController;localBashAbortController=abortController,localBashRunning=!0,updateBashState();let sessionAtStart=state.sessionId,prefix=settingsManager.getShellCommandPrefix(),resolvedCommand=prefix?`${prefix}
3
3
  ${command}`:command;try{let result=await executeBashWithOperations(resolvedCommand,state.cwd,options.operations,{onChunk,signal:abortController.signal});return state.sessionId===sessionAtStart&&await transportCall("recordBashResult",()=>client.recordBashResult(command,result,options.excludeFromContext)),result}finally{localBashAbortController=void 0,localBashRunning=!1,updateBashState()}}let executionId=`bash-${executionNamespace}-${++nextBashExecutionId}`,execution={chunk:onChunk,promises:new Set,error:void 0,hasError:!1};bashExecutions.set(executionId,execution);try{let result=await transportCall("bash",()=>client.bash(command,{excludeFromContext:options?.excludeFromContext,executionId,operations:options?.operations}),{output:"",exitCode:void 0,cancelled:!0,truncated:!1});if(!await waitForBashCallbacks(execution.promises,!1))throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),new Error("Bash output callback did not settle within 5000ms");if(execution.hasError)throw result.fullOutputPath&&await cleanupRemoteBashOutput(result.fullOutputPath),execution.error;return result}finally{bashExecutions.delete(executionId)}};if(property==="abortBash")return()=>{localBashAbortController?localBashAbortController.abort():client.abortBash().catch(reportActionFailure("abortBash"))};if(property==="getContextUsage")return()=>state.contextUsage;if(property==="getSessionStats")return()=>transportCall("getSessionStats",()=>client.getSessionStats(),local.getSessionStats());if(property==="exportToHtml")return(outputPath,options)=>transportCall("exportToHtml",()=>client.exportHtml(outputPath,options?.themeName)).then(result=>result?.path);if(property==="setSessionName")return name=>client.setSessionName(name).catch(reportActionFailure("setSessionName"));if(property==="navigateTree")return async(targetId,options)=>{let result=await transportCall("navigateTree",()=>client.navigateTree(targetId,options),{cancelled:!0});return result.cancelled||await refresh(),result};if(property==="editAssistantMessage")return async(entryId,text,options)=>{let result=await client.editAssistantMessage(entryId,text,{expectedLeafId:options?.expectedLeafId,summarize:options?.summarize,customInstructions:options?.customInstructions});return result.outcome==="unchanged"?{cancelled:!1,unchanged:!0}:result.outcome==="cancelled"?{cancelled:!0,aborted:result.aborted}:(await refresh(),{cancelled:!1,entryId:result.entry.id})};if(property==="getUserMessagesForForking")return()=>transportCall("getUserMessagesForForking",()=>client.getForkMessages(),[]);if(property==="subscribe")return listener=>{listeners.add(listener);let localUnsubscribe=target.subscribe(listener);return()=>{listeners.delete(listener),localUnsubscribe()}};if(property==="isStreaming")return state.isStreaming;if(property==="isIdle")return!state.isStreaming;if(property==="isCompacting")return state.isCompacting;if(property==="pendingMessageCount")return state.pendingMessageCount;if(property==="getSteeringMessages")return()=>state.steering;if(property==="getFollowUpMessages")return()=>state.followUp;if(property==="clearQueue")return options=>{let result={steering:[...state.steering],followUp:[...state.followUp],ordered:[...state.ordered]};return Object.defineProperty(result,"ordered",{value:result.ordered,enumerable:!1}),client.clearQueue(options).catch(reportActionFailure("clearQueue")),result};if(property==="abortBranchSummary")return()=>{client.abortBranchSummary().catch(reportActionFailure("abortBranchSummary"))};if(property==="recordBashResult")return(command,result,options)=>{client.recordBashResult(command,result,options?.excludeFromContext).catch(reportActionFailure("recordBashResult"))};if(property!=="set_label"){if(property==="retryAttempt")return state.retryAttempt;if(property==="isBashRunning")return state.isBashRunning;if(property==="reload")return _options=>transportCall("reload",()=>client.reload(),{cancelled:!0});if(property==="checkReloadVeto")return()=>transportCall("checkReloadVeto",()=>client.checkReloadVeto(),{cancelled:!0});if(property==="exportToJsonl")return outputPath=>transportCall("exportToJsonl",()=>client.exportJsonl(outputPath)).then(result=>result?.path);if(property==="state"){let localState=target.state;return{...localState,model:state.model??localState.model,thinkingLevel:state.thinkingLevel,isStreaming:state.isStreaming,isCompacting:state.isCompacting}}return property==="sessionFile"?state.sessionFile:property==="sessionId"?state.sessionId:property==="sessionName"?state.sessionName:property==="serviceTier"?state.serviceTier:property==="steeringMode"?state.steeringMode:property==="followUpMode"?state.followUpMode:property==="autoCompactionEnabled"?state.autoCompactionEnabled:property==="isFastModeActive"?()=>state.fastMode:property==="sessionManager"?remoteSessionManager:property==="settingsManager"?settingsManager:property==="messages"?target.messages:property==="favoriteModels"?state.favoriteModels:property==="scopedModels"?state.scopedModels:property==="model"?state.model??target.model:property==="thinkingLevel"?state.thinkingLevel:Reflect.get(target,property,receiver)}}}),setHostUiHandler:callback=>{if(hostUiHandler=callback,callback)for(let request of pendingUiRequests.splice(0))Promise.resolve(callback(request)).then(response=>response&&client.sendExtensionUIResponse(response)).catch(reportActionFailure("host UI response"))},refresh,aroundLocalReplacement:async body=>{localReplacementDepth++;try{return await body()}finally{localReplacementDepth--}},abortLocalBash:()=>localBashAbortController?.abort(),createReplacedSessionContext:()=>{let context=local.createReplacedSessionContext();return Object.defineProperty(context,"cwd",{value:state.cwd}),Object.defineProperty(context,"sessionManager",{value:remoteSessionManager}),context.sendMessage=(message,options)=>transportCall("sendMessage",()=>client.sendCustomMessage(message,{triggerTurn:options?.triggerTurn,deliverAs:options?.deliverAs})),context.sendUserMessage=(content,options)=>{if(typeof content=="string")return transportCall("sendUserMessage",()=>client.prompt(content,{streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}));let text=content.filter(part=>part.type==="text").map(part=>part.text).join(`
4
4
  `),images=content.filter(part=>part.type==="image");return transportCall("sendUserMessage",()=>client.prompt(text,{images,streamingBehavior:options?.deliverAs,expandPromptTemplates:options?.expandPromptTemplates}))},context}}}function hydrateMessageUpdate(event,streamingAssistant){if(event.type!=="message_update"||!streamingAssistant)return event;let update=event.assistantMessageEvent;if(update.type!=="text_delta"&&update.type!=="thinking_delta"&&update.type!=="toolcall_delta")return event;let content=streamingAssistant.content[update.contentIndex];if(update.type==="text_delta"&&content?.type==="text"&&(content.text+=update.delta),update.type==="thinking_delta"&&content?.type==="thinking"&&(content.thinking+=update.delta),update.type==="toolcall_delta"&&content?.type==="toolCall"){let raw=JSON.stringify(content.arguments)+update.delta;try{let parsed=JSON.parse(raw);typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)&&(content.arguments=parsed)}catch{}}return streamingAssistant.usage=event.usage,{type:"message_update",message:structuredClone(streamingAssistant),assistantMessageEvent:{...update,partial:structuredClone(streamingAssistant)}}}function isInteractiveHostEvent(event){return typeof event=="object"&&event!==null&&"type"in event}export{INTERACTIVE_HOST_FALLBACK_WARNING,INTERACTIVE_HOST_RECONNECTING_WARNING,RemoteInteractiveRuntime,createInteractiveHostRuntime,createRemoteSessionProxy,isInteractiveHostEvent};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
+ import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-FYFLULRU.js";import"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import"./chunk-VRDDXZF3.js";import"./chunk-GFUZPFHN.js";import{isApiKeyLoginProvider}from"./chunk-MA3Z67LK.js";import"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-KFIHWCMN.js";import"./chunk-2LSXWYT5.js";import"./chunk-U6Z6OBX4.js";import"./chunk-RA3P6BWS.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
@@ -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{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,ProviderScope,bindToProviderScope,createAgentSessionRuntime,runWithProviderScope}from"./chunk-PJ5U4M7M.js";import"./chunk-XJUVWITG.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import{SessionManager}from"./chunk-NBUMCMS4.js";import"./chunk-GFUZPFHN.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-63UWBQCO.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-CKNRCW35.js";import"./chunk-YRN3PCTM.js";import"./chunk-4C7LNOHI.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-KFIHWCMN.js";import{GENERATION_HANDOFF_CAPABILITY}from"./chunk-2LSXWYT5.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-U6Z6OBX4.js";import{HOST_DAEMON_DIR_ENV,PUBLIC_SOCKET_IDENTITY_FILE,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,createHostDaemonPaths,ensureSocketSecret,parseIdleExitMs,processIsLive,readHostWatchdogConfigFromBrandEnv,readProcessStartTime,readSocketIdentityFile,resolveSocketTransportAddress,shieldSocketDuringClose,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-RA3P6BWS.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostInstanceId,protocolIdentity}from"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-QROWINIH.js";import"./chunk-ANTGWIGI.js";import{killTrackedDetachedChildren}from"./chunk-2H3Y7EYQ.js";import"./chunk-VRAYXSST.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import{VERSION,envValue,isBunBinary}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{access,chmod,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{dirname as dirname2,join as join2}from"node:path";import{readdirSync,readFileSync}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadChildReaperSyscalls(platform=process.platform){let supported=supportedPlatform(platform);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat=linuxStat(pid),tail=stat?.slice(stat.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat=linuxStat(pid),open=stat?.indexOf("(")??-1,close=stat?.lastIndexOf(")")??-1;return stat===void 0||open===-1||close<=open?"":stat.slice(open+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS=1e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now();continue}now()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count])=>`${name} x${count}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log}),timer=setInterval(()=>reaper.tick(),config.tickMs);return timer.unref(),()=>clearInterval(timer)}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB";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;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??4096}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),3e4),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let rssMb=Math.round(this.readRssBytes()/1048576);if(rssMb<=this.warnMb){if(!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();this.emit({type:"host_memory_pressure",rssMb,sessions});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<3e5||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: rssMb=${rssMb} sessions=${sessions} (idle parking halved)
2
+ import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,ProviderScope,bindToProviderScope,createAgentSessionRuntime,runWithProviderScope}from"./chunk-FYFLULRU.js";import"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import{SessionManager}from"./chunk-VRDDXZF3.js";import"./chunk-GFUZPFHN.js";import{RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_UNKNOWN_SESSION,SessionEventWriter,buildRpcSessionState,createRpcConnectionHandler,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError}from"./chunk-MA3Z67LK.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-KFIHWCMN.js";import{GENERATION_HANDOFF_CAPABILITY}from"./chunk-2LSXWYT5.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,parseClientCapabilities}from"./chunk-U6Z6OBX4.js";import{HOST_DAEMON_DIR_ENV,PUBLIC_SOCKET_IDENTITY_FILE,SOCKET_SECRET_FILE_ENV,armHostWatchdog,authenticateSocket,createHostDaemonPaths,ensureSocketSecret,parseIdleExitMs,processIsLive,readHostWatchdogConfigFromBrandEnv,readProcessStartTime,readSocketIdentityFile,resolveSocketTransportAddress,shieldSocketDuringClose,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-RA3P6BWS.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,hostInstanceId,protocolIdentity}from"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killTrackedDetachedChildren}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import{VERSION,envValue,isBunBinary}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{access,chmod,mkdir as mkdir2,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{dirname as dirname2,join as join2}from"node:path";import{readdirSync,readFileSync}from"node:fs";var P_PID=1,WNOHANG=1,WEXITED=4,WNOWAIT={darwin:32,linux:16777216},SI_PID_OFFSET={darwin:12,linux:16},MAX_TRACKED_CHILDREN=4096;function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadChildReaperSyscalls(platform=process.platform){let supported=supportedPlatform(platform);if(supported===void 0||typeof globalThis.Bun>"u")return;let{dlopen,FFIType,ptr}=await import("bun:ffi"),wait=dlopen(supported==="darwin"?"libSystem.B.dylib":"libc.so.6",{waitid:{args:[FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32},waitpid:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),info=new Uint8Array(512),infoView=new DataView(info.buffer),status=new Int32Array(1),peekOptions=WEXITED|WNOHANG|WNOWAIT[supported],siPidOffset=SI_PID_OFFSET[supported];return{listDirectChildren:supported==="darwin"?darwinChildren(dlopen,FFIType,ptr):linuxChildren,isWaitable(pid){return info.fill(0),wait.symbols.waitid(P_PID,pid,ptr(info),peekOptions)===0&&infoView.getInt32(siPidOffset,!0)===pid},reapExited(pid){if(pid<=0)throw new Error(`child reaper refuses to wait on pid ${pid}`);return wait.symbols.waitpid(pid,ptr(status),WNOHANG)===pid},describe:supported==="darwin"?darwinName(dlopen,FFIType,ptr):linuxName}}function darwinChildren(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_listchildpids:{args:[FFIType.i32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),pids=new Int32Array(MAX_TRACKED_CHILDREN);return()=>{let found=libproc.symbols.proc_listchildpids(process.pid,ptr(pids),pids.byteLength);return found<=0?[]:Array.from(pids.subarray(0,Math.min(found,pids.length)))}}function darwinName(dlopen,FFIType,ptr){let libproc=dlopen("libSystem.B.dylib",{proc_name:{args:[FFIType.i32,FFIType.ptr,FFIType.u32],returns:FFIType.i32}}),name=new Uint8Array(256),decoder=new TextDecoder;return pid=>{name.fill(0);let written=libproc.symbols.proc_name(pid,ptr(name),name.length);return written<=0?"":decoder.decode(name.subarray(0,written))}}function linuxChildren(){let children=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!(!Number.isInteger(pid)||pid<=0)&&(parentOf(pid)===process.pid&&children.push(pid),children.length>=MAX_TRACKED_CHILDREN))break}return children}function linuxStat(pid){try{return readFileSync(`/proc/${pid}/stat`,"utf8")}catch{return}}function parentOf(pid){let stat=linuxStat(pid),tail=stat?.slice(stat.lastIndexOf(")")+2).split(" ");return tail===void 0?void 0:Number(tail[1])}function linuxName(pid){let stat=linuxStat(pid),open=stat?.indexOf("(")??-1,close=stat?.lastIndexOf(")")??-1;return stat===void 0||open===-1||close<=open?"":stat.slice(open+1,close)}var CHILD_REAPER_ENV="SENPI_RPC_HOST_REAPER",CHILD_REAPER_MIN_WAITABLE_MS_ENV="SENPI_RPC_HOST_REAPER_MIN_WAITABLE_MS",MIN_WAITABLE_FLOOR_MS=5e3,DEFAULT_MIN_WAITABLE_MS=3e4,TICK_MS=1e3,WARN_INTERVAL_MS=5*6e4,WARN_AT_WAITING=10,TOP_NAMES=3;function resolveChildReaperConfig(env){let override=Number(env[CHILD_REAPER_MIN_WAITABLE_MS_ENV]);return{enabled:env[CHILD_REAPER_ENV]!=="0",tickMs:TICK_MS,minWaitableMs:Number.isFinite(override)&&override>0?clampWindow(override):DEFAULT_MIN_WAITABLE_MS}}function clampWindow(milliseconds){return Math.max(MIN_WAITABLE_FLOOR_MS,milliseconds)}function createChildReaper(options){let now=options.now??Date.now,minWaitableMs=clampWindow(options.minWaitableMs??DEFAULT_MIN_WAITABLE_MS),tracked=new Map,lastWarnAt,report=(waiting,reaped)=>{options.log===void 0||reaped.length===0&&waiting.length<WARN_AT_WAITING||lastWarnAt!==void 0&&now()-lastWarnAt<WARN_INTERVAL_MS||(lastWarnAt=now(),options.log(`child reaper: reaped=${reaped.length} waiting=${waiting.length} top=${topNames(waiting,reaped)}`))};return{tick(){let children=options.syscalls.listDirectChildren(),present=new Set(children);for(let pid of[...tracked.keys()])present.has(pid)||tracked.delete(pid);let reaped=[];for(let pid of children){let child=tracked.get(pid)??{name:options.syscalls.describe(pid)||"unknown",waitableSince:void 0};if(tracked.set(pid,child),!options.syscalls.isWaitable(pid)){child.waitableSince=void 0;continue}if(child.waitableSince===void 0){child.waitableSince=now();continue}now()-child.waitableSince<minWaitableMs||options.syscalls.reapExited(pid)&&(tracked.delete(pid),reaped.push(child.name))}report(waitingNames(tracked),reaped)},get waitingPids(){return[...tracked].filter(([,child])=>child.waitableSince!==void 0).map(([pid])=>pid)}}}function waitingNames(tracked){return[...tracked.values()].filter(child=>child.waitableSince!==void 0).map(child=>child.name)}function topNames(waiting,reaped){let counts=new Map;for(let name of[...waiting,...reaped])counts.set(name,(counts.get(name)??0)+1);return[...counts].sort(([,left],[,right])=>right-left).slice(0,TOP_NAMES).map(([name,count])=>`${name} x${count}`).join(", ")}async function startHostChildReaper(log){let config=resolveChildReaperConfig(process.env);if(!config.enabled)return()=>{};let syscalls=await loadChildReaperSyscalls();if(syscalls===void 0)return log(`child reaper unavailable under ${runtimeName()}: children orphaned by a terminated worker thread stay as zombies until this host exits`),()=>{};let reaper=createChildReaper({syscalls,minWaitableMs:config.minWaitableMs,log}),timer=setInterval(()=>reaper.tick(),config.tickMs);return timer.unref(),()=>clearInterval(timer)}function runtimeName(){return typeof globalThis.Bun>"u"?"Node":`Bun on ${process.platform}`}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB";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;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??4096}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),3e4),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let rssMb=Math.round(this.readRssBytes()/1048576);if(rssMb<=this.warnMb){if(!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();this.emit({type:"host_memory_pressure",rssMb,sessions});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<3e5||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: rssMb=${rssMb} sessions=${sessions} (idle parking halved)
3
3
  `))}};import{createHash}from"node:crypto";import{mkdir,readFile,rename,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var SESSION_PATH_RETRY_AFTER_MS=2e3;function reservationFile(dir,sessionPath){return join(dir,`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`)}function createEndpointReservations(host){let told=process.env[HOST_DAEMON_DIR_ENV],dir=told!==void 0&&told.trim()!==""?told:host.socket===void 0?void 0:createHostDaemonPaths({socket:host.socket,agentDir:host.agentDir}).dir;if(dir!==void 0)return createSessionPathReservations({dir:join(dir,"reservations"),instanceId:host.instanceId,...host.onFailure?{onFailure:host.onFailure}:{}})}function createSessionPathReservations(options){let pid=options.pid??process.pid,startTime=readProcessStartTime(pid).then(value=>value??null,()=>null),held=new Set,report=message=>options.onFailure?.(message);return{async claim(sessionPath){let file=reservationFile(options.dir,sessionPath),existing=await readOwner(file);if(existing&&existing.pid!==pid&&await ownerIsLive(existing))return existing;let owner={instanceId:options.instanceId,pid,processStartTime:await startTime,sessionPath};try{await mkdir(options.dir,{recursive:!0,mode:448});let staging=`${file}.${pid}.tmp`;await writeFile(staging,`${JSON.stringify(owner)}
4
4
  `,{mode:384}),await rename(staging,file),held.add(sessionPath)}catch(cause){report(`session path reservation for ${sessionPath} could not be written (${errorMessage(cause)})`)}},release(sessionPath){held.delete(sessionPath)&&rm(reservationFile(options.dir,sessionPath),{force:!0}).catch(cause=>{report(`session path reservation for ${sessionPath} could not be removed (${errorMessage(cause)})`)})}}}async function readOwner(file){let parsed;try{parsed=JSON.parse(await readFile(file,"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let{instanceId,pid,processStartTime,sessionPath}=parsed;if(!(typeof instanceId!="string"||typeof pid!="number"||typeof sessionPath!="string"))return{instanceId,pid,processStartTime:typeof processStartTime=="string"?processStartTime:null,sessionPath}}async function ownerIsLive(owner){if(!processIsLive(owner.pid))return!1;if(owner.processStartTime===null)return!0;let current=await readProcessStartTime(owner.pid).catch(()=>{});return current===void 0||current===owner.processStartTime}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}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;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;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.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(){this.timer===void 0&&(this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark(),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 driftMs=Math.round(now-expectedAt);if(driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool}),!(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)})
5
5
  `))}};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(`
@@ -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{isForcedToolChoiceUnsupportedError,normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat,omitToolChoiceParam}from"./chunk-AGXZF7RF.js";import{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PUWVIQW6.js";import{clampOpenAIPromptCacheKey}from"./chunk-MUYK27UR.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-POMPEGWQ.js";import{retryProviderStreamRequest}from"./chunk-ZTVQY5V6.js";import{getOpenAICompletionsCompat}from"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import{getProviderEnvValue}from"./chunk-V55B77HQ.js";import{parseStreamingJson}from"./chunk-FC7R7NOV.js";import{formatProviderError,normalizeProviderError}from"./chunk-PRC5XIIH.js";import{appendGrammarToolInputJsonDelta,calculateCost,clampThinkingLevel,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,inferOpenAIThinkingLevelMap,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsMax,supportsXhigh,transformMessages}from"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-VR4X5O2Z.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 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 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=body=>createChatCompletion(body,requestOptions).withResponse(),createRequest=async()=>{try{return await createStream(params)}catch(error){if(isForcedToolChoiceUnsupportedError(error,isForcedOpenAICompletionsToolChoice(params.tool_choice)))return params=omitToolChoiceParam(params),createStream(params);throw error}},{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",output.errorMessage=formatProviderError(normalizeProviderError(error));let rawMetadata=getOpenRouterRawMetadata(error);rawMetadata&&!output.errorMessage.includes(String(rawMetadata))&&(output.errorMessage+=`
2
+ import{isForcedToolChoiceUnsupportedError,omitToolChoiceParam}from"./chunk-NQAVM5XL.js";import{resolveOpenAIClientAuth}from"./chunk-GFCKDAH5.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PUWVIQW6.js";import{clampOpenAIPromptCacheKey}from"./chunk-MUYK27UR.js";import{OpenAI}from"./chunk-CD2HJK4C.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions,clampMaxForOpenAI,clampThinkingBudgetToAnswerRoom,thinkingBudgetForLevel}from"./chunk-POMPEGWQ.js";import{retryProviderStreamRequest}from"./chunk-ZTVQY5V6.js";import{normalizeToolParametersForMoonshot,normalizeToolParametersForOpenAICompat}from"./chunk-IXAUDPOK.js";import{getOpenAICompletionsCompat}from"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import{getProviderEnvValue}from"./chunk-V55B77HQ.js";import{parseStreamingJson}from"./chunk-FC7R7NOV.js";import{formatProviderError,normalizeProviderError}from"./chunk-PRC5XIIH.js";import{appendGrammarToolInputJsonDelta,calculateCost,clampThinkingLevel,createGrammarToolInputProperties,getGrammarToolInput,getJsonSchemaToolParameters,inferOpenAIThinkingLevelMap,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsMax,supportsXhigh,transformMessages}from"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-VR4X5O2Z.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 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 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=body=>createChatCompletion(body,requestOptions).withResponse(),createRequest=async()=>{try{return await createStream(params)}catch(error){if(isForcedToolChoiceUnsupportedError(error,isForcedOpenAICompletionsToolChoice(params.tool_choice)))return params=omitToolChoiceParam(params),createStream(params);throw error}},{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",output.errorMessage=formatProviderError(normalizeProviderError(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,normalizedReasoning=clampedReasoning==="off"&&model.id.includes("gpt-6-astra")?"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:model.baseUrl.includes("api.openai.com")&&cacheRetention!=="none"||cacheRetention==="long"&&compat.supportsLongCacheRetention||compat.supportsPromptCacheKey&&cacheRetention!=="none"?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 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});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"&&params.push({role:"assistant",content:"I have processed the tool results."}),msg.role==="user")if(typeof msg.content=="string")params.push({role:"user",content:sanitizeSurrogates(msg.content)});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;params.push({role:"user",content})}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&&signature.length>0&&Object.assign(assistantMsg,{[signature]:nonEmptyThinkingBlocks.map(block=>block.thinking).join(`
@@ -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{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-PJ5U4M7M.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-XJUVWITG.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import"./chunk-NBUMCMS4.js";import"./chunk-GFUZPFHN.js";import"./chunk-63UWBQCO.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-CKNRCW35.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-YRN3PCTM.js";import{SettingsManager}from"./chunk-4C7LNOHI.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-KFIHWCMN.js";import"./chunk-2LSXWYT5.js";import"./chunk-U6Z6OBX4.js";import"./chunk-RA3P6BWS.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-QROWINIH.js";import"./chunk-ANTGWIGI.js";import{killProcessTree}from"./chunk-2H3Y7EYQ.js";import"./chunk-VRAYXSST.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import{source_default}from"./chunk-26UBFF6N.js";import{require_proper_lockfile}from"./chunk-3P23SBT3.js";import{APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import{__toESM}from"./chunk-VR4X5O2Z.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
2
+ import{DefaultResourceLoader,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-FYFLULRU.js";import{DefaultPackageManager,DynamicBorder,appendHiddenTuiStdout,keyHint,rawKeyHint}from"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import"./chunk-VRDDXZF3.js";import"./chunk-GFUZPFHN.js";import"./chunk-MA3Z67LK.js";import{initTheme,stopThemeWatcher,theme}from"./chunk-RLRLQRI2.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-YRN3PCTM.js";import{SettingsManager}from"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-KFIHWCMN.js";import"./chunk-2LSXWYT5.js";import"./chunk-U6Z6OBX4.js";import"./chunk-RA3P6BWS.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import{killProcessTree}from"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import{source_default}from"./chunk-26UBFF6N.js";import{require_proper_lockfile}from"./chunk-3P23SBT3.js";import{APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import{__toESM}from"./chunk-VR4X5O2Z.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
3
3
  `)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...process.execArgv,cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd]});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
4
4
  `,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
5
5
  `)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
@@ -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{classifyCredentialFailure,rendezvousOrder,resolveConfigValue,runCredentialFailover}from"./chunk-QROWINIH.js";import{discoverEnvSlots}from"./chunk-ANTGWIGI.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-VRAYXSST.js";import"./chunk-56TWFZ2C.js";import{acquireHalfOpenLease}from"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import{listSlots}from"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{createHash,randomUUID}from"node:crypto";var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,{providerId,credential,env,repository}=sources,policySlots=[];for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,{}):void 0;key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of listSlots(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0;if(acquireLeases&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=(sources.now??Date.now)()){if(!await acquireHalfOpenLease(repository,providerId,"stored",slot.name,{now:(sources.now??Date.now)()}))continue;let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name];slots.push(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedState?.credentialRevision===storedRevision?leasedState:void 0));continue}slots.push(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable))}if(policySlots.length===0)return slots;let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];return listEnvRotationSlots(sources,envSlots,acquireLeases)}async function listEnvRotationSlots(sources,envSlots,acquireLeases=!0){if(envSlots.length===0)return[];let{providerId,repository}=sources,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0;if(acquireLeases&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=(sources.now??Date.now)()){if(!await acquireHalfOpenLease(repository,providerId,"env",slot.name,{now:(sources.now??Date.now)()}))continue;applicable=(await repository.listSlots(providerId,"env"))[slot.name]}slots.push(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable))}return slots}function blockPatch(block,current,now,credentialRevision,policy){let base={failureCount:(current?.failureCount??0)+1,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:{...base,blockReason:block.reason}}function errorFromEvent(event){if(event.type!=="error")return;let message=event.error.errorMessage??"provider stream error";return new Error(message)}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let winner=(useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:event=>event.type!=="start",errorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0}:void 0)},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
2
+ import{classifyCredentialFailure,rendezvousOrder,resolveConfigValue,runCredentialFailover}from"./chunk-XK24AFYU.js";import{discoverEnvSlots}from"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import{acquireHalfOpenLease}from"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import{listSlots}from"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";import{createHash,randomUUID}from"node:crypto";var sha256SlotHasher=input=>createHash("sha256").update(input).digest().readBigUInt64BE(0);function overlayState(slot,state){return state?{...slot,...state.blockedUntil===void 0?{}:{blockedUntil:state.blockedUntil},...state.blockReason===void 0?{}:{blockReason:state.blockReason},...state.failureCount===void 0?{}:{failureCount:state.failureCount},...state.lease===void 0?{}:{lease:state.lease}}:slot}async function listRotationSlots(sources,options={}){let acquireLeases=options.acquireLeases!==!1,{providerId,credential,env,repository}=sources,policySlots=[];for(let[name,ref]of Object.entries(sources.policy?.slots??{})){let envVarName=ref.env??`models.json:${name}`,key=ref.env!==void 0?env(ref.env):ref.value!==void 0?await resolveConfigValue(ref.value,{}):void 0;key&&policySlots.push({name,envVarName,key,source:"env"})}if(credential){let state=await repository.listSlots(providerId,"stored"),slots=[];for(let slot of listSlots(credential)){let persisted=state[slot.name],storedRevision=await repository.storedCredentialRevision(providerId,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=persisted?.credentialRevision===storedRevision?persisted:void 0;if(acquireLeases&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=(sources.now??Date.now)()){if(!await acquireHalfOpenLease(repository,providerId,"stored",slot.name,{now:(sources.now??Date.now)()}))continue;let leasedState=(await repository.listSlots(providerId,"stored"))[slot.name];slots.push(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},leasedState?.credentialRevision===storedRevision?leasedState:void 0));continue}slots.push(overlayState({name:slot.name,lane:"stored",pinned:credential.pinned===slot.name,storedRevision},applicable))}if(policySlots.length===0)return slots;let namedSources={...sources,credential:void 0,policy:{...sources.policy,slots:{}}},namedSlots=await listEnvRotationSlots(namedSources,policySlots,acquireLeases);return[...slots,...namedSlots]}let envSlots=[...discoverEnvSlots(providerId,env),...policySlots];return listEnvRotationSlots(sources,envSlots,acquireLeases)}async function listEnvRotationSlots(sources,envSlots,acquireLeases=!0){if(envSlots.length===0)return[];let{providerId,repository}=sources,state=await repository.listSlots(providerId,"env"),slots=[];for(let slot of envSlots){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0;if(acquireLeases&&applicable?.blockedUntil!==void 0&&applicable.blockedUntil<=(sources.now??Date.now)()){if(!await acquireHalfOpenLease(repository,providerId,"env",slot.name,{now:(sources.now??Date.now)()}))continue;applicable=(await repository.listSlots(providerId,"env"))[slot.name]}slots.push(overlayState({name:slot.name,lane:"env",envKey:slot.key,envVarName:slot.envVarName},applicable))}return slots}function blockPatch(block,current,now,credentialRevision,policy){let base={failureCount:(current?.failureCount??0)+1,...credentialRevision===void 0?{}:{credentialRevision},...current?.lastSuccessAt===void 0?{}:{lastSuccessAt:current.lastSuccessAt}};return block.reason==="rate_limit"?{...base,blockedUntil:now+Math.min(policy?.cooldownCapMs??block.cooldownMs,block.cooldownMs),blockReason:"rate_limit"}:{...base,blockReason:block.reason}}function errorFromEvent(event){if(event.type!=="error")return;let message=event.error.errorMessage??"provider stream error";return new Error(message)}function streamWithCredentialRotation(options){let{sources,runAttempt}=options,hasher=options.hasher??sha256SlotHasher,affinityKey=options.affinityKey??randomUUID(),useAffinity=sources.policy?.affinity!==!1,now=sources.now??Date.now;return runCredentialFailover({listSlots:()=>listRotationSlots(sources),select:candidates=>{let pinned=candidates.find(candidate=>candidate.pinned===!0);if(pinned)return pinned;let winner=(useAffinity?rendezvousOrder(affinityKey,candidates,hasher):candidates)[0];if(!winner)throw new Error("credential rotation selected from an empty candidate set");return winner},runAttempt,isCommittedOutput:event=>event.type!=="start",errorFromEvent,classify:(error,context)=>classifyCredentialFailure(error,{...context,cooldownBaseMs:sources.policy?.cooldownBaseMs,cooldownCapMs:sources.policy?.cooldownCapMs}),onSuccess:async slot=>{await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>current?{...current,lastSuccessAt:now(),lease:void 0,blockedUntil:void 0,blockReason:void 0}:void 0)},persistBlock:async(slot,block)=>{let revision=slot.lane==="env"&&slot.envVarName!==void 0&&slot.envKey!==void 0?await sources.repository.envCredentialRevision(slot.envVarName,slot.envKey):slot.storedRevision;await sources.repository.mutateSlotState(sources.providerId,slot.lane,slot.name,current=>blockPatch(block,current,now(),revision,sources.policy))},now})}export{listRotationSlots,sha256SlotHasher,streamWithCredentialRotation};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
+ import{runRpcMode}from"./chunk-MA3Z67LK.js";import"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-HSH674C6.js";import"./chunk-HB35RBP4.js";import"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-U7RQY7MH.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";export{runRpcMode};
@@ -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{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-XJUVWITG.js";import{KeybindingsManager}from"./chunk-3Q4WGKFA.js";import"./chunk-CKNRCW35.js";import{setKeybindings}from"./chunk-YRN3PCTM.js";import"./chunk-4C7LNOHI.js";import"./chunk-QOBJEPJZ.js";import"./chunk-VRAYXSST.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-I7YUNMWH.js";import"./chunk-U7RQY7MH.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};
2
+ import{SessionSelectorComponent,createStartupTui,startStartupTui}from"./chunk-3FRTRCR6.js";import{KeybindingsManager}from"./chunk-3Q4WGKFA.js";import"./chunk-RLRLQRI2.js";import{setKeybindings}from"./chunk-YRN3PCTM.js";import"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-7X72IACK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-I3F6VZZF.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-I7YUNMWH.js";import"./chunk-U7RQY7MH.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";async function selectSession(currentSessionsLoader,allSessionsLoader,settingsManager){let ui=await createStartupTui(settingsManager);return new Promise(resolve=>{let keybindings=KeybindingsManager.create();setKeybindings(keybindings);let resolved=!1,selector=new SessionSelectorComponent(currentSessionsLoader,allSessionsLoader,path=>{resolved||(resolved=!0,ui.stop(),resolve(path))},()=>{resolved||(resolved=!0,ui.stop(),resolve(null))},()=>{ui.stop(),process.exit(0)},()=>ui.requestRender(),{showRenameHint:!1,keybindings});ui.addChild(selector),ui.setFocus(selector.getSessionList()),startStartupTui(ui,settingsManager)})}export{selectSession};