@code-yeongyu/senpi 2026.10.11 → 2026.10.12

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 (188) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/bundle/chunks/anthropic-messages-GYG6YZY5.js +10 -0
  3. package/dist/bundle/chunks/{app-server-command-NHDOL4HQ.js → app-server-command-OL6PPUOA.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-EJF2XJ7Q.js → azure-openai-responses-GU6FOSJR.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-ZABLYCHT.js → chunk-46JEQXD7.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-VE3D74HN.js → chunk-55VKYA5V.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-7UNN3YHW.js → chunk-5AVFHHDF.js} +230 -221
  8. package/dist/bundle/chunks/{chunk-2JE2DOIF.js → chunk-5DPTM5E2.js} +1 -1
  9. package/dist/bundle/chunks/chunk-5UPUSGP5.js +2 -0
  10. package/dist/bundle/chunks/chunk-5VMRMY6N.js +16 -0
  11. package/dist/bundle/chunks/{chunk-7X3VRAM3.js → chunk-7P3QPVTF.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-T6IYKWIH.js → chunk-BUGZZVQW.js} +1 -1
  13. package/dist/bundle/chunks/chunk-DL7EFVT2.js +12 -0
  14. package/dist/bundle/chunks/chunk-E5YUVGLQ.js +11 -0
  15. package/dist/bundle/chunks/{chunk-RLFQICEY.js → chunk-EQJY2B5F.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-VYKBN4MR.js → chunk-GC2RU5TS.js} +1 -1
  17. package/dist/bundle/chunks/chunk-GPKEJOTQ.js +202 -0
  18. package/dist/bundle/chunks/{chunk-KCVSSFOV.js → chunk-GQ5PWY6P.js} +4 -3
  19. package/dist/bundle/chunks/{chunk-4GPJOGXZ.js → chunk-I4AEC6MH.js} +1 -1
  20. package/dist/bundle/chunks/chunk-JXSFGRBE.js +8 -0
  21. package/dist/bundle/chunks/{chunk-YGCMN2CX.js → chunk-NAY5LB53.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-EBOD66AS.js → chunk-PBN2CATL.js} +2 -2
  23. package/dist/bundle/chunks/chunk-PFNBY43W.js +2 -0
  24. package/dist/bundle/chunks/{chunk-CY2B4QRR.js → chunk-PUWEQK2W.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-5DBPUQSX.js → chunk-SF6AUNQZ.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-G2XAU4BX.js → chunk-TMTT5CLA.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-2JKDZXIY.js → chunk-VWFKLW73.js} +2 -2
  28. package/dist/bundle/chunks/chunk-WZMSBRTW.js +2 -0
  29. package/dist/bundle/chunks/{chunk-55HLKZSB.js → chunk-XVJRRLGN.js} +1 -1
  30. package/dist/bundle/chunks/chunk-Z2PWWBBD.js +31 -0
  31. package/dist/bundle/chunks/cli-main-RSIYAR4J.js +3 -0
  32. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-SWVU2AXJ.js → cloudflare-workers-ai-system-one-LVWRKOUD.js} +1 -1
  33. package/dist/bundle/chunks/{google-generative-ai-XG4YX6FQ.js → google-generative-ai-JMGYPTXL.js} +1 -1
  34. package/dist/bundle/chunks/{google-vertex-BBOZ6OUB.js → google-vertex-CI4FPIU7.js} +1 -1
  35. package/dist/bundle/chunks/{help-fast-path-EZ3KEW6V.js → help-fast-path-M7KMBM6K.js} +1 -1
  36. package/dist/bundle/chunks/host-command-6UR3DSFR.js +2 -0
  37. package/dist/bundle/chunks/host-lifecycle-2BKCCK5X.js +3 -0
  38. package/dist/bundle/chunks/host-lifecycle.js +10 -7
  39. package/dist/bundle/chunks/host-session-command-A2MZHEBP.js +19 -0
  40. package/dist/bundle/chunks/interactive-mode-EJBMTJOH.js +2 -0
  41. package/dist/bundle/chunks/{list-tips-WE2YGQM6.js → list-tips-BEQAOA4N.js} +1 -1
  42. package/dist/bundle/chunks/{mistral-conversations-RB3ZBCGE.js → mistral-conversations-5OD7662T.js} +1 -1
  43. package/dist/bundle/chunks/{multi-session-host-V4CUQLV7.js → multi-session-host-YYMLHCUA.js} +4 -4
  44. package/dist/bundle/chunks/{openai-codex-responses-DBTPUXRW.js → openai-codex-responses-FN3UPAFI.js} +1 -1
  45. package/dist/bundle/chunks/{openai-completions-QAJQC4BY.js → openai-completions-KMUQ3T4M.js} +1 -1
  46. package/dist/bundle/chunks/{openai-responses-UBJWCEHG.js → openai-responses-V4Q5GVLO.js} +1 -1
  47. package/dist/bundle/chunks/{package-manager-cli-WTRDT4ZH.js → package-manager-cli-6A5ZP26E.js} +1 -1
  48. package/dist/bundle/chunks/rotation-stream-PT6LLBMJ.js +2 -0
  49. package/dist/bundle/chunks/rpc-mode-XNYJPYUM.js +2 -0
  50. package/dist/bundle/chunks/runtime-session-ZBHFMT65.js +2 -0
  51. package/dist/bundle/chunks/{schedule-command-PJVRKAKD.js → schedule-command-FYQG2MFX.js} +1 -1
  52. package/dist/bundle/chunks/session-control-endpoint-7TX4XHN4.js +3 -0
  53. package/dist/bundle/chunks/session-picker-4RNB27SM.js +2 -0
  54. package/dist/bundle/chunks/session-worker.js +418 -412
  55. package/dist/bundle/chunks/{typesafe-system-one-B5TW3FHM.js → typesafe-system-one-WUHW7HR4.js} +1 -1
  56. package/dist/bundle/cli.js +1 -1
  57. package/dist/bundle/index.js +1 -1
  58. package/dist/bundle/rpc-entry.js +1 -1
  59. package/dist/bundle/runtime-manifest.json +1 -1
  60. package/dist/core/agent-session.d.ts +11 -2
  61. package/dist/core/agent-session.js +152 -43
  62. package/dist/core/compaction/compaction.js +2 -0
  63. package/dist/core/extensions/builtin/anthropic-web-search/index.js +22 -14
  64. package/dist/core/extensions/builtin/cache-keepalive/index.js +8 -4
  65. package/dist/core/extensions/builtin/cache-keepalive/session-prewarm.d.ts +2 -1
  66. package/dist/core/extensions/builtin/cache-keepalive/session-prewarm.js +55 -7
  67. package/dist/core/extensions/builtin/cache-keepalive/startup-activity-gate.d.ts +8 -0
  68. package/dist/core/extensions/builtin/cache-keepalive/startup-activity-gate.js +25 -0
  69. package/dist/core/extensions/builtin/compaction/index.js +13 -5
  70. package/dist/core/extensions/builtin/compaction/speculative.d.ts +1 -0
  71. package/dist/core/extensions/builtin/compaction/speculative.js +8 -4
  72. package/dist/core/extensions/builtin/moved-path-guard/tool-classes.js +1 -0
  73. package/dist/core/extensions/builtin/openai-web-search/index.d.ts +4 -1
  74. package/dist/core/extensions/builtin/openai-web-search/index.js +54 -17
  75. package/dist/core/extensions/builtin/server-search-fallback.d.ts +12 -0
  76. package/dist/core/extensions/builtin/server-search-fallback.js +50 -0
  77. package/dist/core/extensions/builtin/terminal/runtime-session.d.ts +10 -1
  78. package/dist/core/extensions/builtin/terminal/runtime-session.js +48 -4
  79. package/dist/core/extensions/builtin/websearch/index.d.ts +1 -1
  80. package/dist/core/extensions/builtin/websearch/index.js +119 -18
  81. package/dist/core/extensions/builtin/websearch/server-search.d.ts +11 -0
  82. package/dist/core/extensions/builtin/websearch/server-search.js +230 -0
  83. package/dist/core/extensions/builtin/websearch/websearch/native.d.ts +2 -0
  84. package/dist/core/extensions/builtin/websearch/websearch/search-model.js +15 -0
  85. package/dist/core/extensions/runner.d.ts +8 -1
  86. package/dist/core/extensions/runner.js +56 -7
  87. package/dist/core/extensions/types.d.ts +12 -2
  88. package/dist/core/extensions/user-activity.d.ts +10 -0
  89. package/dist/core/extensions/user-activity.js +20 -0
  90. package/dist/core/model-config-schema.d.ts +34 -0
  91. package/dist/core/model-config-schema.js +2 -0
  92. package/dist/core/model-config.js +1 -0
  93. package/dist/core/reserved-keywords.d.ts +28 -0
  94. package/dist/core/reserved-keywords.js +81 -0
  95. package/dist/core/retry-fallback/candidates.d.ts +1 -1
  96. package/dist/core/retry-fallback/candidates.js +1 -12
  97. package/dist/core/retry-fallback/controller.d.ts +3 -1
  98. package/dist/core/retry-fallback/controller.js +11 -5
  99. package/dist/core/retry-fallback/cooldown.d.ts +2 -1
  100. package/dist/core/retry-fallback/cooldown.js +21 -12
  101. package/dist/core/retry-fallback/unusable.d.ts +2 -0
  102. package/dist/core/retry-fallback/unusable.js +14 -2
  103. package/dist/core/retry-fallback/usage-limit.d.ts +10 -1
  104. package/dist/core/retry-fallback/usage-limit.js +39 -2
  105. package/dist/core/session-title-generator.js +2 -0
  106. package/dist/index.d.ts +2 -1
  107. package/dist/index.js +1 -0
  108. package/dist/modes/index.d.ts +1 -1
  109. package/dist/modes/interactive/components/assistant-render-descriptors.js +7 -1
  110. package/dist/modes/interactive/composer-user-activity.d.ts +6 -0
  111. package/dist/modes/interactive/composer-user-activity.js +30 -0
  112. package/dist/modes/interactive/grok/chrome.js +2 -1
  113. package/dist/modes/interactive/interactive-mode.js +15 -6
  114. package/dist/modes/interactive/session-control-registry.js +8 -1
  115. package/dist/modes/interactive/theme/reserved-keyword-rainbow.d.ts +11 -0
  116. package/dist/modes/interactive/theme/reserved-keyword-rainbow.js +50 -0
  117. package/dist/modes/interactive/theme/theme.d.ts +3 -1
  118. package/dist/modes/interactive/theme/theme.js +9 -0
  119. package/dist/modes/print-mode.js +7 -2
  120. package/dist/modes/rpc/connection-handler.js +43 -11
  121. package/dist/modes/rpc/custom-capability.d.ts +2 -0
  122. package/dist/modes/rpc/custom-capability.js +2 -0
  123. package/dist/modes/rpc/host-admission-proxy.d.ts +9 -0
  124. package/dist/modes/rpc/host-admission-proxy.js +211 -0
  125. package/dist/modes/rpc/host-admission.d.ts +21 -0
  126. package/dist/modes/rpc/host-admission.js +59 -0
  127. package/dist/modes/rpc/host-capabilities.js +2 -1
  128. package/dist/modes/rpc/host-client-occupancy.d.ts +2 -1
  129. package/dist/modes/rpc/host-client-occupancy.js +7 -0
  130. package/dist/modes/rpc/host-decision.d.ts +2 -2
  131. package/dist/modes/rpc/host-decision.js +4 -0
  132. package/dist/modes/rpc/host-ensure-types.d.ts +2 -0
  133. package/dist/modes/rpc/host-ensure.js +31 -3
  134. package/dist/modes/rpc/host-lifecycle-drain.d.ts +2 -1
  135. package/dist/modes/rpc/host-lifecycle-drain.js +3 -1
  136. package/dist/modes/rpc/host-lifecycle-proxy.d.ts +3 -2
  137. package/dist/modes/rpc/host-lifecycle-proxy.js +10 -19
  138. package/dist/modes/rpc/host-lifecycle-shutdown.d.ts +2 -0
  139. package/dist/modes/rpc/host-lifecycle-shutdown.js +3 -1
  140. package/dist/modes/rpc/host-lifecycle-ticker.d.ts +11 -0
  141. package/dist/modes/rpc/host-lifecycle-ticker.js +27 -0
  142. package/dist/modes/rpc/host-lifecycle.js +15 -23
  143. package/dist/modes/rpc/host-outcome.js +1 -0
  144. package/dist/modes/rpc/host-protocol-info.d.ts +2 -0
  145. package/dist/modes/rpc/host-protocol-info.js +1 -0
  146. package/dist/modes/rpc/host-session-runner.js +22 -1
  147. package/dist/modes/rpc/host-status-all.js +1 -0
  148. package/dist/modes/rpc/host-status.d.ts +1 -0
  149. package/dist/modes/rpc/host-status.js +5 -1
  150. package/dist/modes/rpc/rpc-client.d.ts +7 -1
  151. package/dist/modes/rpc/rpc-client.js +12 -0
  152. package/dist/modes/rpc/rpc-types.d.ts +49 -1
  153. package/dist/modes/rpc/rpc-types.js +5 -0
  154. package/dist/modes/rpc/session-command-activity.js +2 -0
  155. package/dist/modes/rpc/session-held.js +3 -0
  156. package/docs/extensions.md +13 -1
  157. package/docs/providers.md +88 -0
  158. package/docs/rpc.md +150 -5
  159. package/docs/web-search.md +3 -1
  160. package/package.json +7 -7
  161. package/dist/bundle/chunks/anthropic-messages-5QQJVQPZ.js +0 -9
  162. package/dist/bundle/chunks/chunk-2A3MS2Z7.js +0 -8
  163. package/dist/bundle/chunks/chunk-6SBY4ZWC.js +0 -2
  164. package/dist/bundle/chunks/chunk-6WCOSBI7.js +0 -2
  165. package/dist/bundle/chunks/chunk-E75RO54O.js +0 -14
  166. package/dist/bundle/chunks/chunk-JMYO34RK.js +0 -2
  167. package/dist/bundle/chunks/chunk-KRNXUTZJ.js +0 -2
  168. package/dist/bundle/chunks/chunk-L4HVJWIF.js +0 -11
  169. package/dist/bundle/chunks/chunk-N5WLLHUE.js +0 -2
  170. package/dist/bundle/chunks/chunk-NEFNNQSV.js +0 -9
  171. package/dist/bundle/chunks/chunk-PWIYVLIA.js +0 -9
  172. package/dist/bundle/chunks/chunk-Q3R44CGT.js +0 -5
  173. package/dist/bundle/chunks/chunk-QIARZN7G.js +0 -31
  174. package/dist/bundle/chunks/chunk-QKU6JOA4.js +0 -2
  175. package/dist/bundle/chunks/chunk-QYWXDE47.js +0 -2
  176. package/dist/bundle/chunks/chunk-XHELSLN3.js +0 -188
  177. package/dist/bundle/chunks/chunk-YDJ4HGWO.js +0 -16
  178. package/dist/bundle/chunks/chunk-ZJHRDQCH.js +0 -2
  179. package/dist/bundle/chunks/cli-main-TUBNBZNK.js +0 -3
  180. package/dist/bundle/chunks/host-command-WO7VKJBJ.js +0 -2
  181. package/dist/bundle/chunks/host-lifecycle-X2J5FTJL.js +0 -3
  182. package/dist/bundle/chunks/host-session-command-ICBOH5RP.js +0 -19
  183. package/dist/bundle/chunks/interactive-mode-UGDNCGQ5.js +0 -2
  184. package/dist/bundle/chunks/rotation-stream-OODURUGZ.js +0 -2
  185. package/dist/bundle/chunks/rpc-mode-22MCT32O.js +0 -2
  186. package/dist/bundle/chunks/runtime-session-I4NDNGC5.js +0 -2
  187. package/dist/bundle/chunks/session-control-endpoint-SFPRQBDO.js +0 -3
  188. package/dist/bundle/chunks/session-picker-3ZQPV7Z3.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{import_websocket}from"./chunk-YBZDAABT.js";import{normalizeToolCallId}from"./chunk-T6IYKWIH.js";import{retryProviderRequest}from"./chunk-GQ3YLXVZ.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-VYKBN4MR.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-L4HVJWIF.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&&copy&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
2
+ import{import_websocket}from"./chunk-YBZDAABT.js";import{normalizeToolCallId}from"./chunk-BUGZZVQW.js";import{retryProviderRequest}from"./chunk-GQ3YLXVZ.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-GC2RU5TS.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-E5YUVGLQ.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&&copy&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
3
3
  `)||message,code,status},res.data.error)}return Object.assign({message,code,status},res.data.error)}}return{message,code:res.status,status:res.statusText}}};exports.GaxiosError=GaxiosError;function translateData(responseType,data){switch(responseType){case"stream":return data;case"json":return JSON.parse(JSON.stringify(data));case"arraybuffer":return JSON.parse(Buffer.from(data).toString("utf8"));case"blob":return JSON.parse(data.text());default:return data}}function defaultErrorRedactor(data){let REDACT="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function redactHeaders(headers){headers&&headers.forEach((_,key)=>{(/^authentication$/i.test(key)||/^authorization$/i.test(key)||/secret/i.test(key))&&headers.set(key,REDACT)})}function redactString(obj,key){if(typeof obj=="object"&&obj!==null&&typeof obj[key]=="string"){let text=obj[key];(/grant_type=/i.test(text)||/assertion=/i.test(text)||/secret/i.test(text))&&(obj[key]=REDACT)}}function redactObject(obj){!obj||typeof obj!="object"||(obj instanceof FormData||obj instanceof URLSearchParams||"forEach"in obj&&"set"in obj?obj.forEach((_,key)=>{(["grant_type","assertion"].includes(key)||/secret/.test(key))&&obj.set(key,REDACT)}):("grant_type"in obj&&(obj.grant_type=REDACT),"assertion"in obj&&(obj.assertion=REDACT),"client_secret"in obj&&(obj.client_secret=REDACT)))}return data.config&&(redactHeaders(data.config.headers),redactString(data.config,"data"),redactObject(data.config.data),redactString(data.config,"body"),redactObject(data.config.body),data.config.url.searchParams.has("token")&&data.config.url.searchParams.set("token",REDACT),data.config.url.searchParams.has("client_secret")&&data.config.url.searchParams.set("client_secret",REDACT)),data.response&&(defaultErrorRedactor({config:data.response.config}),redactHeaders(data.response.headers),data.response.bodyUsed&&(redactString(data.response,"data"),redactObject(data.response.data))),data}}});var require_retry3=__commonJS({"node_modules/gaxios/build/cjs/src/retry.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRetryConfig=getRetryConfig;async function getRetryConfig(err){let config=getConfig(err);if(!err||!err.config||!config&&!err.config.retry)return{shouldRetry:!1};config=config||{},config.currentRetryAttempt=config.currentRetryAttempt||0,config.retry=config.retry===void 0||config.retry===null?3:config.retry,config.httpMethodsToRetry=config.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],config.noResponseRetries=config.noResponseRetries===void 0||config.noResponseRetries===null?2:config.noResponseRetries,config.retryDelayMultiplier=config.retryDelayMultiplier?config.retryDelayMultiplier:2,config.timeOfFirstRequest=config.timeOfFirstRequest?config.timeOfFirstRequest:Date.now(),config.totalTimeout=config.totalTimeout?config.totalTimeout:Number.MAX_SAFE_INTEGER,config.maxRetryDelay=config.maxRetryDelay?config.maxRetryDelay:Number.MAX_SAFE_INTEGER;let retryRanges=[[100,199],[408,408],[429,429],[500,599]];if(config.statusCodesToRetry=config.statusCodesToRetry||retryRanges,err.config.retryConfig=config,!await(config.shouldRetry||shouldRetryRequest)(err))return{shouldRetry:!1,config:err.config};let delay2=getNextRetryDelay(config);err.config.retryConfig.currentRetryAttempt+=1;let backoff=config.retryBackoff?config.retryBackoff(err,delay2):new Promise(resolve=>{setTimeout(resolve,delay2)});return config.onRetryAttempt&&await config.onRetryAttempt(err),await backoff,{shouldRetry:!0,config:err.config}}function shouldRetryRequest(err){let config=getConfig(err);if(err.config.signal?.aborted&&err.code!=="TimeoutError"||err.code==="AbortError"||!config||config.retry===0||!err.response&&(config.currentRetryAttempt||0)>=config.noResponseRetries||!config.httpMethodsToRetry||!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase()||"GET"))return!1;if(err.response&&err.response.status){let isInRange=!1;for(let[min,max]of config.statusCodesToRetry){let status=err.response.status;if(status>=min&&status<=max){isInRange=!0;break}}if(!isInRange)return!1}return config.currentRetryAttempt=config.currentRetryAttempt||0,!(config.currentRetryAttempt>=config.retry)}function getConfig(err){if(err&&err.config&&err.config.retryConfig)return err.config.retryConfig}function getNextRetryDelay(config){let calculatedDelay=(config.currentRetryAttempt?0:config.retryDelay??100)+(Math.pow(config.retryDelayMultiplier,config.currentRetryAttempt)-1)/2*1e3,maxAllowableDelay=config.totalTimeout-(Date.now()-config.timeOfFirstRequest);return Math.min(calculatedDelay,maxAllowableDelay,config.maxRetryDelay)}}});var require_interceptor=__commonJS({"node_modules/gaxios/build/cjs/src/interceptor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosInterceptorManager=void 0;var GaxiosInterceptorManager=class extends Set{};exports.GaxiosInterceptorManager=GaxiosInterceptorManager}});var require_gaxios=__commonJS({"node_modules/gaxios/build/cjs/src/gaxios.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},_a2;Object.defineProperty(exports,"__esModule",{value:!0});exports.Gaxios=void 0;var extend_1=__importDefault(require_extend()),https_1=__require("https"),common_js_1=require_common(),retry_js_1=require_retry3(),stream_1=__require("stream"),interceptor_js_1=require_interceptor(),randomUUID=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),HTTP_STATUS_NO_CONTENT=204,Gaxios=class{agentCache=new Map;defaults;interceptors;constructor(defaults){this.defaults=defaults||{},this.interceptors={request:new interceptor_js_1.GaxiosInterceptorManager,response:new interceptor_js_1.GaxiosInterceptorManager}}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&_a2.mergeHeaders(headers,input.headers),init&&_a2.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}async request(opts={}){let prepared=await this.#prepareRequest(opts);return prepared=await this.#applyRequestInterceptors(prepared),this.#applyResponseInterceptors(this._request(prepared))}async _defaultAdapter(config){let fetchImpl=config.fetchImplementation||this.defaults.fetchImplementation||await _a2.#getFetch(),preparedOpts={...config};delete preparedOpts.data;let res=await fetchImpl(config.url,preparedOpts),data=await this.getResponseData(config,res);return Object.getOwnPropertyDescriptor(res,"data")?.configurable||Object.defineProperties(res,{data:{configurable:!0,writable:!0,enumerable:!0,value:data}}),Object.assign(res,{config,data})}async _request(opts){try{let translatedResponse;if(opts.adapter?translatedResponse=await opts.adapter(opts,this._defaultAdapter.bind(this)):translatedResponse=await this._defaultAdapter(opts),!opts.validateStatus(translatedResponse.status)){if(opts.responseType==="stream"){let response=[];for await(let chunk of translatedResponse.data)response.push(chunk);translatedResponse.data=response.toString()}let errorInfo=common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse,`Request failed with status code ${translatedResponse.status}`);throw new common_js_1.GaxiosError(errorInfo?.message,opts,translatedResponse,errorInfo)}return translatedResponse}catch(e){let err;e instanceof common_js_1.GaxiosError?err=e:e instanceof Error?err=new common_js_1.GaxiosError(e.message,opts,void 0,e):err=new common_js_1.GaxiosError("Unexpected Gaxios Error",opts,void 0,e);let{shouldRetry,config}=await(0,retry_js_1.getRetryConfig)(err);if(shouldRetry&&config)return err.config.retryConfig.currentRetryAttempt=config.retryConfig.currentRetryAttempt,opts.retryConfig=err.config?.retryConfig,this.#appendTimeoutToSignal(opts),this._request(opts);throw opts.errorRedactor&&opts.errorRedactor(err),err}}async getResponseData(opts,res){if(res.status===HTTP_STATUS_NO_CONTENT)return"";if(opts.maxContentLength&&res.headers.has("content-length")&&opts.maxContentLength<Number.parseInt(res.headers?.get("content-length")||""))throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.",opts,Object.assign(res,{config:opts}));switch(opts.responseType){case"stream":return res.body;case"json":{let data=await res.text();try{return JSON.parse(data)}catch{return data}}case"arraybuffer":return res.arrayBuffer();case"blob":return res.blob();case"text":return res.text();default:return this.getResponseDataFromContentType(res)}}#urlMayUseProxy(url,noProxy=[]){let candidate=new URL(url),noProxyList=[...noProxy],noProxyEnvList=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let rule of noProxyEnvList)noProxyList.push(rule.trim());for(let rule of noProxyList)if(rule instanceof RegExp){if(rule.test(candidate.toString()))return!1}else if(rule instanceof URL){if(rule.origin===candidate.origin)return!1}else if(rule.startsWith("*.")||rule.startsWith(".")){let cleanedRule=rule.replace(/^\*\./,".");if(candidate.hostname.endsWith(cleanedRule))return!1}else if(rule===candidate.origin||rule===candidate.hostname||rule===candidate.href)return!1;return!0}async#applyRequestInterceptors(options){let promiseChain=Promise.resolve(options);for(let interceptor of this.interceptors.request.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#applyResponseInterceptors(response){let promiseChain=Promise.resolve(response);for(let interceptor of this.interceptors.response.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#prepareRequest(options){let preparedHeaders=new Headers(this.defaults.headers);_a2.mergeHeaders(preparedHeaders,options.headers);let opts=(0,extend_1.default)(!0,{},this.defaults,options);if(!opts.url)throw new Error("URL is required.");if(opts.baseURL&&(opts.url=new URL(opts.url,opts.baseURL)),opts.url=new URL(opts.url),opts.params)if(opts.paramsSerializer){let additionalQueryParams=opts.paramsSerializer(opts.params);additionalQueryParams.startsWith("?")&&(additionalQueryParams=additionalQueryParams.slice(1));let prefix=opts.url.toString().includes("?")?"&":"?";opts.url=opts.url+prefix+additionalQueryParams}else{let url=opts.url instanceof URL?opts.url:new URL(opts.url);for(let[key,value]of new URLSearchParams(opts.params))url.searchParams.append(key,value);opts.url=url}typeof options.maxContentLength=="number"&&(opts.size=options.maxContentLength),typeof options.maxRedirects=="number"&&(opts.follow=options.maxRedirects);let shouldDirectlyPassData=typeof opts.data=="string"||opts.data instanceof ArrayBuffer||opts.data instanceof Blob||globalThis.File&&opts.data instanceof File||opts.data instanceof FormData||opts.data instanceof stream_1.Readable||opts.data instanceof ReadableStream||opts.data instanceof String||opts.data instanceof URLSearchParams||ArrayBuffer.isView(opts.data)||["Blob","File","FormData"].includes(opts.data?.constructor?.name||"");if(opts.multipart?.length){let boundary=await randomUUID();preparedHeaders.set("content-type",`multipart/related; boundary=${boundary}`),opts.body=stream_1.Readable.from(this.getMultipartRequest(opts.multipart,boundary))}else shouldDirectlyPassData?opts.body=opts.data:typeof opts.data=="object"?preparedHeaders.get("Content-Type")==="application/x-www-form-urlencoded"?opts.body=opts.paramsSerializer?opts.paramsSerializer(opts.data):new URLSearchParams(opts.data):(preparedHeaders.has("content-type")||preparedHeaders.set("content-type","application/json"),opts.body=JSON.stringify(opts.data)):opts.data&&(opts.body=opts.data);opts.validateStatus=opts.validateStatus||this.validateStatus,opts.responseType=opts.responseType||"unknown",!preparedHeaders.has("accept")&&opts.responseType==="json"&&preparedHeaders.set("accept","application/json");let proxy=opts.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!opts.agent)if(proxy&&this.#urlMayUseProxy(opts.url,opts.noProxy)){let HttpsProxyAgent=await _a2.#getProxyAgent();this.agentCache.has(proxy)?opts.agent=this.agentCache.get(proxy):(opts.agent=new HttpsProxyAgent(proxy,{cert:opts.cert,key:opts.key}),this.agentCache.set(proxy,opts.agent))}else opts.cert&&opts.key&&(this.agentCache.has(opts.key)?opts.agent=this.agentCache.get(opts.key):(opts.agent=new https_1.Agent({cert:opts.cert,key:opts.key}),this.agentCache.set(opts.key,opts.agent)));return typeof opts.errorRedactor!="function"&&opts.errorRedactor!==!1&&(opts.errorRedactor=common_js_1.defaultErrorRedactor),opts.body&&!("duplex"in opts)&&(opts.duplex="half"),this.#appendTimeoutToSignal(opts),Object.assign(opts,{headers:preparedHeaders,url:opts.url instanceof URL?opts.url:new URL(opts.url)})}#appendTimeoutToSignal(opts){if(opts.timeout){let timeoutSignal=AbortSignal.timeout(opts.timeout);opts.signal&&!opts.signal.aborted?opts.signal=AbortSignal.any([opts.signal,timeoutSignal]):opts.signal=timeoutSignal}}validateStatus(status){return status>=200&&status<300}async getResponseDataFromContentType(response){let contentType=response.headers.get("Content-Type");if(contentType===null)return response.text();if(contentType=contentType.toLowerCase(),contentType.includes("application/json")){let data=await response.text();try{data=JSON.parse(data)}catch{}return data}else return contentType.match(/^text\//)?response.text():response.blob()}async*getMultipartRequest(multipartOptions,boundary){let finale=`--${boundary}--`;for(let currentPart of multipartOptions){let partContentType=currentPart.headers.get("Content-Type")||"application/octet-stream";yield`--${boundary}\r
4
4
  Content-Type: ${partContentType}\r
5
5
  \r
@@ -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{getShellConfig}from"./chunk-PUWEQK2W.js";import{getOverflowPatterns}from"./chunk-PBN2CATL.js";import{getApiKeyEnvVars}from"./chunk-RKJNJ3GI.js";import{normalizeProviderError}from"./chunk-TAV6QZFM.js";import{extract429RetryAfterMs}from"./chunk-PELNNWGO.js";import{PROVIDER_NOT_CONFIGURED_PREFIX,USAGE_LIMIT_EXHAUSTION,isOAuthRefreshUnavailableError,normalizeProviderId}from"./chunk-E5YUVGLQ.js";var PRE_COMMIT_EVENT_TYPES=new Set(["start","text_start","thinking_start","toolcall_start"]);function isCommittedRotationOutput(event){return!PRE_COMMIT_EVENT_TYPES.has(event.type)}function isRotationStreamStart(event){return event.type==="start"}function rotationErrorFromEvent(event){if(event.type!=="error")return;let failure=new Error(event.error.errorMessage??"provider stream error"),status=event.error.providerDiagnostic?.httpStatus;return status===void 0?failure:Object.assign(failure,{status})}function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}var FAMILY_KEY=/^(?:opus|sonnet|haiku|fable|mythos)$/,MODEL_FAMILY_LIMIT=/\b(opus|sonnet|haiku|fable|mythos)(?:\s+\d+(?:\.\d+)?)?(?:\s+(?:weekly|daily|monthly|session|\d+-hour))?\s+limit\b/i;function rateLimitModelFamily(text){return MODEL_FAMILY_LIMIT.exec(text)?.[1]?.toLowerCase()}function inFamily(modelId,family){return new RegExp(`(?:^|[^a-z])${family}(?:[^a-z]|$)`,"i").test(modelId)}function modelBlockKey(family,modelId){return inFamily(modelId,family)?family:modelId}function applies(key,modelId){return key===modelId||FAMILY_KEY.test(key)&&inFamily(modelId,key)}function activeModelBlockUntil(blocks,modelId,now){if(blocks===void 0||modelId===void 0)return;let until;for(let[key,block]of Object.entries(blocks))block.blockedUntil>now&&applies(key,modelId)&&(until===void 0||block.blockedUntil>until)&&(until=block.blockedUntil);return until}function pruneModelBlocks(blocks,now,servedModelId){if(blocks===void 0)return;let kept=Object.entries(blocks).filter(([key,block])=>block.blockedUntil>now&&(servedModelId===void 0||!applies(key,servedModelId)));return kept.length===0?void 0:Object.fromEntries(kept)}function withModelBlock(blocks,key,blockedUntil,now){return mergeModelBlocks(pruneModelBlocks(blocks,now),{[key]:{blockedUntil}},now)??{}}function mergeModelBlocks(left,right,now){let merged=new Map(Object.entries(pruneModelBlocks(left,now)??{}));for(let[key,block]of Object.entries(pruneModelBlocks(right,now)??{}))merged.set(key,{blockedUntil:Math.max(merged.get(key)?.blockedUntil??0,block.blockedUntil)});return merged.size===0?void 0:Object.fromEntries(merged)}function describeModelBlocks(blocks,now){return Object.entries(pruneModelBlocks(blocks,now)??{}).map(([key,block])=>`blocked for ${key} until ${new Date(block.blockedUntil).toISOString()}`)}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;var MONTHS=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],RESET_AT_KEYS=new Set(["resets_at"]),RESET_AFTER_SECONDS_KEYS=new Set(["reset_after_seconds"]),RELATIVE_RE=/\b(?:resets?|try again|retry)\s+in\s+~?((?:\d+(?:\.\d+)?\s*(?:days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b(?:\s*,?\s*(?:and\s+)?)?)+)/i,RELATIVE_PART_RE=/(\d+(?:\.\d+)?)\s*(days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b/gi,CLOCK_RE=/\b(?:resets?|try again)\s+(?:at\s+|on\s+)?(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2}),?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*([ap])\.?\s?m\b\.?(?:\s*\(([A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)*)\))?/i;function usageLimitResetMs(text,nowMs){return fromJsonFields(text,nowMs)??fromRelativeProse(text)??fromClockProse(text,nowMs)}function fromJsonFields(text,nowMs){let start=text.indexOf("{");if(start<0)return;let parsed;try{parsed=JSON.parse(text.slice(start))}catch{return}let found;return walk(parsed,(key,value)=>{let ms=RESET_AT_KEYS.has(key)?absoluteFieldMs(value,nowMs):RESET_AFTER_SECONDS_KEYS.has(key)?secondsFieldMs(value):void 0;ms!==void 0&&(found===void 0||ms>found)&&(found=ms)}),found}function walk(value,visit){if(Array.isArray(value)){for(let item of value)walk(item,visit);return}if(!(typeof value!="object"||value===null))for(let[key,entry]of Object.entries(value))visit(key,entry),walk(entry,visit)}function absoluteFieldMs(value,nowMs){if(typeof value=="number"&&Number.isFinite(value)&&value>0){let epochMs=value<1e12?value*1e3:value;return Math.max(0,Math.ceil(epochMs-nowMs))}if(typeof value=="string"&&/\d{4}-\d{2}-\d{2}T/.test(value)){let epochMs=Date.parse(value);return Number.isNaN(epochMs)?void 0:Math.max(0,epochMs-nowMs)}}function secondsFieldMs(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?Math.ceil(value*1e3):void 0}function fromRelativeProse(text){let phrase=RELATIVE_RE.exec(text)?.[1];if(phrase===void 0)return;let total=0;for(let[,amount,unit]of phrase.matchAll(RELATIVE_PART_RE))total+=Number.parseFloat(amount??"0")*unitMs(unit??"");return Math.ceil(total)}function unitMs(unit){let u=unit.toLowerCase();return u.startsWith("d")?864e5:u.startsWith("h")?36e5:u==="s"||u.startsWith("sec")?1e3:6e4}function fromClockProse(text,nowMs){let match=CLOCK_RE.exec(text);if(!match)return;let[,monthName,dayText,hourText,minuteText,meridiem,zoneText]=match,hour12=Number.parseInt(hourText??"",10),minute=minuteText===void 0?0:Number.parseInt(minuteText,10);if(hour12<1||hour12>12||minute>59)return;let hour=hour12%12+(meridiem?.toLowerCase()==="p"?12:0),zone=zoneText??Intl.DateTimeFormat().resolvedOptions().timeZone;if(!isValidTimeZone(zone))return;let today=zonedParts(zone,nowMs);if(monthName!==void 0){let month=MONTHS.indexOf(monthName.toLowerCase()),day=Number.parseInt(dayText??"",10);if(month<0||day<1||day>31)return;let target2=zonedToEpoch(zone,today.year,month,day,hour,minute);return target2<=nowMs&&(target2=zonedToEpoch(zone,today.year+1,month,day,hour,minute)),target2-nowMs}let target=zonedToEpoch(zone,today.year,today.month,today.day,hour,minute);return target<=nowMs&&(target=zonedToEpoch(zone,today.year,today.month,today.day+1,hour,minute)),target-nowMs}function isValidTimeZone(zone){try{return new Intl.DateTimeFormat("en-US",{timeZone:zone}),!0}catch{return!1}}function zonedParts(zone,epochMs){let parts=new Intl.DateTimeFormat("en-US",{timeZone:zone,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(epochMs),get=type=>Number.parseInt(parts.find(part=>part.type===type)?.value??"0",10);return{year:get("year"),month:get("month")-1,day:get("day"),hour:get("hour"),minute:get("minute"),second:get("second")}}function zoneOffsetMs(zone,epochMs){let p=zonedParts(zone,epochMs);return Date.UTC(p.year,p.month,p.day,p.hour,p.minute,p.second)-Math.floor(epochMs/1e3)*1e3}function zonedToEpoch(zone,year,month,day,hour,minute){let wall=Date.UTC(year,month,day,hour,minute),first=wall-zoneOffsetMs(zone,wall);return wall-zoneOffsetMs(zone,first)}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ACCOUNT_USAGE_LIMIT_TEXT=new RegExp([...USAGE_LIMIT_EXHAUSTION.markers.map(escapeRegExp),String.raw`\b(?:hit|reached)\s+your\b[^.]*?\blimit\b`,String.raw`\busage\s+limit\s+reached\b`,String.raw`\b(?:Go|Free)UsageLimitError\b`,String.raw`\bblocking_limit\b`,String.raw`\brapid_refill_breaker\b`,String.raw`\bquota\s+exceeded\b`].join("|"),"i");function isAccountUsageLimitText(text){return ACCOUNT_USAGE_LIMIT_TEXT.test(text)}var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,RETRY_SAME_MAX_ATTEMPTS=2;function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i;function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){if(isOAuthRefreshUnavailableError(error))return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||INVALID_KEY_TEXT.test(text))return{kind:"failover",block:{reason:"auth_error"}};if(status===403)return ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};let usageLimit=isAccountUsageLimitText(text)&&!isOverflowText(text);if(status===429||RATE_LIMIT_TEXT.test(text)||usageLimit){let nowMs=context.nowMs??Date.now(),hint=extract429RetryAfterMs({status:status??429,bodyText:text},nowMs)??(usageLimit?normalized.retryAfterMs??usageLimitResetMs(text,nowMs):void 0),modelFamily=rateLimitModelFamily(text);return{kind:"failover",block:{reason:"rate_limit",...rateLimitCooldown(failureCount,hint,{baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs}),...modelFamily===void 0?{}:{modelFamily}}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="auth_error"||slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1;for(;;){let slots=await options.listSlots(),candidates=slots.filter(slot2=>!attempted.has(slot2.name)&&isAvailable(slot2,now()));if(candidates.length===0){if(lastTerminalEvent!==void 0){yield lastTerminalEvent;return}let retryAt=soonestRetryAt(slots,now());throw lastError!==void 0&&lastOriginal!==void 0?new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt}):new CredentialFailoverError({kind:"fail_request"},new Error("No credential slots available"),retryAt===void 0?{}:{retryAt})}let slot=options.select(candidates),committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts)continue;if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Aborted"))})})}import{spawn}from"child_process";var COMMAND_EXECUTION_MAX_ATTEMPTS=3,COMMAND_EXECUTION_BACKOFF_MS=[250,1e3],COMMAND_TIMEOUT_MS=1e4,COMMAND_MAX_OUTPUT_BYTES=1024*1024;function runCommandProcess(file,args,options){return new Promise(resolveOutcome=>{let spawnOptions={shell:options.shell,windowsHide:!0,...options.env===void 0?{}:{env:{...process.env,...options.env}}},child=options.stdin===void 0?spawn(file,[...args],{...spawnOptions,stdio:["ignore","pipe","ignore"]}):spawn(file,[...args],{...spawnOptions,stdio:["pipe","pipe","ignore"]}),stdout="",settled=!1,finish=outcome=>{settled||(settled=!0,clearTimeout(timer),resolveOutcome(outcome))},timer=setTimeout(()=>{child.kill("SIGTERM"),child.unref(),finish({executed:!0,value:void 0})},COMMAND_TIMEOUT_MS);child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk,!(stdout.length<=COMMAND_MAX_OUTPUT_BYTES)&&(child.kill("SIGTERM"),finish({executed:!0,value:void 0}))}),child.on("error",error=>finish({executed:error.code!=="ENOENT",value:void 0})),child.on("close",code=>{let value=stdout.trim();finish({executed:!0,value:code===0&&value?value:void 0})}),child.stdin?.end(options.stdin)})}async function executeWithConfiguredShell(command,env){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin";return await runCommandProcess(shell,commandFromStdin?args:[...args,command],{shell:!1,...commandFromStdin?{stdin:command}:{},...env===void 0?{}:{env}})}catch{return{executed:!1,value:void 0}}}async function executeCommandOnce(command,env){if(process.platform==="win32"){let configured=await executeWithConfiguredShell(command,env);if(configured.executed)return configured.value}return(await runCommandProcess(command,[],{shell:!0,...env===void 0?{}:{env}})).value}async function runConfigCommand(commandConfig,env){let command=commandConfig.slice(1);for(let attempt=0;attempt<COMMAND_EXECUTION_MAX_ATTEMPTS;attempt++){let value=await executeCommandOnce(command,env);if(value!==void 0)return value;let backoffMs=COMMAND_EXECUTION_BACKOFF_MS[attempt];backoffMs!==void 0&&await sleep(backoffMs)}}var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){return env?.[name]||process.env[name]||void 0}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0)return;resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?env===void 0?executeCommand(reference.config):runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}function executeCommand(commandConfig){let cached=commandResultCache.get(commandConfig);if(cached)return cached;let result=runConfigCommand(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}async function resolveConfigValueOrThrow(config,description,env){let resolvedValue=await resolveConfigValueUncached(config,env);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}async function resolveHeadersOrThrow(headers,description,env){if(!headers)return;let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=await resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}var MAX_ENV_SLOT_INDEX=16;function primaryEnvVar(providerId){if(normalizeProviderId(providerId)==="anthropic-subscription")return"CLAUDE_CODE_OAUTH_TOKEN";let envVars=getApiKeyEnvVars(providerId);if(!(!envVars||envVars.length===0))return envVars.find(name=>name.endsWith("_API_KEY"))??envVars[0]}function discoverEnvSlots(providerId,env){let primary=primaryEnvVar(providerId);if(!primary)return[];let slots=[],base=env(primary);base&&slots.push({name:"env",envVarName:primary,key:base,source:"env"});for(let index=2;index<=MAX_ENV_SLOT_INDEX;index++){let envVarName=`${primary}_${index}`,value=env(envVarName);value&&slots.push({name:`env-${index}`,envVarName,key:value,source:"env"})}return slots}export{sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,discoverEnvSlots,isCommittedRotationOutput,isRotationStreamStart,rotationErrorFromEvent,MAX_SLOT_BLOCK_MS,rendezvousOrder,rateLimitModelFamily,modelBlockKey,activeModelBlockUntil,pruneModelBlocks,withModelBlock,mergeModelBlocks,describeModelBlocks,usageLimitResetMs,classifyCredentialFailure,CredentialFailoverError,runCredentialFailover};
@@ -0,0 +1,16 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
+ import{CHILD_STALLED_STOP_MAX_MS_ENV,DEFAULT_HANDOFF_GRACE_MS,HANDOFF_GRACE_MS_ENV,HOST_DAEMON_DIR_ENV,HOST_INSTANCE_ID_ENV,IdleExitDecider,MAX_RPC_LINE_CHARACTERS,MAX_SOCKET_PATH_BYTES,PUBLIC_SOCKET_IDENTITY_FILE,SOCKET_SECRET_FILE_ENV,STOP_STALL_EVIDENCE_MAX_AGE_MS,acquireOwnershipSafeLock,ageOf,attachJsonlLineReader,authenticateSocket,childStalledStopMaxMs,classifyEndpointOwnership,clearStopProgress,createHostDaemonPaths,createSocketSecret,ensureSocketSecret,errorMessage,generationPaths,hostLoopStalled,hostOwnerGone,parseIdleExitMs,readHostOwner,readJsonObject,recentStall,releaseGeneration,resolveHostPolicy,resolveSocketTransportAddress,sameHostOwner,sendSocketHandshake,serializeJsonLine,shieldSocketDuringClose,socketSecretPath,statSocketIdentity,supervisorLog,unlinkOwnedSocket,writeJsonAtomic,writeSocketIdentityFile,writeStderrLine,writeStopProgress}from"./chunk-DL7EFVT2.js";import{processIsLive,readProcessIdentity,readProcessStartTime}from"./chunk-ZRWOLP4E.js";import{require_signal_exit}from"./chunk-U3VOXCGP.js";import{DISPLAY_VERSION,VERSION,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-463OK2Y4.js";import{__toESM}from"./chunk-IKOFCODM.js";import{randomUUID as randomUUID2}from"node:crypto";import{realpathSync}from"node:fs";import{join as join4}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var HostAdmission=class{constructor(info){this.stopped=!1,this.listeners=new Set,this.replies=Promise.resolve(),this.info=info}get stopping(){return this.stopped}protocol(){return{...this.info,lifecycle:this.stopped?"stopping":"ready"}}observe(info){this.info=info}stop(){this.stopped||(this.stopped=!0,this.replies=Promise.all([...this.listeners].map(listener=>listener())).then(()=>{}))}async flush(){let timer;try{await Promise.race([this.replies,new Promise(resolve2=>{timer=setTimeout(resolve2,2e3)})])}finally{clearTimeout(timer)}}onStop(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}};function hostStoppingResponse(id,command,admission){return{...typeof id=="string"?{id}:{},type:"response",command,success:!1,error:"host_stopping",errorCode:"host_stopping",errorData:{instanceId:admission.protocol().instanceId}}}var import_signal_exit=__toESM(require_signal_exit(),1);import{appendFileSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,statSync,utimesSync,writeFileSync}from"node:fs";import{join}from"node:path";var PROCESS_CRASH_RECORD_LIMIT=50,PROCESS_MARKER_HEARTBEAT_MS=6e4,FILE_MODE=384,DIR_MODE=448,MARKER_SUFFIX=".json";function processCrashPaths(agentDir){let dir=join(agentDir,"process-crashes");return{dir,liveDir:join(dir,"live"),recordsFile:join(dir,"crashes.jsonl")}}function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}function recordProcessLifetime(agentDir,kind,options){return sweepDeadProcessMarkers(agentDir,options),options.supervised?()=>{}:installProcessLifetimeMarker(agentDir,kind,options)}function installProcessLifetimeMarker(agentDir,kind,options={}){let pid=options.pid??process.pid,now=options.now??Date.now,file=join(processCrashPaths(agentDir).liveDir,`${pid}${MARKER_SUFFIX}`),marker={kind,pid,startedAt:now(),...crashingRuntimeVersions()};try{mkdirSync(processCrashPaths(agentDir).liveDir,{recursive:!0,mode:DIR_MODE}),writeFileSync(file,`${JSON.stringify(marker)}
3
+ `,{mode:FILE_MODE})}catch{return()=>{}}let heartbeat=setInterval(()=>{try{let at=new Date(now());utimesSync(file,at,at)}catch{}},options.heartbeatMs??PROCESS_MARKER_HEARTBEAT_MS);heartbeat.unref();let disposed=!1,dispose=()=>{disposed||(disposed=!0,clearInterval(heartbeat),process.off("exit",onProcessExit),removeSignalHook(),rmSync(file,{force:!0}))},onProcessExit=()=>{try{dispose()}catch{}};process.on("exit",onProcessExit);let removeSignalHook=(0,import_signal_exit.default)(onProcessExit);return dispose}function sweepDeadProcessMarkers(agentDir,options={}){let paths=processCrashPaths(agentDir),selfPid=options.pid??process.pid,isAlive=options.isAlive??isProcessAlive,names;try{names=readdirSync(paths.liveDir)}catch{return 0}let recorded=0;for(let name of names){if(!name.endsWith(MARKER_SUFFIX))continue;let pid=Number(name.slice(0,-MARKER_SUFFIX.length));if(!Number.isSafeInteger(pid)||pid<=0||pid===selfPid||isAlive(pid))continue;let claimed=join(paths.liveDir,`${name}.${selfPid}.sweep`);try{renameSync(join(paths.liveDir,name),claimed)}catch{continue}try{let record2=crashRecordFromMarker(readFileSync(claimed,"utf8"),statSync(claimed).mtimeMs);record2!==void 0&&(appendProcessCrashRecord(paths,record2),recorded+=1)}catch{}finally{rmSync(claimed,{force:!0})}}return recorded}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function crashRecordFromMarker(raw,lastHeartbeatMs){let value=JSON.parse(raw);if(typeof value!="object"||value===null)return;let kind=Reflect.get(value,"kind"),startedAt=Reflect.get(value,"startedAt"),senpiVersion=Reflect.get(value,"senpiVersion"),bunVersion=Reflect.get(value,"bunVersion"),productVersion=Reflect.get(value,"productVersion");if(!(typeof kind!="string"||typeof startedAt!="number"||typeof senpiVersion!="string"))return{at:new Date(lastHeartbeatMs).toISOString(),kind,detection:"unclean_exit",uptimeMs:Math.max(0,Math.round(lastHeartbeatMs-startedAt)),...typeof bunVersion=="string"?{bunVersion}:{},senpiVersion,...typeof productVersion=="string"?{productVersion}:{}}}function appendProcessCrashRecord(paths,record2){mkdirSync(paths.dir,{recursive:!0,mode:DIR_MODE}),appendFileSync(paths.recordsFile,`${JSON.stringify(record2)}
4
+ `,{mode:FILE_MODE});let records=readProcessCrashRecordsFrom(paths.recordsFile);if(records.length<=PROCESS_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-PROCESS_CRASH_RECORD_LIMIT);writeFileSync(paths.recordsFile,`${kept.join(`
5
+ `)}
6
+ `,{mode:FILE_MODE})}function readProcessCrashRecordsFrom(file){return readFileSync(file,"utf8").split(`
7
+ `).filter(line=>line.trim()!=="")}import{appendFileSync as appendFileSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var HOST_CRASH_RECORD_LIMIT=50,CRASH_RECORD_FILE_MODE=384,TERMINAL_RECORD_LOCK_WAIT_MS=500;function hostCrashRecordFile(daemonDir){return join2(daemonDir,"crashes.jsonl")}function isHostCrash(record2){return record2.kind!=="rpc-host-watchdog"&&record2.detection!=="engine_stop"}function recordHostCrash(daemonDir,record2){try{mkdirSync2(daemonDir,{recursive:!0,mode:448}),appendFileSync2(hostCrashRecordFile(daemonDir),`${JSON.stringify(record2)}
8
+ `,{mode:CRASH_RECORD_FILE_MODE}),pruneHostCrashRecords(daemonDir)}catch{}}async function recordTerminalHostRecord(daemonDir,record2){let release=await acquireRecordLock(daemonDir);try{(!(record2.generation!==void 0&&readHostCrashRecords(daemonDir).some(existing=>existing.kind==="rpc-host"&&existing.generation===record2.generation))||release===void 0)&&recordHostCrash(daemonDir,{...record2,kind:"rpc-host"})}finally{await release?.().catch(()=>{})}}async function acquireRecordLock(daemonDir){try{return mkdirSync2(daemonDir,{recursive:!0,mode:448}),await acquireOwnershipSafeLock(join2(daemonDir,"crashes.lock"),{retries:{retries:Math.ceil(TERMINAL_RECORD_LOCK_WAIT_MS/50),minTimeout:20,maxTimeout:50}})}catch{return}}function readHostCrashRecords(daemonDir){let raw;try{raw=readFileSync2(hostCrashRecordFile(daemonDir),"utf8")}catch{return[]}let records=[];for(let line of raw.split(`
9
+ `))if(line.trim()!=="")try{let value=JSON.parse(line);typeof value=="object"&&value!==null&&typeof Reflect.get(value,"at")=="string"&&records.push(value)}catch{}return records}function pruneHostCrashRecords(daemonDir){let records=readHostCrashRecords(daemonDir);if(records.length<=HOST_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-HOST_CRASH_RECORD_LIMIT);writeFileSync2(hostCrashRecordFile(daemonDir),`${kept.map(r=>JSON.stringify(r)).join(`
10
+ `)}
11
+ `,{mode:CRASH_RECORD_FILE_MODE})}import{rm}from"node:fs/promises";var STOP_INTENT_MAX_AGE_MS=12e4,CHILD_STOP_TIMEOUT_MS=5e3,CHILD_KILL_EXIT_TIMEOUT_MS=3e4,SENDER_KINDS=new Set(["ensure","supervisor","stop","successor","handoff"]);async function writeStopIntent(generation,intent,log=message=>{process.stderr.write(`${message}
12
+ `)}){try{await writeJsonAtomic(generation.stopIntentFile,intent)}catch(cause){log(`could not record the stop intent for ${generation.dir}: ${cause instanceof Error?cause.message:cause}`)}}async function readStopIntent(generation,options={}){let raw=await readJsonObject(generation.stopIntentFile);if(raw===void 0)return;let intent=parseStopIntent(raw),age=ageOf(raw.at,options.now??Date.now());if(intent!==void 0&&age!==void 0&&age<=(options.maxAgeMs??STOP_INTENT_MAX_AGE_MS))return intent;await clearStopIntent(generation)}async function consumeStopIntent(generation,now=Date.now()){let intent=await readStopIntent(generation,{now});return intent!==void 0&&await clearStopIntent(generation),intent}async function clearStopIntent(generation){await rm(generation.stopIntentFile,{force:!0}).catch(()=>{})}function layeredSupervisorIntent(outer,supervisor,stop){return outer===void 0?{sender:supervisor,signal:"SIGTERM",...stop}:{sender:outer.sender,chain:[...outer.chain??[outer.sender],supervisor],targetPid:stop.targetPid,reason:`${outer.reason} -> ${stop.reason}`,signal:"SIGTERM",at:stop.at}}function parseStopIntent(raw){let sender=parseSender(raw.sender),chain=Array.isArray(raw.chain)?raw.chain.map(parseSender):void 0;if(!(sender===void 0||chain?.some(entry=>entry===void 0))&&!(typeof raw.reason!="string"||typeof raw.at!="string"))return{sender,...chain?{chain:chain.filter(entry=>entry!==void 0)}:{},targetPid:typeof raw.targetPid=="number"?raw.targetPid:0,reason:raw.reason,signal:typeof raw.signal=="string"?raw.signal:"SIGTERM",at:raw.at}}function parseSender(value){if(typeof value!="object"||value===null)return;let pid=Reflect.get(value,"pid"),kind=Reflect.get(value,"kind"),generation=Reflect.get(value,"generation");if(!(typeof pid!="number"||typeof kind!="string"||!isSenderKind(kind)))return{pid,kind,...typeof generation=="string"?{generation}:{}}}function isSenderKind(kind){return SENDER_KINDS.has(kind)}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}async function noteChildExit(context){let now=context.now??Date.now(),intent=await consumeStopIntent(context.generation,now).catch(()=>{}),outcome=describeExit(context,intent);if(outcome===void 0)return;let stall=await recentStall(context.generation,now,STOP_STALL_EVIDENCE_MAX_AGE_MS).catch(()=>{});await recordTerminalHostRecord(context.daemonDir,{at:new Date(now).toISOString(),...context.signal===null?{code:context.code??void 0}:{signal:context.signal},uptimeMs:Math.max(0,now-context.childStartedAt),kind:"rpc-host",generation:context.instanceId,...outcome,...stall?{stall:{driftMs:stall.driftMs,at:stall.at,attributedSessionId:stall.sessionId}}:{},...crashingRuntimeVersions()}).catch(()=>{})}function describeExit(context,intent){return intent!==void 0?{detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:intent.reason,stopIntent:!0}:context.shutdown!==void 0?{detection:"engine_stop",sender:context.shutdown.supervisor,reason:context.shutdown.reason,stopIntent:!1}:classifyChildExit(context.code,context.signal).exitCode===0?void 0:{detection:context.signal===null||SELF_INFLICTED_SIGNALS.has(context.signal)?"supervisor":"external",stopIntent:!1}}var SELF_INFLICTED_SIGNALS=new Set(["SIGSEGV","SIGBUS","SIGABRT","SIGILL","SIGFPE","SIGTRAP","SIGSYS"]);async function noteEscalatedStop(daemonDir,instanceId,intent,now=Date.now()){await recordTerminalHostRecord(daemonDir,{at:new Date(now).toISOString(),signal:"SIGKILL",kind:"rpc-host",generation:instanceId,detection:"engine_stop",sender:intent.sender,...intent.chain?{chain:intent.chain}:{},reason:`${intent.reason}; supervisor_escalated`,stopIntent:!0}).catch(()=>{})}function hostCrashCleanupPaths(targets){let publicEntry=targets.platform==="win32"?[targets.publicSocket]:[];return targets.successor?publicEntry:[targets.generationPidFile,targets.settingsFile,...publicEntry,targets.pointerFile]}import{watch}from"node:fs";import{createConnection,Socket}from"node:net";var OBSERVE_REQUEST_FIELD="observe",OBSERVING_COMMANDS=new Set(["get_protocol_info","list_sessions"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record2=request;return record2.type==="warm"?!0:record2[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record2.type)}var MAX_CLASSIFIED_LINE_BYTES=64*1024,NEWLINE=10,ClientOccupancy=class{constructor(onAttach){this.clients=new Set,this.observers=new Set,this.attached=new Set,this.closed=!1,this.onAttach=onAttach}get attachedCount(){return this.attached.size}get unclassifiedCount(){return this.clients.size-this.observers.size-this.attached.size}admit(client){if(this.closed)return client.destroy(),!1;this.clients.add(client);let pending=Buffer.alloc(0),attach=()=>{client.off("data",classify),pending=Buffer.alloc(0),this.observers.delete(client),this.attached.add(client),this.onAttach()},classify=chunk=>{pending=Buffer.concat([pending,chunk]);for(let newline=pending.indexOf(NEWLINE);newline!==-1;newline=pending.indexOf(NEWLINE)){let line=pending.subarray(0,newline).toString("utf8");if(pending=pending.subarray(newline+1),!isObservingRequest(line)){attach();return}this.observers.add(client)}pending.length>MAX_CLASSIFIED_LINE_BYTES&&attach()};return client.on("data",classify),!0}release(client){let unclassified=this.clients.has(client)&&!this.observers.has(client)&&!this.attached.has(client);return this.clients.delete(client),this.observers.delete(client),this.attached.delete(client),unclassified}destroyAll(){this.closed=!0;for(let client of this.clients)client.destroy()}};var SessionRunActivity=class{#running=new Set;observe(line){let event=parseHostEvent(line);if(event===void 0)return!1;if(event.type==="agent_start")this.#running.add(event.sessionId);else if(event.type==="agent_settled"||event.type==="session_closed")this.#running.delete(event.sessionId);else return!1;return!0}get busySessions(){return this.#running.size}};function parseHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId}=event;return typeof sessionId=="string"?{type,sessionId}:void 0}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}var SupervisorActivity=class{constructor(options){this.runs=new SessionRunActivity,this.options=options,this.decider=new IdleExitDecider(options.idleExitMs),this.clients=new ClientOccupancy(()=>this.refresh()),this.observerLink=createObserverLink({open:()=>this.connectObserver(),settled:options.settled,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}})}current(){return{connections:this.clients.attachedCount,activeTurns:activeTurnsForIdleDecision({healthy:this.observerLink.healthy(),unhealthySince:this.observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:this.decider.idleExitMs,observedBusy:this.runs.busySessions})}}refresh(){let current=this.current();return(current.connections>0||current.activeTurns>0||this.clients.unclassifiedCount>0)&&this.options.onActivity?.(),this.decider.update(current)}quiescent(){return this.observerLink.healthy()&&this.runs.busySessions===0&&this.clients.attachedCount===0&&this.clients.unclassifiedCount===0}openObserver(){return this.observerLink.open()}stopObserver(){this.observerLink.stop(),this.observerSocket?.destroy()}async connectObserver(){let secret=this.options.internalSecret,next=createConnection(resolveSocketTransportAddress(this.options.internalSocket,process.platform,secret));return secret&&sendSocketHandshake(next,secret),await waitForConnect(next,5e3),this.observerSocket=next,attachJsonlLineReader(next,line=>this.observeHostEvent(line),{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{let lost=()=>{handler(),this.options.onActivity?.()};next.once("close",lost),next.once("error",lost)}}}observeHostEvent(line){this.runs.observe(line)&&this.refresh()}},OWNER_EXIT_GRACE_MS=2e3,OWNER_PROBE_MAX_INTERVAL_MS=5e3,SupervisorOwner=class{constructor(generationDir){this.watchFailed=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.gone=!1,this.revision=0,this.stopped=!1,this.idle=new IdleExitDecider(OWNER_EXIT_GRACE_MS,()=>performance.now()),this.generationDir=generationDir}async start(fd){if(await this.reload(),!(fd===void 0||this.owner==null))try{let pipe=new Socket({fd,readable:!0,writable:!1});this.pipe=pipe;let bound=this.owner,failed=!1,eof=()=>{!failed&&!this.stopped&&sameHostOwner(this.owner,bound)&&(this.gone=!0)};pipe.once("end",eof),process.platform==="win32"&&pipe.once("close",eof),pipe.once("error",()=>{failed=!0,this.pipe===pipe&&(this.pipe=void 0),pipe.destroy()}),pipe.resume()}catch{this.pipe=void 0}}async reload(){let revision=++this.revision,next=await readHostOwner(this.generationDir);if(!(this.stopped||revision!==this.revision)){if(sameHostOwner(this.owner,next)||(this.pipe?.destroy(),this.pipe=void 0,this.gone=!1,this.nextProbeAt=0,this.probeIntervalMs=1e3,this.activity()),this.owner=next,next==null)this.watcher?.close(),this.watcher=void 0;else if(!this.watcher&&!this.watchFailed)try{this.watcher=watch(this.generationDir,(_event,filename)=>{filename?.toString()==="owner.json"&&this.reload()}),this.watcher.once("error",()=>{this.watchFailed=!0,this.watcher?.close(),this.watcher=void 0})}catch{this.watchFailed=!0}}}activity(){this.idle.update({connections:1,activeTurns:0})}async shouldExit(activity){this.watcher||await this.reload();let owner=this.owner,revision=this.revision;if(owner!=null&&!this.pipe&&!this.gone&&performance.now()>=this.nextProbeAt){let gone=await hostOwnerGone(owner);if(this.stopped||revision!==this.revision)return!1;this.gone=gone,this.nextProbeAt=performance.now()+this.probeIntervalMs,this.probeIntervalMs=Math.min(OWNER_PROBE_MAX_INTERVAL_MS,this.probeIntervalMs*2)}let quiet=this.gone&&owner!=null&&activity.quiescent();if(this.idle.update({connections:quiet?0:1,activeTurns:0})!=="exit")return!1;let current=await readHostOwner(this.generationDir);return!this.stopped&&revision===this.revision&&sameHostOwner(owner,current)&&activity.quiescent()}stop(){this.stopped=!0,this.watcher?.close(),this.pipe?.destroy()}};function waitForConnect(socket,timeoutMs){return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve2()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0||process.platform==="win32")return()=>{};let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function ignore(){}var SupervisorDrain=class{constructor(child,shuttingDown,beginStopping=()=>{}){this.draining=!1,this.child=child,this.shuttingDown=shuttingDown,this.beginStopping=beginStopping}get active(){return this.draining}drain(){if(this.draining||this.shuttingDown())return;this.draining=!0,this.beginStopping(),supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??6e5;this.graceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),this.requestChildDrain()},graceMs),this.graceTimer.unref(),this.requestChildDrain()}stop(){this.graceTimer&&clearTimeout(this.graceTimer)}requestChildDrain(){let{child}=this;if(child.pid!==void 0&&child.exitCode===null&&child.signalCode===null)try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`)}}};function drainOnPublicSocketLoss(path,identity,settled,drain,onReplaced){return watchForSupersession({path,identity,settled},loss=>{loss==="replaced"&&onReplaced(),supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drain.drain()})}async function watchWin32ChildIdentity(child,shuttingDown,onGone){let pid=child.pid;if(pid===void 0)return()=>{};let childStartTime=await readProcessStartTime(pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checking=!1,timer=setInterval(()=>{shuttingDown()||checking||child.exitCode!==null||child.signalCode!==null||(checking=!0,readProcessStartTime(pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&&currentStartTime!==void 0&&currentStartTime!==childStartTime||missingIdentityChecks>=2)&&onGone()}).catch(()=>{}).finally(()=>{checking=!1}))},500);return timer.unref?.(),()=>clearInterval(timer)}import{spawn}from"node:child_process";import{Socket as Socket3}from"node:net";import{extname}from"node:path";function runtimeExecArgv(execArgv=process.execArgv,bun=process.versions.bun!==void 0){let args=[];for(let index=0;index<execArgv.length;index++){let arg=execArgv[index];if(bun){if(arg==="-e"||arg==="--eval"||arg==="-p"||arg==="--print"||arg==="-pe"){index++;continue}if(arg.startsWith("-e")||arg.startsWith("-p"))continue}if(arg==="-e"||arg==="--eval"||arg==="-pe"||arg==="--input-type"||arg==="--input_type"){index++;continue}if(arg==="-p"||arg==="--print"){execArgv[index+1]!==void 0&&!execArgv[index+1].startsWith("-")&&index++;continue}arg==="-i"||arg==="--interactive"||arg.startsWith("--interactive=")||arg.startsWith("--eval=")||arg.startsWith("--print=")||arg.startsWith("--input-type=")||arg.startsWith("--input_type=")||args.push(arg)}return args}import{existsSync,readFileSync as readFileSync3}from"node:fs";import{dirname,resolve}from"node:path";import{fileURLToPath}from"node:url";function resolveCliMainPath(modulePath=fileURLToPath(import.meta.url),bundled=isBundledNode){let declared=bundled?resolveDeclaredCliEntry(modulePath):void 0;if(declared!==void 0)return declared;let extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname(modulePath),"..","..",`cli-main${extension}`);return existsSync(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(existsSync(manifestPath)){try{let declared=JSON.parse(readFileSync3(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(existsSync(entry))return entry}}catch{}return}let parent=dirname(dir);if(parent===dir)return;dir=parent}}import{rmSync as rmSync2}from"node:fs";import{rm as rm2}from"node:fs/promises";import{Socket as Socket2}from"node:net";var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PPID_INTERVAL_MS=250,HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function readHostWatchdogConfig(env=process.env){let fd=parsePositiveInteger(env[HOST_WATCH_FD_ENV]),ppid=parsePositiveInteger(env[HOST_WATCH_PPID_ENV]);if(fd===void 0&&ppid===void 0)return;let scratchDir=env[HOST_SCRATCH_DIR_ENV],cleanupPaths=env[HOST_CLEANUP_PATHS_ENV]?.split(`
13
+ `).filter(Boolean),publicSocket=env[HOST_PUBLIC_SOCKET_ENV],daemonDir=env[HOST_DAEMON_DIR_ENV],instanceId=env[HOST_INSTANCE_ID_ENV];return{fd,ppid,scratchDir:scratchDir===void 0||scratchDir===""?void 0:scratchDir,cleanupPaths,publicSocket:publicSocket===""?void 0:publicSocket,...daemonDir&&instanceId?{daemonDir,instanceId}:{}}}function readHostWatchdogConfigFromBrandEnv(){return readHostWatchdogConfig({[HOST_WATCH_FD_ENV]:process.env[HOST_WATCH_FD_ENV]??envValue("RPC_HOST_WATCH_FD"),[HOST_WATCH_PPID_ENV]:process.env[HOST_WATCH_PPID_ENV]??envValue("RPC_HOST_WATCH_PPID"),[HOST_SCRATCH_DIR_ENV]:process.env[HOST_SCRATCH_DIR_ENV]??envValue("RPC_HOST_SCRATCH_DIR"),[HOST_PUBLIC_SOCKET_ENV]:process.env[HOST_PUBLIC_SOCKET_ENV]??envValue("RPC_HOST_PUBLIC_SOCKET"),[HOST_CLEANUP_PATHS_ENV]:process.env[HOST_CLEANUP_PATHS_ENV]??envValue("RPC_HOST_CLEANUP_PATHS"),[HOST_DAEMON_DIR_ENV]:process.env[HOST_DAEMON_DIR_ENV],[HOST_INSTANCE_ID_ENV]:process.env[HOST_INSTANCE_ID_ENV]})}function armHostWatchdog(config,onSupervisorGone){if(!config)return()=>{};let fire=reason=>{disarm(),config.daemonDir!==void 0&&config.instanceId!==void 0&&recordHostCrash(config.daemonDir,{at:new Date().toISOString(),uptimeMs:Math.round(process.uptime()*1e3),kind:"rpc-host-watchdog",generation:config.instanceId,reason});let captured=captureBeforeCleanup(config);if(process.platform==="win32"){let cleanup=captured.then(()=>cleanupWatchdogPaths(config));onSupervisorGone(reason,cleanup)}else captured.then(()=>cleanupWatchdogPaths(config)).finally(()=>onSupervisorGone(reason))},disarmers=[],disarm=()=>{for(let stop of disarmers.splice(0))stop()};return config.fd!==void 0&&disarmers.push(watchFdForEof(config.fd,fire)),config.ppid!==void 0&&disarmers.push(watchPpid(config.ppid,fire)),disarm}function watchFdForEof(fd,fire){let stream,streamFailed=!1,fired=!1,fireOnce=reason=>{fired||(fired=!0,fire(reason))};try{stream=new Socket2({fd,readable:!0,writable:!1})}catch{return()=>{}}stream.resume();let onEnd=()=>fireOnce(`supervisor pipe fd ${fd} closed`),onClose=()=>{streamFailed||onEnd()},onError=()=>{streamFailed=!0};return stream.once("end",onEnd),process.platform==="win32"&&stream.once("close",onClose),stream.once("error",onError),()=>{stream.off("end",onEnd),stream.off("close",onClose),stream.off("error",onError),stream.destroy()}}function watchPpid(supervisorPid,fire){if(supervisorPid===process.pid)return()=>{};let timer=setInterval(()=>{if(!processAlive(supervisorPid)){fire(`supervisor pid ${supervisorPid} is gone (ppid=${process.ppid})`);return}process.ppid!==supervisorPid&&fire(`supervisor pid ${supervisorPid} is gone (ppid=${process.ppid})`)},HOST_WATCH_PPID_INTERVAL_MS);return timer.unref?.(),()=>clearInterval(timer)}function processAlive(pid){try{return process.kill(pid,0),!0}catch(cause){return cause instanceof Error&&"code"in cause&&cause.code!=="ESRCH"}}function captureBeforeCleanup(config){return config.beforeCleanup===void 0?Promise.resolve():Promise.resolve().then(config.beforeCleanup).catch(()=>{})}async function cleanupWatchdogPaths(config){let paths=[...config.cleanupPaths??[],...config.scratchDir?[config.scratchDir]:[]];for(let path of paths)try{process.platform==="win32"?rmSync2(path,{recursive:!0,force:!0,maxRetries:10,retryDelay:100}):await rm2(path,{recursive:!0,force:!0})}catch{}}var INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,ownerFd,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--owner-fd"&&index+1<argv.length){if(ownerFd=Number(argv[++index]),!Number.isSafeInteger(ownerFd)||ownerFd<3)return;continue}if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,ownerFd,bindSocket,replaceIdentity}}var OWNER_WATCH_FD=3,ownerPipes=new Set;function keepOwnerPipe(child){let pipe=child.stdio[OWNER_WATCH_FD];if(!(pipe instanceof Socket3))throw new Error("RPC owner pipe was not inherited");ownerPipes.add(pipe),pipe.on("error",()=>{}),pipe.unref(),child.once("exit",()=>{ownerPipes.delete(pipe),pipe.destroy()})}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...runtimeExecArgv(),resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}var HOST_CHILD_WATCH_FD=3;function spawnHostChild(options){let{launch,internalSocket,internal,internalSecret,publicSocket}=options,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket));return spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:options.daemonDir,[HOST_INSTANCE_ID_ENV]:options.instanceId,[HOST_WATCH_FD_ENV]:String(HOST_CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},...internalSecret?{[SOCKET_SECRET_FILE_ENV]:internal.secretPath}:{},[HOST_CLEANUP_PATHS_ENV]:options.cleanupPaths.join(`
14
+ `),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:["ignore","ignore","inherit","pipe"],windowsHide:!0})}import{access,chmod,mkdir,rename,unlink}from"node:fs/promises";import{createConnection as createConnection2,createServer}from"node:net";import{dirname as dirname2}from"node:path";import{StringDecoder}from"node:string_decoder";function proxyWithAdmission(client,internal,admission){let pending=[],refused=new Set,protocols=0,refusals=Promise.resolve(),unsubscribe=admission.onStop(()=>(refusals=refusePending(),refusals));async function refusePending(){let ids=pending.splice(0);for(let id of ids)refused.add(id);try{for(let id of ids)await write(client,serializeJsonLine(hostStoppingResponse(id,"open_session",admission)))}catch{fail()}}client.once("close",()=>{unsubscribe(),internal?.destroy()});let fail=()=>{internal?.destroy(),client.destroy()};client.once("error",fail),internal?.once("error",()=>{admission.stopping||fail()}),requests().catch(()=>{admission.stopping||fail()}),internal&&responses(internal).catch(()=>{admission.stopping||fail()});async function requests(){for await(let line of lines(client,MAX_RPC_LINE_CHARACTERS)){if(line===void 0){await write(client,serializeJsonLine({type:"response",command:"parse",success:!1,error:`RPC input line exceeds ${MAX_RPC_LINE_CHARACTERS} characters.`}));continue}let request=record(line);admission.stopping&&request?.type==="get_protocol_info"?await write(client,serializeJsonLine({id:request.id,type:"response",command:request.type,success:!0,data:admission.protocol()})):admission.stopping&&(request?.type==="open_session"||!internal)?await write(client,serializeJsonLine(hostStoppingResponse(request?.id,String(request?.type??"parse"),admission))):internal&&(request?.type==="open_session"&&pending.push(request.id),request?.type==="get_protocol_info"&&protocols++,await write(internal,`${line}
15
+ `))}internal?.end()}async function responses(source){let fragments=[];for await(let chunk of source){let newline=chunk.lastIndexOf(10);if(newline===-1){fragments.push(chunk);continue}let complete=chunk.subarray(0,newline+1);if(pending.length===0&&protocols===0&&refused.size===0){client.cork();let written;try{for(let fragment of fragments)client.write(fragment);written=write(client,complete)}finally{client.uncork()}await written}else{let batch=fragments.length>0?Buffer.concat([...fragments,complete]):complete;await write(client,filterReplies(batch))}fragments=newline+1<chunk.length?[chunk.subarray(newline+1)]:[]}fragments.length>0&&await write(client,filterReplies(Buffer.concat(fragments))),await refusals,client.end(()=>client.destroy())}function filterReplies(batch){if(pending.length===0&&protocols===0&&refused.size===0)return batch;let output=[],changed=!1;for(let start=0;start<batch.length;){let newline=batch.indexOf(10,start),end=newline===-1?batch.length:newline+1,line=batch.subarray(start,end);start=end;let response=line.includes('"open_session"')||line.includes('"get_protocol_info"')?record(line.toString("utf8")):void 0;if(response?.type==="response"&&response.command==="open_session"){if(refused.has(response.id)){changed=!0;continue}let index=pending.indexOf(response.id);index!==-1&&pending.splice(index,1)}if(response?.type==="response"&&response.command==="get_protocol_info"&&(protocols=Math.max(0,protocols-1),response.success===!0)){isRecord(response.data)&&admission.observe(response.data),output.push(Buffer.from(serializeJsonLine({...response,data:admission.protocol()}))),changed=!0;continue}output.push(line)}return changed?Buffer.concat(output):batch}}async function write(socket,line){await new Promise((resolve2,reject)=>{socket.write(line,error=>error?reject(error):resolve2())})}async function*lines(socket,limit){let decoder=new StringDecoder("utf8"),buffer="",discarding=!1;for await(let chunk of socket){let text=typeof chunk=="string"?chunk:decoder.write(chunk),offset=0;for(;offset<text.length;){let newline=text.indexOf(`
16
+ `,offset),end=newline===-1?text.length:newline;if(discarding||(buffer.length+end-offset>limit?(buffer="",discarding=!0,yield void 0):buffer+=text.slice(offset,end)),newline===-1)break;discarding||(yield buffer),buffer="",discarding=!1,offset=newline+1}}buffer+=decoder.end(),!discarding&&buffer.length>0&&(yield buffer)}function record(line){try{let value=JSON.parse(line);return isRecord(value)?value:void 0}catch{return}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function createPublicProxy(options){let{internalSocket,internalSecret,publicSecret,clients}=options;return createServer(client=>{let accept=()=>{if(!clients.admit(client))return;let internal=options.admission.stopping?void 0:createConnection2(resolveSocketTransportAddress(internalSocket,process.platform,internalSecret));internal&&internalSecret&&sendSocketHandshake(internal,internalSecret);let detach=()=>{clients.release(client)&&options.onAdmit?.(),options.onDetach(),internal?.destroy(),client.destroy()};proxyWithAdmission(client,internal,options.admission),client.once("close",detach),client.once("error",detach)};publicSecret?authenticateSocket(client,publicSecret,accept):accept()})}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename(bindSocket,publicSocket)}async function ensurePublicSocketSecret(publicSocket){let secretPath=socketSecretPath(publicSocket);try{return await ensureSocketSecret(secretPath)}catch(cause){throw new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`,{cause})}}async function waitForListener(socketPath,timeoutMs,secret){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await canConnect(socketPath,secret))return;await new Promise(resolveDelay=>setTimeout(resolveDelay,50))}throw new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`)}function canConnect(socketPath,secret){return new Promise(resolve2=>{let socket=createConnection2(resolveSocketTransportAddress(socketPath,process.platform,secret));secret&&sendSocketHandshake(socket,secret);let settle=value=>{socket.destroy(),resolve2(value)};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1))})}async function prepareSocketPath(socketPath){if(process.platform!=="win32"){if(Buffer.byteLength(socketPath)>MAX_SOCKET_PATH_BYTES)throw new Error(`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`);await mkdir(dirname2(socketPath),{recursive:!0,mode:448});try{await access(socketPath)}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}if(await canConnect(socketPath))throw new Error(`${socketPath}: address already in use by a live server.`);await unlink(socketPath)}}function listen(server,socketPath,secret){return new Promise((resolve2,reject)=>{server.once("error",reject),server.listen({path:resolveSocketTransportAddress(socketPath,process.platform,secret),readableAll:!1,writableAll:!1},async()=>{server.off("error",reject);try{process.platform!=="win32"&&!socketPath.startsWith("\0")&&await chmod(socketPath,384),resolve2()}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise(resolve2=>{server.close(()=>resolve2())})}import{randomUUID}from"node:crypto";import{mkdir as mkdir2,readFile,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join3}from"node:path";async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join3(baseDir,`internal-${randomUUID()}`);return await mkdir2(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join3(dir2,"secret")}}let dir=join3(tmpdir(),`senpi-rpc-host-internal-${randomUUID().slice(0,8)}`);return await mkdir2(dir,{recursive:!1,mode:448}),await writeFile(join3(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join3(dir,"host.sock"),dir,secretPath:join3(dir,".secret")}}async function recordChildPid(file,pid){try{let identity=await readProcessIdentity(pid,process.platform,1e3,void 0,"UTC"),processStartTime=identity.kind==="present"?identity.identity:null;processStartTime===null&&supervisorLog(`host child pid ${pid} start time unreadable at recording`),await writeJsonAtomic(file,{pid,processStartTime})}catch(cause){supervisorLog(`could not record the host child pid: ${errorMessage(cause)}`)}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile(settingsFile,"utf8"))}catch{return}}import{rm as rm3}from"node:fs/promises";var LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_ERROR_MS=5e3;function loopLagErrorMs(env=process.env){return parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}var STALL_WAIT_SLICE_MS=5e3;async function waitOutStalledChild(options){let{child,generation,signalledAt}=options,maxMs=childStalledStopMaxMs(),untilAt=signalledAt+maxMs,stalled=()=>hostLoopStalled(generation,{now:Date.now(),errorMs:loopLagErrorMs(),windowMs:STOP_STALL_EVIDENCE_MAX_AGE_MS}).catch(()=>!1),waited=0;try{for(;Date.now()<untilAt&&await stalled();){waited===0&&supervisorLog(`host child is stalled; waiting up to ${maxMs}ms (${CHILD_STALLED_STOP_MAX_MS_ENV})`),await writeStopProgress(generation,{at:new Date().toISOString(),phase:"waiting_stalled_child",untilAt:new Date(untilAt).toISOString()}).catch(()=>{});let slice=Math.min(STALL_WAIT_SLICE_MS,untilAt-Date.now()),exited=await options.waitForExit(child,slice);if(waited+=slice,exited)break}}finally{await clearStopProgress(generation)}return waited}var WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3;function supervisorSender(instanceId){return{pid:process.pid,kind:"supervisor",generation:instanceId}}function childExited(child){return child.exitCode!==null||child.signalCode!==null}async function performShutdown(context,reason,exitCode){let{state,child}=context;state.shuttingDown=!0,state.shutdownReason=reason,context.admission.stop();let childStopStarted=!1,hardExit;try{context.stopWatchers(),context.drain.stop(),writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`),childStopStarted=!0,await stopChild(context,reason),await state.childExitRecorded,await context.admission.flush(),context.activity.clients.destroyAll(),process.platform==="win32"&&(hardExit=setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS)),context.drain.active||await shieldSocketDuringClose(context.publicSocket,()=>closeServer(context.server)),context.internalDir&&await rm3(context.internalDir,{recursive:!0,force:!0}),context.activity.stopObserver(),state.publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedSocket(context.publicSocket,state.publicSocketIdentity,supervisorLog),await releaseGeneration(context.paths,{instanceId:context.instanceId,pid:process.pid,superseded:state.endpointReplaced})}catch(cause){supervisorLog(`shutdown failed for host child pid ${child.pid??"unknown"}: ${errorMessage(cause)}`),exitCode=1;try{childStopStarted||await reapChildAfterFailure(child),await state.childExitRecorded}catch(reapCause){supervisorLog(`shutdown recovery failed for host child pid ${child.pid??"unknown"}: ${errorMessage(reapCause)}`)}}finally{hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}async function stopChild(context,reason){let{child,generation}=context,pid=child.pid;if(childExited(child)||pid===void 0)return;let termAttempted=!1,killAttempted=!1;try{let outer=await readStopIntent(generation).catch(cause=>{supervisorLog(`cannot read child stop intent: ${errorMessage(cause)}`)}),at=new Date().toISOString(),intent=layeredSupervisorIntent(outer,supervisorSender(context.instanceId),{targetPid:pid,reason,at});await writeStopIntent(generation,intent,supervisorLog);let signalledAt=Date.now();if(termAttempted=!0,signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS))return;let stallWaitMs=await waitOutStalledChild({child,generation,signalledAt,waitForExit:waitForChildExit});if(childExited(child))return;if(stallWaitMs>0){let escalated={...intent,reason:`${intent.reason}; escalated_after_stall_wait=${stallWaitMs}`};await writeStopIntent(generation,escalated,supervisorLog)}if(killAttempted=!0,signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after SIGKILL`)}catch(cause){throw killAttempted||await reapChildAfterFailure(child,termAttempted),cause}}async function reapChildAfterFailure(child,termAttempted=!1){let pid=child.pid;if(!(childExited(child)||pid===void 0)&&!(!termAttempted&&(signalChild(pid,"SIGTERM"),await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)))&&(signalChild(pid,"SIGKILL"),!await waitForChildExit(child,CHILD_KILL_EXIT_TIMEOUT_MS)))throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after recovery SIGKILL`)}function signalChild(pid,signal){try{return process.kill(pid,signal),!0}catch{return!1}}function waitForChildExit(child,timeoutMs){return childExited(child)?Promise.resolve(!0):new Promise(resolve2=>{let timer=setTimeout(()=>{child.off("exit",onExit2),resolve2(!1)},timeoutMs),onExit2=()=>{clearTimeout(timer),resolve2(!0)};child.once("exit",onExit2)})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}function startSupervisorTicker(options){let{activity,owner,draining,shuttingDown,shutdown}=options,tickIntervalMs=Math.max(20,Math.min(1e3,options.idleExitMs/4)),ownerCheck=!1,ticker=setInterval(()=>{!draining()&&activity.refresh()==="exit"&&activity.clients.unclassifiedCount===0&&shutdown("idle",0),!ownerCheck&&!shuttingDown()&&!draining()&&(ownerCheck=!0,owner.shouldExit(activity).then(exit=>{exit&&!shuttingDown()&&!draining()&&shutdown("owner_gone",0)}).finally(()=>{ownerCheck=!1}))},tickIntervalMs);return()=>{clearInterval(ticker),owner.stop()}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID2(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,internal=await createInternalSocketPath(paths.dir),internalSocket=internal.socket,internalSecretPath=internal.secretPath??socketSecretPath(internalSocket),internalSecret=process.platform==="win32"?await createSocketSecret(internalSecretPath):void 0,state={shuttingDown:!1,shutdownReason:void 0,childExitRecorded:Promise.resolve(),publicSocketOwned:!1,publicSocketIdentity:void 0,endpointReplaced:!1},owner=new SupervisorOwner(generation.dir),activity=new SupervisorActivity({idleExitMs:policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs,internalSocket,...internalSecret?{internalSecret}:{},settled:()=>state.shuttingDown,onActivity:()=>owner.activity()}),watchers=[],child=spawnHostChild({launch,internalSocket,internal:{...internal,secretPath:internalSecretPath},...internalSecret?{internalSecret}:{},daemonDir:paths.dir,instanceId,cleanupPaths:hostCrashCleanupPaths({pointerFile:paths.pointerFile,generationPidFile:generation.pidFile,settingsFile:paths.settingsFile,publicSocket,successor:!!successor,platform:process.platform}),publicSocket}),childStartedAt=Date.now();child.stdio[HOST_CHILD_WATCH_FD]?.on("error",()=>{}),child.pid!==void 0&&recordChildPid(generation.childPidFile,child.pid),child.once("exit",(code,signal)=>{let reason=state.shutdownReason;if(state.childExitRecorded=noteChildExit({daemonDir:paths.dir,generation,instanceId,code,signal,childStartedAt,...state.shuttingDown&&reason!==void 0?{shutdown:{reason,supervisor:supervisorSender(instanceId)}}:{}}),state.shuttingDown)return;let verdict=classifyChildExit(code,signal);state.childExitRecorded.then(()=>shutdown(verdict.reason,verdict.exitCode))});let admission=new HostAdmission({protocolVersion:1,serverVersion:VERSION,capabilities:[],instanceId}),drain=new SupervisorDrain(child,()=>state.shuttingDown,()=>admission.stop()),server=createPublicProxy({internalSocket,...internalSecret?{internalSecret}:{},...publicSecret?{publicSecret}:{},clients:activity.clients,admission,onDetach:()=>activity.refresh(),onAdmit:()=>owner.activity()});server.once("error",cause=>{state.shuttingDown||shutdown(`public socket listener failed: ${errorMessage(cause)}`,1)}),watchers.push(startSupervisorTicker({idleExitMs:policy.idleExitMs,activity,owner,draining:()=>drain.active,shuttingDown:()=>state.shuttingDown,shutdown}));let teardown={paths,generation,instanceId,publicSocket,server,internalDir:internal.dir,child,activity,drain,admission,state,stopWatchers:()=>{for(let stop of watchers.splice(0))stop()}},shutdownPromise;function shutdown(reason,exitCode){return shutdownPromise??=performShutdown(teardown,reason,exitCode),shutdownPromise}registerSupervisorSignals(shutdown,()=>drain.drain());try{(launch.ownerFd!==void 0||await readSettingsFile(generation.settingsFile))&&await owner.start(launch.ownerFd),await waitForListener(internalSocket,3e4,internalSecret),await activity.openObserver(),await prepareSocketPath(bindSocket),await listen(server,bindSocket,publicSecret),state.publicSocketOwned=!0,successor&&await adoptPublicSocket(bindSocket,publicSocket,launch.replaceIdentity),state.publicSocketIdentity=await statSocketIdentity(publicSocket),state.publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join4(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),state.publicSocketIdentity),watchers.push(drainOnPublicSocketLoss(publicSocket,state.publicSocketIdentity,()=>state.shuttingDown||drain.active,drain,()=>{state.endpointReplaced=!0}))}catch(cause){await shutdown(`startup failed: ${errorMessage(cause)}`,1)}process.platform==="win32"&&watchers.push(await watchWin32ChildIdentity(child,()=>state.shuttingDown,()=>{shutdown("rpc host child exit observed by identity watchdog",0)})),writeStderrLine(`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${policy.coldStart==="persistent"?"never":String(policy.idleExitMs)})`),await new Promise(()=>{})}function isEntryScript(){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath2(import.meta.url)===realpathSync(entry)}catch{return!1}}if(!isBundledNode&&isEntryScript()){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}export{runtimeExecArgv,OBSERVE_REQUEST_FIELD,loopLagErrorMs,recordProcessLifetime,isHostCrash,readHostCrashRecords,CHILD_STOP_TIMEOUT_MS,CHILD_KILL_EXIT_TIMEOUT_MS,writeStopIntent,readStopIntent,classifyChildExit,noteEscalatedStop,ClientOccupancy,resolveCliMainPath,readHostWatchdogConfigFromBrandEnv,armHostWatchdog,INTERNAL_SUPERVISOR_FLAG,findInternalSupervisorArgs,parseSupervisorArgs,OWNER_WATCH_FD,keepOwnerPipe,resolveHostChildLaunch,spawnableChildLaunch,createInternalSocketPath,runHostSupervisor};
@@ -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{clientMessageIdentitySchema}from"./chunk-IRKWZZKD.js";import{watchWithErrorHandler}from"./chunk-JABBHOD5.js";import{ProjectTrustStore}from"./chunk-RRU5LXMS.js";import{modelSupportsAssistantPrefill}from"./chunk-EBOD66AS.js";import{sanitizeProviderDiagnostic}from"./chunk-YOPVJDSU.js";import{getSupportedThinkingLevels,supportsMax,supportsXhigh}from"./chunk-L4HVJWIF.js";function supportsXhigh2(model){return supportsXhigh(model)}function supportsMax2(model){return supportsMax(model)}function getSupportedThinkingLevels2(model){let supportedLevels=getSupportedThinkingLevels(model);return supportedLevels.length>0?supportedLevels:["off"]}function clampThinkingSelection(selection,requested,level,model){if(selection===void 0)return;let{requested:_staleRequested,clampReason:_staleReason,...base}=selection;return requested===level||model===void 0?{...base,level}:{...base,level,requested,clampReason:model.reasoning?"level-unsupported":"model-not-reasoning"}}function getThinkingClampNotice(selection,model){let clamped=selection;if(!(model===void 0||clamped?.requested===void 0||clamped.clampReason===void 0))return{provider:model.provider,modelId:model.id,requestedLevel:clamped.requested,appliedLevel:clamped.level,reason:clamped.clampReason}}function formatThinkingClampWarning(notice){let model=`${notice.provider}/${notice.modelId}`;return notice.reason==="model-not-reasoning"?`Thinking level "${notice.requestedLevel}" was requested, but ${model} is not marked as a reasoning model, so thinking is "${notice.appliedLevel}". If the model supports reasoning, set "reasoning": true for it in models.json.`:`Thinking level "${notice.requestedLevel}" is not available on ${model}; using "${notice.appliedLevel}".`}function classifyReasoningCapability(model){if(!model.reasoning)return{kind:"none",levels:["off"],nonOffLevels:[]};let levels=getSupportedThinkingLevels2(model),nonOffLevels=levels.filter(level=>level!=="off");return levels.includes("off")?nonOffLevels.length===1?{kind:"on-off",levels,nonOffLevels}:nonOffLevels.length===0?{kind:"none",levels,nonOffLevels}:{kind:"graded",levels,nonOffLevels}:{kind:"always-on",levels,nonOffLevels}}var BROWSER_ENGINES=["connected","builtin","none"];function isBrowserEngine(value){return BROWSER_ENGINES.some(engine=>engine===value)}var MAX_RPC_MESSAGE_CHARACTERS=1e6,SESSION_CONTEXT_LIMITS={keys:32,valueBytes:16*1024,totalBytes:32*1024},SESSION_CONTEXT_KEY_PATTERN=/^[a-z][a-z0-9_]*$/;function validContent(content){return typeof content=="string"?!0:Array.isArray(content)&&content.every(item=>{if(typeof item!="object"||item===null)return!1;let value=item;return value.type==="text"?typeof value.text=="string":value.type==="image"&&typeof value.data=="string"&&typeof value.mimeType=="string"})}function validBaseEntry(entry){return typeof entry.id=="string"&&(entry.parentId===null||typeof entry.parentId=="string")&&typeof entry.timestamp=="string"}function validSessionEntry(entry){if(typeof entry!="object"||entry===null||Array.isArray(entry))return!1;let value=entry;if(!validBaseEntry(value))return!1;switch(value.type){case"message":{let message=value.message;if(typeof message!="object"||message===null)return!1;let item=message;return["user","assistant","tool"].includes(item.role)&&validContent(item.content)}case"thinking_level_change":return typeof value.thinkingLevel=="string";case"model_change":return typeof value.provider=="string"&&typeof value.modelId=="string";case"model_change_rejected":return typeof value.provider=="string"&&typeof value.modelId=="string"&&typeof value.detail=="string";case"compaction":return typeof value.summary=="string"&&typeof value.firstKeptEntryId=="string"&&typeof value.tokensBefore=="number";case"branch_summary":return typeof value.fromId=="string"&&typeof value.summary=="string";case"custom":return typeof value.customType=="string";case"custom_message":return typeof value.customType=="string"&&validContent(value.content)&&typeof value.display=="boolean";case"label":return typeof value.targetId=="string"&&(value.label===void 0||typeof value.label=="string");case"session_info":return value.name===void 0||typeof value.name=="string";default:return!1}}function rpcCommandPayloadError(command){if(rpcCommandShapeError(command))return;let value=command;if((value.type==="prompt"||value.type==="steer"||value.type==="follow_up")&&!clientMessageIdentitySchema.safeParse(value).success)return"clientMessageId and clientTurnId must be non-empty strings of at most 256 characters.";if((value.type==="steer"||value.type==="follow_up")&&value.enqueueOrder!==void 0&&!(typeof value.enqueueOrder=="number"&&Number.isFinite(value.enqueueOrder)))return"enqueueOrder must be a finite number.";if(value.type==="append_user_message"&&!validContent(value.content))return"append_user_message content must be a string or text/image content array.";if(value.type==="append_session_entry"&&!validSessionEntry(value.entry))return"append_session_entry entry is malformed."}function sessionContextError(context){if(context===void 0)return;if(typeof context!="object"||context===null||Array.isArray(context))return"context must be an object of string values.";let entries=Object.entries(context);if(entries.length>SESSION_CONTEXT_LIMITS.keys)return`context has ${entries.length} keys, at most ${SESSION_CONTEXT_LIMITS.keys} are accepted.`;for(let[key,value]of entries){if(!SESSION_CONTEXT_KEY_PATTERN.test(key))return`context key "${key}" must match ${SESSION_CONTEXT_KEY_PATTERN.source}.`;if(typeof value!="string")return`context value for key "${key}" must be a string.`;let valueBytes=Buffer.byteLength(value);if(valueBytes>SESSION_CONTEXT_LIMITS.valueBytes)return`context value for key "${key}" is ${valueBytes} bytes, at most ${SESSION_CONTEXT_LIMITS.valueBytes} bytes are accepted.`}let totalBytes=Buffer.byteLength(JSON.stringify(context));if(totalBytes>SESSION_CONTEXT_LIMITS.totalBytes)return`context is ${totalBytes} bytes of JSON, at most ${SESSION_CONTEXT_LIMITS.totalBytes} bytes are accepted.`}function sessionKindError(kind){if(!(kind===void 0||kind==="interactive"||kind==="worker"))return'kind must be "interactive" or "worker".'}function sessionAutoTitleError(value){if(!(value===void 0||typeof value=="boolean"))return"auto_title must be a boolean."}function sessionPromptSurfaceError(value){if(!(value===void 0||value==="terminal"||value==="app"||value==="chat"))return'promptSurface must be "terminal", "app" or "chat".'}function sessionBrowserEngineError(value){if(!(value===void 0||isBrowserEngine(value)))return'browserEngine must be "connected", "builtin" or "none".'}var MAX_RETRY_FALLBACK_CHAINS=32,MAX_RETRY_FALLBACK_ENTRIES=32,MAX_RETRY_FALLBACK_SELECTOR_LENGTH=512;function sessionRetryFallbackError(value){if(value===void 0)return;let shape="retryFallback must be { modelFallback: boolean, fallbackChains: Record<string, string[]> }.";if(typeof value!="object"||value===null||Array.isArray(value))return shape;let record=value;if(typeof record.modelFallback!="boolean")return shape;let chains=record.fallbackChains;if(typeof chains!="object"||chains===null||Array.isArray(chains))return shape;let entries=Object.entries(chains);if(entries.length>MAX_RETRY_FALLBACK_CHAINS)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_CHAINS} chains.`;for(let[key,selectors]of entries){if(!isSelector(key)||!Array.isArray(selectors)||!selectors.every(isSelector))return shape;if(selectors.length>MAX_RETRY_FALLBACK_ENTRIES)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_ENTRIES} entries per chain.`}}function isSelector(value){return typeof value=="string"&&value.trim().length>0&&value.length<=MAX_RETRY_FALLBACK_SELECTOR_LENGTH}function rpcCommandShapeError(command){if(typeof command!="object"||command===null||Array.isArray(command))return"RPC command must be a JSON object."}function rpcMessageLengthError(command){if(rpcCommandShapeError(command))return;let input=command;if(!(input.type!=="prompt"&&input.type!=="steer"&&input.type!=="follow_up")&&!(typeof input.message!="string"||input.message.length<=MAX_RPC_MESSAGE_CHARACTERS))return`RPC ${input.type} message exceeds ${MAX_RPC_MESSAGE_CHARACTERS} characters.`}import{randomUUID}from"node:crypto";import{mkdir,rm,writeFile}from"node:fs/promises";import{join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{Worker}from"node:worker_threads";var RECURSIVE_WATCH_WORKER_SOURCE=`
2
+ import{clientMessageIdentitySchema}from"./chunk-IRKWZZKD.js";import{watchWithErrorHandler}from"./chunk-JABBHOD5.js";import{ProjectTrustStore}from"./chunk-RRU5LXMS.js";import{modelSupportsAssistantPrefill}from"./chunk-PBN2CATL.js";import{sanitizeProviderDiagnostic}from"./chunk-YOPVJDSU.js";import{getSupportedThinkingLevels,supportsMax,supportsXhigh}from"./chunk-E5YUVGLQ.js";function supportsXhigh2(model){return supportsXhigh(model)}function supportsMax2(model){return supportsMax(model)}function getSupportedThinkingLevels2(model){let supportedLevels=getSupportedThinkingLevels(model);return supportedLevels.length>0?supportedLevels:["off"]}function clampThinkingSelection(selection,requested,level,model){if(selection===void 0)return;let{requested:_staleRequested,clampReason:_staleReason,...base}=selection;return requested===level||model===void 0?{...base,level}:{...base,level,requested,clampReason:model.reasoning?"level-unsupported":"model-not-reasoning"}}function getThinkingClampNotice(selection,model){let clamped=selection;if(!(model===void 0||clamped?.requested===void 0||clamped.clampReason===void 0))return{provider:model.provider,modelId:model.id,requestedLevel:clamped.requested,appliedLevel:clamped.level,reason:clamped.clampReason}}function formatThinkingClampWarning(notice){let model=`${notice.provider}/${notice.modelId}`;return notice.reason==="model-not-reasoning"?`Thinking level "${notice.requestedLevel}" was requested, but ${model} is not marked as a reasoning model, so thinking is "${notice.appliedLevel}". If the model supports reasoning, set "reasoning": true for it in models.json.`:`Thinking level "${notice.requestedLevel}" is not available on ${model}; using "${notice.appliedLevel}".`}function classifyReasoningCapability(model){if(!model.reasoning)return{kind:"none",levels:["off"],nonOffLevels:[]};let levels=getSupportedThinkingLevels2(model),nonOffLevels=levels.filter(level=>level!=="off");return levels.includes("off")?nonOffLevels.length===1?{kind:"on-off",levels,nonOffLevels}:nonOffLevels.length===0?{kind:"none",levels,nonOffLevels}:{kind:"graded",levels,nonOffLevels}:{kind:"always-on",levels,nonOffLevels}}var BROWSER_ENGINES=["connected","builtin","none"];function isBrowserEngine(value){return BROWSER_ENGINES.some(engine=>engine===value)}var MAX_RPC_MESSAGE_CHARACTERS=1e6,SESSION_CONTEXT_LIMITS={keys:32,valueBytes:16*1024,totalBytes:32*1024},SESSION_CONTEXT_KEY_PATTERN=/^[a-z][a-z0-9_]*$/;function validContent(content){return typeof content=="string"?!0:Array.isArray(content)&&content.every(item=>{if(typeof item!="object"||item===null)return!1;let value=item;return value.type==="text"?typeof value.text=="string":value.type==="image"&&typeof value.data=="string"&&typeof value.mimeType=="string"})}function validBaseEntry(entry){return typeof entry.id=="string"&&(entry.parentId===null||typeof entry.parentId=="string")&&typeof entry.timestamp=="string"}function validSessionEntry(entry){if(typeof entry!="object"||entry===null||Array.isArray(entry))return!1;let value=entry;if(!validBaseEntry(value))return!1;switch(value.type){case"message":{let message=value.message;if(typeof message!="object"||message===null)return!1;let item=message;return["user","assistant","tool"].includes(item.role)&&validContent(item.content)}case"thinking_level_change":return typeof value.thinkingLevel=="string";case"model_change":return typeof value.provider=="string"&&typeof value.modelId=="string";case"model_change_rejected":return typeof value.provider=="string"&&typeof value.modelId=="string"&&typeof value.detail=="string";case"compaction":return typeof value.summary=="string"&&typeof value.firstKeptEntryId=="string"&&typeof value.tokensBefore=="number";case"branch_summary":return typeof value.fromId=="string"&&typeof value.summary=="string";case"custom":return typeof value.customType=="string";case"custom_message":return typeof value.customType=="string"&&validContent(value.content)&&typeof value.display=="boolean";case"label":return typeof value.targetId=="string"&&(value.label===void 0||typeof value.label=="string");case"session_info":return value.name===void 0||typeof value.name=="string";default:return!1}}function rpcCommandPayloadError(command){if(rpcCommandShapeError(command))return;let value=command;if((value.type==="prompt"||value.type==="steer"||value.type==="follow_up")&&!clientMessageIdentitySchema.safeParse(value).success)return"clientMessageId and clientTurnId must be non-empty strings of at most 256 characters.";if((value.type==="steer"||value.type==="follow_up")&&value.enqueueOrder!==void 0&&!(typeof value.enqueueOrder=="number"&&Number.isFinite(value.enqueueOrder)))return"enqueueOrder must be a finite number.";if(value.type==="append_user_message"&&!validContent(value.content))return"append_user_message content must be a string or text/image content array.";if(value.type==="append_session_entry"&&!validSessionEntry(value.entry))return"append_session_entry entry is malformed."}function sessionContextError(context){if(context===void 0)return;if(typeof context!="object"||context===null||Array.isArray(context))return"context must be an object of string values.";let entries=Object.entries(context);if(entries.length>SESSION_CONTEXT_LIMITS.keys)return`context has ${entries.length} keys, at most ${SESSION_CONTEXT_LIMITS.keys} are accepted.`;for(let[key,value]of entries){if(!SESSION_CONTEXT_KEY_PATTERN.test(key))return`context key "${key}" must match ${SESSION_CONTEXT_KEY_PATTERN.source}.`;if(typeof value!="string")return`context value for key "${key}" must be a string.`;let valueBytes=Buffer.byteLength(value);if(valueBytes>SESSION_CONTEXT_LIMITS.valueBytes)return`context value for key "${key}" is ${valueBytes} bytes, at most ${SESSION_CONTEXT_LIMITS.valueBytes} bytes are accepted.`}let totalBytes=Buffer.byteLength(JSON.stringify(context));if(totalBytes>SESSION_CONTEXT_LIMITS.totalBytes)return`context is ${totalBytes} bytes of JSON, at most ${SESSION_CONTEXT_LIMITS.totalBytes} bytes are accepted.`}function sessionKindError(kind){if(!(kind===void 0||kind==="interactive"||kind==="worker"))return'kind must be "interactive" or "worker".'}function sessionAutoTitleError(value){if(!(value===void 0||typeof value=="boolean"))return"auto_title must be a boolean."}function sessionPromptSurfaceError(value){if(!(value===void 0||value==="terminal"||value==="app"||value==="chat"))return'promptSurface must be "terminal", "app" or "chat".'}function sessionBrowserEngineError(value){if(!(value===void 0||isBrowserEngine(value)))return'browserEngine must be "connected", "builtin" or "none".'}var MAX_RETRY_FALLBACK_CHAINS=32,MAX_RETRY_FALLBACK_ENTRIES=32,MAX_RETRY_FALLBACK_SELECTOR_LENGTH=512;function sessionRetryFallbackError(value){if(value===void 0)return;let shape="retryFallback must be { modelFallback: boolean, fallbackChains: Record<string, string[]> }.";if(typeof value!="object"||value===null||Array.isArray(value))return shape;let record=value;if(typeof record.modelFallback!="boolean")return shape;let chains=record.fallbackChains;if(typeof chains!="object"||chains===null||Array.isArray(chains))return shape;let entries=Object.entries(chains);if(entries.length>MAX_RETRY_FALLBACK_CHAINS)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_CHAINS} chains.`;for(let[key,selectors]of entries){if(!isSelector(key)||!Array.isArray(selectors)||!selectors.every(isSelector))return shape;if(selectors.length>MAX_RETRY_FALLBACK_ENTRIES)return`retryFallback allows at most ${MAX_RETRY_FALLBACK_ENTRIES} entries per chain.`}}function isSelector(value){return typeof value=="string"&&value.trim().length>0&&value.length<=MAX_RETRY_FALLBACK_SELECTOR_LENGTH}function rpcCommandShapeError(command){if(typeof command!="object"||command===null||Array.isArray(command))return"RPC command must be a JSON object."}function rpcMessageLengthError(command){if(rpcCommandShapeError(command))return;let input=command;if(!(input.type!=="prompt"&&input.type!=="steer"&&input.type!=="follow_up")&&!(typeof input.message!="string"||input.message.length<=MAX_RPC_MESSAGE_CHARACTERS))return`RPC ${input.type} message exceeds ${MAX_RPC_MESSAGE_CHARACTERS} characters.`}import{randomUUID}from"node:crypto";import{mkdir,rm,writeFile}from"node:fs/promises";import{join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{Worker}from"node:worker_threads";var RECURSIVE_WATCH_WORKER_SOURCE=`
3
3
  const { watch } = require("node:fs");
4
4
  const { parentPort } = require("node:worker_threads");
5
5
 
@@ -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{shortHash}from"./chunk-VYKBN4MR.js";var TOOL_CALL_ID_MAX_LENGTH=64;function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");if(sanitized.length<=TOOL_CALL_ID_MAX_LENGTH)return sanitized;let suffix=`_${shortHash(id)}`;return`${sanitized.slice(0,TOOL_CALL_ID_MAX_LENGTH-suffix.length)}${suffix}`}export{normalizeToolCallId};
2
+ import{shortHash}from"./chunk-GC2RU5TS.js";var TOOL_CALL_ID_MAX_LENGTH=64;function normalizeToolCallId(id){let sanitized=id.replace(/[^a-zA-Z0-9_-]/g,"_");if(sanitized.length<=TOOL_CALL_ID_MAX_LENGTH)return sanitized;let suffix=`_${shortHash(id)}`;return`${sanitized.slice(0,TOOL_CALL_ID_MAX_LENGTH-suffix.length)}${suffix}`}export{normalizeToolCallId};
@@ -0,0 +1,12 @@
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{ProcessIdentityUnreadableError,parseDaemonPidFile,processIsLive,processMatchesPidFile,processStartTimeMs,readProcessIdentity,readProcessStartTime,sameProcessStartMs}from"./chunk-ZRWOLP4E.js";import{getAgentDir}from"./chunk-463OK2Y4.js";import{existsSync,realpathSync}from"node:fs";import{basename,dirname,join,resolve}from"node:path";function canonicalSessionPath(path){let absolutePath=resolve(path),missing=[],existing=absolutePath;for(;!existsSync(existing);){let parent=dirname(existing);if(parent===existing)return absolutePath;missing.unshift(basename(existing)),existing=parent}try{return join(realpathSync(existing),...missing)}catch{return absolutePath}}function sessionDirectoryRemoved(sessionFile){return!existsSync(dirname(sessionFile))}import{createHash}from"node:crypto";import{basename as basename2,dirname as dirname2,join as join2,win32}from"node:path";function canonicalEndpointPath(socket,platform=process.platform){return platform==="win32"?win32.normalize(socket).toLowerCase():socket.startsWith("\0")?socket:join2(canonicalSessionPath(dirname2(socket)),basename2(socket))}function daemonDirectoryName(socket,platform=process.platform){return directoryNameOf(canonicalEndpointPath(socket,platform))}function sameEndpoint(socket,other){return socket===other||canonicalEndpointPath(socket)===canonicalEndpointPath(other)}function socketNamesDirectory(socket,name){return daemonDirectoryName(socket)===name||process.platform!=="win32"&&directoryNameOf(socket)===name}function directoryNameOf(endpoint){return createHash("sha256").update(endpoint,"utf8").digest("hex").slice(0,16)}function shardKey(kind,ownerId){return createHash("sha256").update(`${kind}:${ownerId}`,"utf8").digest("hex").slice(0,16)}function shardSocketPathForKey(root,kind,key){return join2(root,`${kind}-${key}.sock`)}function shardSocketPath(root,kind,ownerId){return shardSocketPathForKey(root,kind,shardKey(kind,ownerId))}var SHARD_SOCKET_NAME=/^(p|i)-([0-9a-f]{16})\.sock$/;function parseShardSocket(socket){let match=SHARD_SOCKET_NAME.exec(basename2(socket)),key=match?.[2];return key===void 0?null:{kind:match?.[1]==="i"?"i":"p",key}}import{chmod,mkdir}from"node:fs/promises";import{join as join3}from"node:path";var DIRECTORY_MODE=448;function generationPaths(paths,instanceId){let dir=join3(paths.generationsDir,instanceId);return{dir,relativeDir:`generations/${instanceId}`,pidFile:join3(dir,"host.pid"),settingsFile:join3(dir,"settings.json"),scratchDir:join3(dir,"scratch"),childPidFile:join3(dir,"host-child.pid"),stopIntentFile:join3(dir,"stop-intent.json"),stalledFile:join3(dir,"host-stalled.json"),aliveFile:join3(dir,"host-alive.json"),stopProgressFile:join3(dir,"stop-progress.json")}}var HostDaemonStateError=class extends Error{constructor(path,cause){super(`RPC daemon state directory ${path} is not usable: ${cause instanceof Error?cause.message:cause}`,{cause}),this.name="HostDaemonStateError",this.path=path}};async function createGenerationDirectory(generation){try{await mkdir(generation.scratchDir,{recursive:!0,mode:DIRECTORY_MODE}),await chmod(generation.dir,DIRECTORY_MODE)}catch(cause){throw new HostDaemonStateError(generation.dir,cause)}}import{randomUUID}from"node:crypto";import{chmod as chmod2,link,mkdir as mkdir2,readFile,rename,rm,writeFile}from"node:fs/promises";import{basename as basename3,join as join4}from"node:path";var HOST_DAEMON_LAYOUT=2,HOST_DAEMON_DIR_ENV="SENPI_RPC_HOST_DAEMON_DIR",ENDPOINT_REGISTRY_VERSION=1,DIRECTORY_MODE2=448,HOST_STATE_FILE_MODE=384;function createHostDaemonPaths(target){let flatDir=join4(target.agentDir??getAgentDir(),"rpc-host-daemon");return{socket:target.socket,flatDir,layoutMarker:join4(flatDir,"layout.json"),legacyPidFile:join4(flatDir,"host.pid"),...hostDaemonDirectoryPaths(join4(flatDir,daemonDirectoryName(target.socket)))}}function hostDaemonDirectoryPaths(dir){return{dir,endpointFile:join4(dir,"endpoint.json"),pointerFile:join4(dir,"host.pid"),lockFile:join4(dir,"daemon.lock"),settingsFile:join4(dir,"settings.json"),stderrLog:join4(dir,"stderr.log"),generationsDir:join4(dir,"generations"),reservationsDir:join4(dir,"reservations")}}async function createDaemonDirectories(paths,identity={}){try{await mkdir2(paths.flatDir,{recursive:!0,mode:DIRECTORY_MODE2}),await makePrivateDirectory(paths.dir),await Promise.all([makePrivateDirectory(paths.generationsDir),makePrivateDirectory(paths.reservationsDir),writeFile(paths.layoutMarker,`${JSON.stringify({layout:HOST_DAEMON_LAYOUT,dir:basename3(paths.dir)})}
3
+ `,{mode:HOST_STATE_FILE_MODE})])}catch(cause){throw new HostDaemonStateError(paths.dir,cause)}await ensureEndpointIdentity(paths,paths.socket,identity)}async function makePrivateDirectory(directory){await mkdir2(directory,{recursive:!0,mode:DIRECTORY_MODE2})===void 0&&await chmod2(directory,DIRECTORY_MODE2)}async function ensureEndpointIdentity(paths,socket,options={}){let temporary=`${paths.endpointFile}.${process.pid}-${randomUUID()}.tmp`;try{await mkdir2(paths.dir,{recursive:!0,mode:DIRECTORY_MODE2});let record=`${JSON.stringify({layout:HOST_DAEMON_LAYOUT,registry_version:ENDPOINT_REGISTRY_VERSION,endpoint_kind:options.kind??"rpc_host",socket,created_at:new Date().toISOString()})}
4
+ `;await writeFile(temporary,record,{mode:HOST_STATE_FILE_MODE,flag:"wx"}),!await link(temporary,paths.endpointFile).then(()=>!0,cause=>isErrorCode(cause,"EEXIST")?!1:createExclusively(paths.endpointFile,record))&&options.repair===!0&&!await namesThisDirectory(paths)&&await rename(temporary,paths.endpointFile)}catch(cause){throw new HostDaemonStateError(paths.endpointFile,cause)}finally{await rm(temporary,{force:!0})}}async function createExclusively(path,content){try{return await writeFile(path,content,{mode:HOST_STATE_FILE_MODE,flag:"wx"}),!0}catch(cause){if(isErrorCode(cause,"EEXIST"))return!1;throw cause}}function isErrorCode(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}async function namesThisDirectory(paths){let record;try{record=JSON.parse(await readFile(paths.endpointFile,"utf8"))}catch{return!1}return typeof record!="object"||record===null||!("socket"in record)?!1:typeof record.socket=="string"&&record.socket!==""&&socketNamesDirectory(record.socket,basename3(paths.dir))}import{writeSync}from"node:fs";function writeStderrLine(text){try{writeSync(2,`${text}
5
+ `)}catch{}}function supervisorLog(message){writeStderrLine(`senpi rpc host supervisor: ${message}`)}var loggedUnknownIdentities=new Set;function logUnknownHostIdentity(record,pid){let key=`${record}:${pid}`;loggedUnknownIdentities.has(key)||(loggedUnknownIdentities.add(key),writeStderrLine(JSON.stringify({event:"legacy_host_identity_unknown",record,pid})))}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}import{createHash as createHash2}from"node:crypto";import{mkdir as mkdir3,readdir,readFile as readFile4,rename as rename3,rm as rm3,writeFile as writeFile4}from"node:fs/promises";import{join as join6}from"node:path";import{readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{join as join5}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";import{readFile as readFile2,rename as rename2,rm as rm2,writeFile as writeFile2}from"node:fs/promises";async function writeJsonAtomic(path,content){let temporary=`${path}.${process.pid}.${randomUUID2().slice(0,8)}.tmp`;try{await writeFile2(temporary,`${JSON.stringify(content)}
6
+ `,{mode:384}),await rename2(temporary,path)}catch(cause){throw await rm2(temporary,{force:!0}).catch(()=>{}),cause}}async function readJsonObject(path){try{let value=JSON.parse(await readFile2(path,"utf8"));return typeof value=="object"&&value!==null&&!Array.isArray(value)?{...value}:void 0}catch{return}}function ageOf(at,now){if(typeof at!="string")return;let parsed=Date.parse(at);return Number.isNaN(parsed)?void 0:now-parsed}async function readHostOwner(generationDir){let record=await readJsonObject(join5(generationDir,"owner.json"));if(record?.owner===null)return null;if(!isRecord(record?.owner))return;let{pid,startTime}=record.owner;return typeof pid=="number"&&Number.isSafeInteger(pid)&&pid>0&&typeof startTime=="string"&&startTime.length>0?{pid,startTime}:void 0}function writeHostOwner(generationDir,owner){return writeJsonAtomic(join5(generationDir,"owner.json"),{owner})}function sameHostOwner(a,b){if(a==null||b==null||a.pid!==b.pid)return!1;let started=processStartTimeMs(a.startTime);return started!==void 0&&started===processStartTimeMs(b.startTime)}async function callerHostOwner(){let observed=await readProcessIdentity(process.pid,process.platform,void 0,void 0,"UTC");if(observed.kind!=="present"||processStartTimeMs(observed.identity)===void 0)throw new Error("cannot establish RPC host owner OS start identity");return{pid:process.pid,startTime:observed.identity}}async function hostOwnerGone(owner){let observed=await readProcessIdentity(owner.pid,process.platform,1e3,void 0,"UTC");return observed.kind==="absent"||observed.kind==="present"&&processStartTimeMs(observed.identity)!==void 0&&processStartTimeMs(owner.startTime)!==void 0&&!sameProcessStartMs(processStartTimeMs(observed.identity),processStartTimeMs(owner.startTime))}async function claimHostOwner(generationDir){let previous=await readHostOwner(generationDir);if(previous===void 0)throw new Error("RPC host does not support owner lifetime registration");let next=await callerHostOwner();if(!sameHostOwner(previous,next)){if(previous!==null&&!await hostOwnerGone(previous))throw new Error("RPC host lifetime owner is still alive or its identity is unknown");await writeHostOwner(generationDir,next)}}async function writeHostSettings(paths,settings){let generation=generationPaths(paths,settings.instanceId);await createGenerationDirectory(generation),await writeStateFile(paths.settingsFile,settings),await writeStateFile(generation.settingsFile,settings)}async function readHostSettings(paths){let parsed=parseJson(await readFileOrUndefined(paths.settingsFile));if(parsed)return{...typeof parsed.coldStart=="string"&&{coldStart:parsed.coldStart},...typeof parsed.idleExitMs=="number"&&{idleExitMs:parsed.idleExitMs}}}async function writeStateFile(path,content){try{await writeFile3(path,`${JSON.stringify(content)}
7
+ `,{mode:HOST_STATE_FILE_MODE})}catch(cause){throw new HostDaemonStateError(path,cause)}}async function readFileOrUndefined(path){try{return await readFile3(path,"utf8")}catch(error){if(isNodeErrorCode(error,"ENOENT")||isNodeErrorCode(error,"ENOTDIR"))return;throw error}}function parseJson(text){if(text!==void 0)try{let parsed=JSON.parse(text);return isRecord(parsed)?parsed:void 0}catch{return}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}var SESSION_PATH_RETRY_AFTER_MS=2e3;function reservationFile(dir,sessionPath){return join6(dir,`${createHash2("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({daemonDir:dir,instanceId:host.instanceId,...host.onFailure?{onFailure:host.onFailure}:{}})}function createSessionPathReservations(options){let paths=hostDaemonDirectoryPaths(options.daemonDir),dir=paths.reservationsDir,pid=options.pid??process.pid,startTime=readProcessStartTime(pid).then(value=>value??null,()=>null),held=new Set,updates=new Map,report=message=>options.onFailure?.(message),publish=async(sessionPath,attached,stillHeld)=>{let owner={instanceId:options.instanceId,pid,processStartTime:await startTime,sessionPath,attached},file=reservationFile(dir,sessionPath);await mkdir3(dir,{recursive:!0,mode:448});let staging=`${file}.${pid}.tmp`;if(await writeFile4(staging,`${JSON.stringify(owner)}
8
+ `,{mode:384}),stillHeld?.()===!1){await rm3(staging,{force:!0});return}await rename3(staging,file)};return{async holderPids(observedStarts){let candidates=(await readSessionPathClaims(dir)).map(({owner})=>owner),generations=await readdir(paths.generationsDir,{withFileTypes:!0}).catch(()=>[]);for(let generation of generations){if(!generation.isDirectory())continue;let record=parseJson(await readFileOrUndefined(join6(paths.generationsDir,generation.name,"host-child.pid")));typeof record?.pid=="number"&&candidates.push({pid:record.pid,processStartTime:typeof record.processStartTime=="string"?record.processStartTime:null,instanceId:generation.name,sessionPath:""})}let byPid=new Map;for(let owner of candidates){if(owner.pid===process.pid)continue;let owners=byPid.get(owner.pid)??[];owners.push(owner),byPid.set(owner.pid,owners)}let live=await Promise.all([...byPid].map(async([pid2,owners])=>{if(!processIsLive(pid2))return;if(observedStarts){if(!observedStarts.has(pid2))return;let observed2=observedStarts.get(pid2);return owners.some(owner=>owner.processStartTime===null?!1:sameProcessStartMs(processStartTimeMs(owner.processStartTime),observed2))?pid2:void 0}let current=await readProcessStartTime(pid2,process.platform,1e3).catch(()=>{}),observed=current===void 0?void 0:processStartTimeMs(current);return observed!==void 0&&owners.some(owner=>owner.processStartTime!==null&&sameProcessStartMs(processStartTimeMs(owner.processStartTime),observed))?pid2:void 0}));return[...new Set(live.filter(value=>value!==void 0))]},async claim(sessionPath,attached=!0){let existing=await readOwner(reservationFile(dir,sessionPath));if(existing&&existing.pid!==pid){let standing=await standingOwner(existing,paths.pointerFile);if(standing)return standing}try{await publish(sessionPath,attached),held.add(sessionPath)}catch(cause){report(`session path reservation for ${sessionPath} could not be written (${errorMessage2(cause)})`)}},async release(sessionPath){held.delete(sessionPath)&&(await updates.get(sessionPath),updates.delete(sessionPath),await rm3(reservationFile(dir,sessionPath),{force:!0}).catch(cause=>{report(`session path reservation for ${sessionPath} could not be removed (${errorMessage2(cause)})`)}))},setAttached(sessionPath,attached){if(!held.has(sessionPath))return;let update=(updates.get(sessionPath)??Promise.resolve()).then(()=>publish(sessionPath,attached,()=>held.has(sessionPath))).catch(cause=>{report(`session path reservation for ${sessionPath} could not be updated (${errorMessage2(cause)})`)});updates.set(sessionPath,update)}}}async function readSessionPathClaims(dir){let entries=await readdir(dir).catch(()=>[]),claims=[];for(let entry of entries){if(!entry.endsWith(".json"))continue;let file=join6(dir,entry),owner=await readOwner(file);owner&&claims.push({file,owner})}return claims}async function standingOwner(owner,pointerFile){if(!await claimOwnerIsLive(owner))return;let current=await currentInstanceId(pointerFile)===owner.instanceId;return current||owner.attached!==!1?{...owner,current}:void 0}async function currentInstanceId(pointerFile){let pointer=parseJson(await readFileOrUndefined(pointerFile).catch(()=>{}));return typeof pointer?.instance_id=="string"?pointer.instance_id:void 0}async function readOwner(file){let parsed;try{parsed=JSON.parse(await readFile4(file,"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let{instanceId,pid,processStartTime,sessionPath,attached}=parsed;if(!(typeof instanceId!="string"||typeof pid!="number"||typeof sessionPath!="string"))return{instanceId,pid,processStartTime:typeof processStartTime=="string"?processStartTime:null,sessionPath,...typeof attached=="boolean"?{attached}:{}}}async function claimOwnerIsLive(owner){if(!processIsLive(owner.pid))return!1;let recorded=owner.processStartTime===null?void 0:processStartTimeMs(owner.processStartTime);if(recorded===void 0)return logUnknownHostIdentity("session-path-claim",owner.pid),!0;let current=await readProcessStartTime(owner.pid).catch(()=>{}),observed=current===void 0?void 0:processStartTimeMs(current);return observed===void 0||sameProcessStartMs(recorded,observed)}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}var HOST_GENERATION_ENV="SENPI_RPC_HOST_GENERATION",HOST_INSTANCE_ID_ENV="SENPI_RPC_HOST_INSTANCE_ID";var HOST_COLD_START_ENV="SENPI_RPC_HOST_COLD_START",HOST_IDLE_EXIT_MS_ENV="SENPI_RPC_HOST_IDLE_EXIT_MS",DEFAULT_HOST_IDLE_EXIT_MS=9e5,HANDOFF_GRACE_MS_ENV="SENPI_RPC_HANDOFF_GRACE_MS",DEFAULT_HANDOFF_GRACE_MS=6e5;function parseColdStart(value){return value==="transient"||value==="persistent"?value:void 0}function parseIdleExitMs(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveHostPolicy(settings,env){let record=isRecord2(settings)?settings:{},coldStart=parseColdStart(env[HOST_COLD_START_ENV])??parseColdStart(asOptionalString(record.coldStart))??"transient",idleExitMs=parseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV])??parseIdleExitMs(asOptionalString(record.idleExitMs))??9e5;return{coldStart,idleExitMs}}var IdleExitDecider=class{constructor(idleExitMs,now=Date.now){this.idleExitMs=idleExitMs,this.now=now}update(activity){return activity.connections>0||activity.activeTurns>0?(this.idleSince=void 0,"active"):this.idleExitMs===Number.POSITIVE_INFINITY?"idle":this.idleSince===void 0?(this.idleSince=this.now(),"idle"):this.now()-this.idleSince>=this.idleExitMs?"exit":"idle"}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function asOptionalString(value){return typeof value=="string"?value:typeof value=="number"?String(value):void 0}import{rename as rename4,rm as rm6}from"node:fs/promises";import{readdir as readdir3,rm as rm5}from"node:fs/promises";import{readdir as readdir2}from"node:fs/promises";import{readdirSync,readFileSync}from"node:fs";function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadProcessTableReader(platform=process.platform,options={}){let supported=supportedPlatform(platform);return supported===void 0||typeof globalThis.Bun>"u"?void 0:supported==="darwin"?await darwinReader(options):linuxReader}var KINFO_PROC_STRIDE=648,KINFO_PID_OFFSET=40,KINFO_PPID_OFFSET=560,KINFO_STAT_OFFSET=36,SZOMB=5,PROC_PIDTASKINFO=4,TASKINFO_RESIDENT_OFFSET=8,TABLE_START_BYTES=1<<20,TABLE_MAX_BYTES=32<<20;function parseKernelProcessTable(table,rowCount,residentKb){if(rowCount<=0||table.byteLength<rowCount*KINFO_PROC_STRIDE)return;let view=new DataView(table.buffer,table.byteOffset,table.byteLength),rows=[],selfSeen=!1;for(let index=0;index<rowCount;index++){let base=index*KINFO_PROC_STRIDE,pid=view.getUint32(base+KINFO_PID_OFFSET,!0);if(!Number.isInteger(pid)||pid<=0)continue;let ppid=view.getUint32(base+KINFO_PPID_OFFSET,!0),zombie=table[base+KINFO_STAT_OFFSET]===SZOMB;if(pid===process.pid){if(ppid!==process.ppid||zombie)return;selfSeen=!0}rows.push({pid,ppid,state:zombie?"Z":"U",rssKb:residentKb(pid)})}return selfSeen?rows:void 0}async function darwinReader(options){let{dlopen,FFIType,ptr}=await import("bun:ffi"),library=dlopen("libSystem.B.dylib",{sysctl:{args:[FFIType.ptr,FFIType.u32,FFIType.ptr,FFIType.ptr,FFIType.ptr,FFIType.i32],returns:FFIType.i32},proc_pidinfo:{args:[FFIType.i32,FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),mib=new Int32Array([1,14,0]),none=new Uint8Array(1),requested=options.initialTableBytes,table=new Uint8Array(Number.isFinite(requested)&&requested!==void 0&&requested>0?Math.min(Math.floor(requested),TABLE_MAX_BYTES):TABLE_START_BYTES),length=new Uint32Array(1),taskInfo=new Uint8Array(256),taskView=new DataView(taskInfo.buffer),residentKb=pid=>(taskInfo.fill(0),library.symbols.proc_pidinfo(pid,PROC_PIDTASKINFO,0,ptr(taskInfo),taskInfo.byteLength)>0?Math.round(Number(taskView.getBigUint64(TASKINFO_RESIDENT_OFFSET,!0))/1024):0);return()=>{for(;;){if(length[0]=table.byteLength,library.symbols.sysctl(ptr(mib),mib.length,ptr(table),ptr(length),ptr(none),0)!==0){if(table.byteLength>=TABLE_MAX_BYTES)return;let reported=length[0]>table.byteLength?length[0]:0;table=new Uint8Array(Math.min(TABLE_MAX_BYTES,Math.max(table.byteLength*2,reported)));continue}return parseKernelProcessTable(table,Math.floor(length[0]/KINFO_PROC_STRIDE),residentKb)}}}function linuxReader(){let rows=[];for(let entry of readdirSync("/proc")){let pid=Number(entry);if(!Number.isInteger(pid)||pid<=0)continue;let stat3;try{stat3=readFileSync(`/proc/${pid}/stat`,"utf8")}catch{continue}let tail=stat3.slice(stat3.lastIndexOf(")")+2).split(" "),state=tail[0],ppid=Number(tail[1]);if(state===void 0||!Number.isInteger(ppid))continue;let rssPages=Number(tail[21]);rows.push({pid,ppid,state,rssKb:Number.isFinite(rssPages)?Math.round(rssPages*4):0})}return rows}var UNOBSERVED={rss_mb:null,host_rss_mb:null,open_fds:null,zombies:null},readers=new Map;function tableReader(platform){let cached=readers.get(platform);if(cached!==void 0)return cached;let loading=loadProcessTableReader(platform);return readers.set(platform,loading),loading}async function readHostProcessMetrics(pid,platform=process.platform){if(platform==="win32")return UNOBSERVED;let read=await tableReader(platform);if(read===void 0)return UNOBSERVED;let rows=read();if(rows===void 0)return UNOBSERVED;let tree=descendants(rows,pid);return tree.length===0?UNOBSERVED:{rss_mb:residentMegabytes(tree),host_rss_mb:residentMegabytes(tree.filter(row=>row.pid===pid||row.ppid===pid)),open_fds:platform==="linux"?await openDescriptors(tree):null,zombies:tree.filter(row=>row.state.startsWith("Z")).length}}function residentMegabytes(rows){return Math.round(rows.reduce((total,row)=>total+row.rssKb,0)/KILOBYTES_PER_MEGABYTE)}function descendants(rows,root){let tree=rows.filter(row=>row.pid===root);if(tree.length===0)return tree;for(let index=0;index<tree.length;index++){let parent=tree[index].pid;for(let row of rows)row.ppid===parent&&!tree.includes(row)&&tree.push(row)}return tree}var KILOBYTES_PER_MEGABYTE=1024;async function openDescriptors(tree){let total=0,counted=!1;for(let row of tree){let entries=await readdir2(`/proc/${row.pid}/fd`).catch(()=>{});entries!==void 0&&(counted=!0,total+=entries.length)}return counted?total:null}import{rm as rm4}from"node:fs/promises";import{join as join7}from"node:path";var STALL_REFUSAL_WINDOW_MS_ENV="SENPI_RPC_STALL_REFUSAL_MS",DEFAULT_STALL_REFUSAL_WINDOW_MS=12e4,STOP_STALL_EVIDENCE_MAX_AGE_MS=6e4,CHILD_STALLED_STOP_MAX_MS_ENV="SENPI_RPC_CHILD_STALLED_STOP_MAX_MS",DEFAULT_CHILD_STALLED_STOP_MAX_MS=6e4;function childStalledStopMaxMs(env=process.env){return parseIdleExitMs(env[CHILD_STALLED_STOP_MAX_MS_ENV])??DEFAULT_CHILD_STALLED_STOP_MAX_MS}function ownGenerationDir(env){let daemonDir=env[HOST_DAEMON_DIR_ENV],instanceId=env[HOST_INSTANCE_ID_ENV];if(!(!daemonDir||!instanceId))return join7(daemonDir,"generations",instanceId)}function stallRefusalWindowMs(env=process.env){return parseIdleExitMs(env[STALL_REFUSAL_WINDOW_MS_ENV])??DEFAULT_STALL_REFUSAL_WINDOW_MS}function writeStallEvidence(generationDir,evidence){return writeJsonAtomic(join7(generationDir,"host-stalled.json"),evidence)}function writeHeartbeat(generationDir,at){return writeJsonAtomic(join7(generationDir,"host-alive.json"),{at})}async function readStallEvidence(generation){let raw=await readJsonObject(generation.stalledFile);if(!(raw===void 0||typeof raw.at!="string"||typeof raw.driftMs!="number"))return{at:raw.at,driftMs:raw.driftMs,processCpuMs:typeof raw.processCpuMs=="number"?raw.processCpuMs:0,heapDeltaMb:typeof raw.heapDeltaMb=="number"?raw.heapDeltaMb:0,...typeof raw.sessionId=="string"?{sessionId:raw.sessionId}:{},...typeof raw.tool=="string"?{tool:raw.tool}:{}}}async function recentStall(generation,now,maxAgeMs){let evidence=await readStallEvidence(generation),age=ageOf(evidence?.at,now);return evidence!==void 0&&age!==void 0&&age<=maxAgeMs?evidence:void 0}async function hostLoopStalled(generation,options){if(await recentStall(generation,options.now,options.windowMs)!==void 0)return!0;let heartbeatAge=ageOf((await readJsonObject(generation.aliveFile))?.at,options.now);return heartbeatAge!==void 0&&heartbeatAge>options.errorMs&&heartbeatAge<options.windowMs}async function hostChildAlive(generation){let record=await readJsonObject(generation.childPidFile),pid=record?.pid;if(typeof pid!="number"||!Number.isInteger(pid)||pid<=0)return;if(!processIsLive(pid))return!1;let observed=await readProcessIdentity(pid,process.platform,1e3,processIsLive,"UTC");if(!processIsLive(pid))return!1;let recordedMs=typeof record?.processStartTime=="string"?processStartTimeMs(record.processStartTime):void 0,observedMs=observed.kind==="present"?processStartTimeMs(observed.identity):void 0;return recordedMs!==void 0&&observedMs!==void 0?sameProcessStartMs(recordedMs,observedMs):(supervisorLog(`host child pid ${pid} start time unreadable; preserving generation`),!0)}function writeStopProgress(generation,progress){return writeJsonAtomic(generation.stopProgressFile,progress)}async function clearStopProgress(generation){await rm4(generation.stopProgressFile,{force:!0}).catch(()=>{})}async function activeStopProgress(generation,now,freshMs){let raw=await readJsonObject(generation.stopProgressFile),age=ageOf(raw?.at,now),untilAt=typeof raw?.untilAt=="string"?Date.parse(raw.untilAt):Number.NaN;if(!(age===void 0||age>freshMs||Number.isNaN(untilAt)||untilAt<=now))return untilAt}async function pruneDeadGenerations(paths){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile).catch(()=>{})),pointedAt=typeof pointer?.instance_id=="string"?pointer.instance_id:void 0,generations=[];for(let instanceId of await readdir3(paths.generationsDir).catch(()=>[])){let record=parseJson(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));typeof record?.pid!="number"||processIsLive(record.pid)||await hostChildAlive(generationPaths(paths,instanceId))||(await rm5(generationPaths(paths,instanceId).dir,{recursive:!0,force:!0}).catch(()=>{}),generations.push(instanceId))}let pointerRemoved=pointedAt!==void 0&&generations.includes(pointedAt);pointerRemoved&&await rm5(paths.pointerFile,{force:!0}).catch(()=>{});let claims=[];for(let claim of await readSessionPathClaims(paths.reservationsDir))await claimOwnerIsLive(claim.owner)||(await rm5(claim.file,{force:!0}).catch(()=>{}),claims.push(claim.owner.sessionPath));return{generations,claims,pointer:pointerRemoved}}function memoryOf(metrics){return{rss_mb:metrics.rss_mb,host_rss_mb:metrics.host_rss_mb}}async function readGenerationRows(paths,options={}){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile).catch(()=>{})),currentId=typeof pointer?.instance_id=="string"?pointer.instance_id:void 0,claims=await readSessionPathClaims(paths.reservationsDir),rows=[];for(let instanceId of await readdir3(paths.generationsDir).catch(()=>[])){let record=parseJson(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));if(typeof record?.pid!="number")continue;let alive=processIsLive(record.pid)||await hostChildAlive(generationPaths(paths,instanceId))===!0;!alive&&options.includeDead!==!0||rows.push({instanceId,generation:typeof record.generation=="number"?record.generation:0,pid:record.pid,engineVersion:typeof record.engineVersion=="string"?record.engineVersion:null,...alive?memoryOf(await readHostProcessMetrics(record.pid)):{rss_mb:null,host_rss_mb:null},sessions:claims.filter(claim=>claim.owner.instanceId===instanceId).length,current:instanceId===currentId,alive})}return rows.sort((left,right)=>left.generation-right.generation)}async function readHostRegistration(paths){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile));if(!pointer||typeof pointer.instance_id!="string")return;let text=await readFileOrUndefined(generationPaths(paths,pointer.instance_id).pidFile),record=text===void 0?void 0:parseDaemonPidFile(text);if(record===void 0)return;let parsed=parseJson(text)??{},writer=parseWriter(parsed);return{record,...writer&&{writer},...typeof parsed.socket=="string"&&{socket:parsed.socket},instanceId:pointer.instance_id,generation:typeof parsed.generation=="number"?parsed.generation:0}}async function writeHostRegistration(paths,registration,options={}){options.fresh!==!0&&await pruneDeadGenerations(paths);let{generation,writer}=await writeGenerationRecord(paths,registration);await writeStateFile(`${paths.pointerFile}.${process.pid}.tmp`,{layout:HOST_DAEMON_LAYOUT,instance_id:registration.instanceId,generation_dir:generation.relativeDir,writer}),await rename4(`${paths.pointerFile}.${process.pid}.tmp`,paths.pointerFile)}async function writeGenerationRecord(paths,registration){let generation=generationPaths(paths,registration.instanceId),writer={pid:process.pid,startTime:await thisProcessStartTime()},{build}=registration;return await createGenerationDirectory(generation),await writeStateFile(generation.pidFile,{...registration.record,instance_id:registration.instanceId,generation:registration.generation,...build&&{engineVersion:build.text,engineOrdinal:build.ordinal},launchProfileId:registration.launchProfileId,socket:registration.socket,writer}),{generation,writer}}async function clearHostRegistration(paths){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile));if(typeof pointer?.instance_id=="string"){if(await hostChildAlive(generationPaths(paths,pointer.instance_id)))throw new Error(`refusing to clear generation ${pointer.instance_id} with a live host child`);await rm6(generationPaths(paths,pointer.instance_id).dir,{recursive:!0,force:!0})}await rm6(paths.settingsFile,{force:!0}),await rm6(paths.pointerFile,{force:!0})}async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId);if(await hostChildAlive(generation))return;let record=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record!==void 0&&record.pid!==owner.pid)return;if(owner.superseded===!0){await rm6(generation.dir,{recursive:!0,force:!0});return}let ownsPointer=parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId;ownsPointer&&await rm6(paths.settingsFile,{force:!0}),await rm6(generation.dir,{recursive:!0,force:!0}),ownsPointer&&await rm6(paths.pointerFile,{force:!0})}async function provenOwner(registered,socket){let record=registered?.record;if(!record||registered?.socket!==void 0&&!sameEndpoint(registered.socket,socket))return;if(record.processStartTime===null){processIsLive(record.pid)&&logUnknownHostIdentity("host.pid",record.pid);return}let identity={pid:record.pid,processStartTime:record.processStartTime};return await processMatchesPidFile(identity,readProcessStartTime).catch(error=>(error instanceof ProcessIdentityUnreadableError&&logUnknownHostIdentity("host.pid",identity.pid),!1))?{...identity,instanceId:registered.instanceId}:void 0}async function writtenByThisProcess(writer,readStartTime){if(writer===void 0||writer.pid!==process.pid||writer.startTime===null)return!1;let startTime=readStartTime?await readStartTime(process.pid).then(value=>value??null,()=>null):await thisProcessStartTime();return sameProcessStartMs(processStartTimeMs(writer.startTime),startTime===null?void 0:processStartTimeMs(startTime))}var selfStartTime;function thisProcessStartTime(){return selfStartTime??=readProcessStartTime(process.pid).then(value=>value??null,()=>null),selfStartTime}function parseWriter(parsed){if(!isRecord(parsed.writer)||typeof parsed.writer.pid!="number")return;let{pid,startTime}=parsed.writer;return{pid,startTime:typeof startTime=="string"?startTime:null}}import{createHash as createHash3,randomBytes,timingSafeEqual}from"node:crypto";import{chmod as chmod3,mkdir as mkdir4,readFile as readFile5,writeFile as writeFile5}from"node:fs/promises";import{dirname as dirname3,win32 as win322}from"node:path";var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){try{let existing=await readFile5(path);if(existing.length===SOCKET_SECRET_BYTES)return existing}catch(error){if(!isNodeErrorCode2(error,"ENOENT"))throw error}return createSocketSecret(path)}async function createSocketSecret(path){await mkdir4(dirname3(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile5(path,secret,{mode:384}),await chmod3(path,384),secret}async function readSocketSecret(path){let secret=await readFile5(path);if(secret.length!==SOCKET_SECRET_BYTES)throw new Error(`invalid RPC socket secret: ${path}`);return secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win322.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash3("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode2(error,code){return error instanceof Error&&"code"in error&&error.code===code}import{mkdir as mkdir5,readFile as readFile6,rename as rename5,stat,unlink,writeFile as writeFile6}from"node:fs/promises";import{dirname as dirname4}from"node:path";var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner",SOCKET_IDENTITY_WAIT_MS=3e4,MAX_SOCKET_PATH_BYTES=103;function generationBindPath(publicSocket,generation){return`${publicSocket}.next-${generation}`}function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}async function statSocketIdentity(socketPath){try{let{dev,ino}=await stat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}}async function classifyEndpointOwnership(socketPath,identity){if(identity===void 0||process.platform==="win32"||socketPath.startsWith("\0"))return"unknown";let current;try{current=await statSocketIdentity(socketPath)}catch{return"unknown"}return current===void 0?"absent":sameSocketIdentity(current,identity)?"held":"replaced"}async function socketEntryReplaced(socketPath,identity){return await classifyEndpointOwnership(socketPath,identity)==="replaced"}async function writeSocketIdentityFile(path,identity){await mkdir5(dirname4(path),{recursive:!0,mode:448});let tmpPath=`${path}.${process.pid}.tmp`;await writeFile6(tmpPath,`${JSON.stringify(identity)}
9
+ `,{mode:384}),await rename5(tmpPath,path)}async function readSocketIdentityFile(path){let raw;try{raw=await readFile6(path,"utf8")}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}let parsed;try{parsed=JSON.parse(raw)}catch{return}if(!(typeof parsed!="object"||parsed===null||typeof parsed.dev!="number"||typeof parsed.ino!="number"))return{dev:parsed.dev,ino:parsed.ino}}async function waitForSocketIdentityFile(path,timeoutMs=SOCKET_IDENTITY_WAIT_MS,intervalMs=25){let deadline=Date.now()+timeoutMs;for(;;){let identity=await readSocketIdentityFile(path);if(identity!==void 0)return identity;if(Date.now()>=deadline)return;await delayUnrefed(intervalMs)}}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage3(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink(socketPath)}catch(cause){isNodeErrorCode3(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage3(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename5(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename5(shieldPath,socketPath)}catch{}}}function delayUnrefed(ms){return new Promise(resolve2=>{setTimeout(resolve2,ms).unref?.()})}function errorMessage3(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode3(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}import{StringDecoder}from"node:string_decoder";function serializeJsonLine(value){return`${JSON.stringify(value)}
10
+ `}var MAX_RPC_LINE_CHARACTERS=16*1024*1024;function attachJsonlLineReader(stream,onLine,options={}){let decoder=new StringDecoder("utf8"),maxLineLength=options.maxLineLength??Number.POSITIVE_INFINITY;if(!(maxLineLength>0))throw new Error("maxLineLength must be greater than zero.");let buffer="",discardingOversizedLine=!1,consume=text=>{let offset=0;for(;offset<text.length;){if(discardingOversizedLine){let newlineIndex2=text.indexOf(`
11
+ `,offset);if(newlineIndex2===-1)return;discardingOversizedLine=!1,offset=newlineIndex2+1;continue}let newlineIndex=text.indexOf(`
12
+ `,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}import{stat as stat2}from"node:fs/promises";var LegacyLockArtifactError=class extends Error{constructor(lockPath){super(`Legacy lock directory is present at ${lockPath}`),this.code="ELEGACY_LOCK_ARTIFACT",this.name="LegacyLockArtifactError",this.lockPath=lockPath}},DEFAULT_RETRIES={retries:100,minTimeout:20,maxTimeout:100};async function openLockDatabase(lockPath){if(typeof globalThis.Bun<"u"){let{Database}=await import("bun:sqlite"),database2=new Database(lockPath,{create:!0});return{exec:sql=>database2.exec(sql),close:()=>database2.close(!1)}}let{DatabaseSync}=await import("node:sqlite"),database=new DatabaseSync(lockPath);return{exec:sql=>database.exec(sql),close:()=>database.close()}}async function acquireOwnershipSafeLock(lockPath,options={}){let retries=options.retries??DEFAULT_RETRIES,deadline=Date.now()+retries.retries*retries.maxTimeout;for(;;){await rejectLegacyDirectory(lockPath);let busyMs=Math.max(1,Math.min(retries.maxTimeout,deadline-Date.now())),database;try{database=await openLockDatabase(lockPath),database.exec(`PRAGMA busy_timeout = ${busyMs}; BEGIN EXCLUSIVE;`);let released=!1,held=database;return async()=>{if(!released){released=!0;try{held.exec("COMMIT;")}finally{held.close()}}}}catch(error){try{database?.close()}catch{}if(await rejectLegacyDirectory(lockPath),isBusy(error)&&Date.now()<deadline){await new Promise(resolve2=>setTimeout(resolve2,Math.min(retries.minTimeout,Math.max(1,deadline-Date.now()))));continue}throw error}}}async function rejectLegacyDirectory(lockPath){try{if((await stat2(lockPath)).isDirectory())throw new LegacyLockArtifactError(lockPath)}catch(error){if(error instanceof LegacyLockArtifactError||error.code!=="ENOENT")throw error}}function isBusy(error){let message=error instanceof Error?error.message:String(error);return/busy|locked/i.test(message)||error?.code==="SQLITE_BUSY"}export{canonicalSessionPath,sessionDirectoryRemoved,canonicalEndpointPath,daemonDirectoryName,sameEndpoint,socketNamesDirectory,shardKey,shardSocketPathForKey,shardSocketPath,parseShardSocket,generationPaths,HOST_DAEMON_LAYOUT,HOST_DAEMON_DIR_ENV,ENDPOINT_REGISTRY_VERSION,HOST_STATE_FILE_MODE,createHostDaemonPaths,hostDaemonDirectoryPaths,createDaemonDirectories,ensureEndpointIdentity,writeJsonAtomic,readJsonObject,ageOf,readHostOwner,writeHostOwner,sameHostOwner,callerHostOwner,hostOwnerGone,claimHostOwner,writeHostSettings,readHostSettings,writeStateFile,readFileOrUndefined,parseJson,readHostProcessMetrics,writeStderrLine,supervisorLog,logUnknownHostIdentity,errorMessage,SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,readSessionPathClaims,claimOwnerIsLive,HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,DEFAULT_HANDOFF_GRACE_MS,parseColdStart,parseIdleExitMs,resolveHostPolicy,IdleExitDecider,STOP_STALL_EVIDENCE_MAX_AGE_MS,CHILD_STALLED_STOP_MAX_MS_ENV,childStalledStopMaxMs,ownGenerationDir,stallRefusalWindowMs,writeStallEvidence,writeHeartbeat,recentStall,hostLoopStalled,hostChildAlive,writeStopProgress,clearStopProgress,activeStopProgress,pruneDeadGenerations,readGenerationRows,readHostRegistration,writeHostRegistration,writeGenerationRecord,clearHostRegistration,releaseGeneration,provenOwner,writtenByThisProcess,thisProcessStartTime,SOCKET_SECRET_FILE_ENV,socketSecretPath,ensureSocketSecret,createSocketSecret,readSocketSecret,resolveSocketTransportAddress,authenticateSocket,sendSocketHandshake,PUBLIC_SOCKET_IDENTITY_FILE,MAX_SOCKET_PATH_BYTES,generationBindPath,statSocketIdentity,classifyEndpointOwnership,socketEntryReplaced,writeSocketIdentityFile,readSocketIdentityFile,waitForSocketIdentityFile,unlinkOwnedSocket,shieldSocketDuringClose,acquireOwnershipSafeLock,serializeJsonLine,MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader};