@code-yeongyu/senpi 2026.9.18 → 2026.9.19

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 (195) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/dist/bundle/chunks/{anthropic-messages-ZEJ3DPCP.js → anthropic-messages-WZCFP6BT.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-ELSORC4D.js → app-server-command-QK7Q6XK5.js} +1 -1
  4. package/dist/bundle/chunks/bun-extension-importer-JQZRPNJH.js +10 -0
  5. package/dist/bundle/chunks/{chunk-Y6HDGVS5.js → chunk-34GCWLNV.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-XJUVWITG.js → chunk-3FRTRCR6.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-VRAYXSST.js → chunk-FDLVINNY.js} +2 -2
  8. package/dist/bundle/chunks/{chunk-QNZ24YOQ.js → chunk-HGAX6JZ7.js} +3 -1
  9. package/dist/bundle/chunks/{chunk-QGBRSL64.js → chunk-HSH674C6.js} +1 -1
  10. package/dist/bundle/chunks/chunk-IUZUN32Z.js +13 -0
  11. package/dist/bundle/chunks/chunk-IXAUDPOK.js +2 -0
  12. package/dist/bundle/chunks/{chunk-AH72FRZ2.js → chunk-KKDSBABY.js} +11 -11
  13. package/dist/bundle/chunks/{chunk-NLOZDJQX.js → chunk-LF3XTYYF.js} +3 -3
  14. package/dist/bundle/chunks/{chunk-ANTGWIGI.js → chunk-MUC3MZTV.js} +1 -1
  15. package/dist/bundle/chunks/chunk-NARL7XFO.js +8 -0
  16. package/dist/bundle/chunks/chunk-NQAVM5XL.js +2 -0
  17. package/dist/bundle/chunks/chunk-P7PWCGLJ.js +5 -0
  18. package/dist/bundle/chunks/{chunk-4C7LNOHI.js → chunk-PLZK7ABD.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-CKNRCW35.js → chunk-RLRLQRI2.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-7FXIHFZU.js → chunk-UAYBYTFN.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-7A47FVQC.js → chunk-W4SRGDQ4.js} +3 -6
  22. package/dist/bundle/chunks/{chunk-QROWINIH.js → chunk-XK24AFYU.js} +1 -1
  23. package/dist/bundle/chunks/cli-main-7SG3K4K3.js +3 -0
  24. package/dist/bundle/chunks/cursor-agent.js +38 -0
  25. package/dist/bundle/chunks/cursor.js +2 -0
  26. package/dist/bundle/chunks/devin-agent.js +5 -0
  27. package/dist/bundle/chunks/devin.js +75 -0
  28. package/dist/bundle/chunks/{help-fast-path-WQCATMI4.js → help-fast-path-RQDCLDQT.js} +1 -1
  29. package/dist/bundle/chunks/host-command-3LS772D5.js +2 -0
  30. package/dist/bundle/chunks/{host-lifecycle-EAXSS3F2.js → host-lifecycle-TA5XGUW5.js} +1 -1
  31. package/dist/bundle/chunks/host-lifecycle.js +20 -0
  32. package/dist/bundle/chunks/interactive-host-runtime-AITXUDCT.js +4 -0
  33. package/dist/bundle/chunks/interactive-mode-7MN6GGCG.js +2 -0
  34. package/dist/bundle/chunks/{multi-session-host-OK6WMHB4.js → multi-session-host-WKX34SOP.js} +1 -1
  35. package/dist/bundle/chunks/{openai-completions-2RS3VSPV.js → openai-completions-TOWYKX2U.js} +1 -1
  36. package/dist/bundle/chunks/{package-manager-cli-C2K4YRGI.js → package-manager-cli-CB2X57TD.js} +1 -1
  37. package/dist/bundle/chunks/{rotation-stream-536AQTIS.js → rotation-stream-KDLA7K6X.js} +1 -1
  38. package/dist/bundle/chunks/rpc-mode-CI6V2SBW.js +2 -0
  39. package/dist/bundle/chunks/{session-picker-BUHK3FCS.js → session-picker-DXCITGLS.js} +1 -1
  40. package/dist/bundle/chunks/session-worker.js +359 -346
  41. package/dist/bundle/chunks/{state-store-OYDXEIXU.js → state-store-HBBOD7I5.js} +1 -1
  42. package/dist/bundle/cli.js +1 -1
  43. package/dist/bundle/index.js +1 -1
  44. package/dist/bundle/rpc-entry.js +1 -1
  45. package/dist/cli/args.d.ts.map +1 -1
  46. package/dist/cli/args.js +2 -0
  47. package/dist/cli/args.js.map +1 -1
  48. package/dist/cli/deferred-commands.d.ts +7 -0
  49. package/dist/cli/deferred-commands.d.ts.map +1 -1
  50. package/dist/cli/deferred-commands.js +12 -0
  51. package/dist/cli/deferred-commands.js.map +1 -1
  52. package/dist/cli/host-command.d.ts +21 -0
  53. package/dist/cli/host-command.d.ts.map +1 -0
  54. package/dist/cli/host-command.js +148 -0
  55. package/dist/cli/host-command.js.map +1 -0
  56. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.d.ts +1 -1
  57. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.d.ts.map +1 -1
  58. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.js +2 -17
  59. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-7.js.map +1 -1
  60. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.d.ts +3 -0
  61. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.d.ts.map +1 -0
  62. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.js +5 -0
  63. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-8.js.map +1 -0
  64. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.d.ts +3 -0
  65. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.d.ts.map +1 -0
  66. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.js +28 -0
  67. package/dist/core/extensions/builtin/prompt-preset/kimi-k2-code.js.map +1 -0
  68. package/dist/core/extensions/builtin/prompt-preset/presets.d.ts.map +1 -1
  69. package/dist/core/extensions/builtin/prompt-preset/presets.js +21 -1
  70. package/dist/core/extensions/builtin/prompt-preset/presets.js.map +1 -1
  71. package/dist/core/extensions/builtin/prompt-preset/settings.d.ts +1 -1
  72. package/dist/core/extensions/builtin/prompt-preset/settings.d.ts.map +1 -1
  73. package/dist/core/extensions/builtin/prompt-preset/settings.js +1 -0
  74. package/dist/core/extensions/builtin/prompt-preset/settings.js.map +1 -1
  75. package/dist/core/extensions/bun-extension-importer.d.ts.map +1 -1
  76. package/dist/core/extensions/bun-extension-importer.js +31 -5
  77. package/dist/core/extensions/bun-extension-importer.js.map +1 -1
  78. package/dist/core/extensions/bun-extension-registry.d.ts +9 -0
  79. package/dist/core/extensions/bun-extension-registry.d.ts.map +1 -1
  80. package/dist/core/extensions/bun-extension-registry.js +72 -16
  81. package/dist/core/extensions/bun-extension-registry.js.map +1 -1
  82. package/dist/core/extensions/extension-runtime-module.d.ts +5 -0
  83. package/dist/core/extensions/extension-runtime-module.d.ts.map +1 -0
  84. package/dist/core/extensions/extension-runtime-module.js +6 -0
  85. package/dist/core/extensions/extension-runtime-module.js.map +1 -0
  86. package/dist/core/model-resolver.d.ts.map +1 -1
  87. package/dist/core/model-resolver.js +1 -0
  88. package/dist/core/model-resolver.js.map +1 -1
  89. package/dist/index.d.ts +2 -1
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +3 -1
  92. package/dist/index.js.map +1 -1
  93. package/dist/main.d.ts.map +1 -1
  94. package/dist/main.js +7 -1
  95. package/dist/main.js.map +1 -1
  96. package/dist/modes/index.d.ts +3 -0
  97. package/dist/modes/index.d.ts.map +1 -1
  98. package/dist/modes/index.js +5 -0
  99. package/dist/modes/index.js.map +1 -1
  100. package/dist/modes/rpc/host-daemon-env.d.ts +18 -0
  101. package/dist/modes/rpc/host-daemon-env.d.ts.map +1 -0
  102. package/dist/modes/rpc/host-daemon-env.js +95 -0
  103. package/dist/modes/rpc/host-daemon-env.js.map +1 -0
  104. package/dist/modes/rpc/host-decision.d.ts +1 -1
  105. package/dist/modes/rpc/host-decision.d.ts.map +1 -1
  106. package/dist/modes/rpc/host-decision.js +2 -0
  107. package/dist/modes/rpc/host-decision.js.map +1 -1
  108. package/dist/modes/rpc/host-ensure.js +8 -1
  109. package/dist/modes/rpc/host-ensure.js.map +1 -1
  110. package/dist/modes/rpc/host-launch-spec.d.ts +43 -0
  111. package/dist/modes/rpc/host-launch-spec.d.ts.map +1 -0
  112. package/dist/modes/rpc/host-launch-spec.js +183 -0
  113. package/dist/modes/rpc/host-launch-spec.js.map +1 -0
  114. package/dist/modes/rpc/host-launch.d.ts +3 -1
  115. package/dist/modes/rpc/host-launch.d.ts.map +1 -1
  116. package/dist/modes/rpc/host-launch.js +24 -5
  117. package/dist/modes/rpc/host-launch.js.map +1 -1
  118. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  119. package/dist/modes/rpc/host-lifecycle.js +36 -2
  120. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  121. package/dist/modes/rpc/host-probe.d.ts +7 -0
  122. package/dist/modes/rpc/host-probe.d.ts.map +1 -1
  123. package/dist/modes/rpc/host-probe.js +15 -4
  124. package/dist/modes/rpc/host-probe.js.map +1 -1
  125. package/dist/modes/rpc/host-process-metrics.d.ts +10 -0
  126. package/dist/modes/rpc/host-process-metrics.d.ts.map +1 -0
  127. package/dist/modes/rpc/host-process-metrics.js +83 -0
  128. package/dist/modes/rpc/host-process-metrics.js.map +1 -0
  129. package/dist/modes/rpc/host-runner.d.ts +38 -0
  130. package/dist/modes/rpc/host-runner.d.ts.map +1 -0
  131. package/dist/modes/rpc/host-runner.js +195 -0
  132. package/dist/modes/rpc/host-runner.js.map +1 -0
  133. package/dist/modes/rpc/host-status.d.ts +58 -0
  134. package/dist/modes/rpc/host-status.d.ts.map +1 -0
  135. package/dist/modes/rpc/host-status.js +117 -0
  136. package/dist/modes/rpc/host-status.js.map +1 -0
  137. package/docs/extensions.md +35 -0
  138. package/docs/providers.md +30 -0
  139. package/docs/rpc.md +177 -15
  140. package/docs/settings.md +1 -1
  141. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +72 -0
  142. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  143. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  144. package/node_modules/@earendil-works/pi-ai/README.md +9 -0
  145. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  146. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +1 -0
  147. package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  148. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts +2 -2
  149. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts.map +1 -1
  150. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js +2 -2
  151. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js.map +1 -1
  152. package/node_modules/@earendil-works/pi-ai/dist/providers/all.d.ts +150 -7
  153. package/node_modules/@earendil-works/pi-ai/dist/providers/all.d.ts.map +1 -1
  154. package/node_modules/@earendil-works/pi-ai/dist/providers/all.js +17 -3
  155. package/node_modules/@earendil-works/pi-ai/dist/providers/all.js.map +1 -1
  156. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.d.ts +13 -0
  157. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.d.ts.map +1 -0
  158. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.js +55 -0
  159. package/node_modules/@earendil-works/pi-ai/dist/providers/bai-stream.js.map +1 -0
  160. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.d.ts +11 -0
  161. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.d.ts.map +1 -0
  162. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.js +94 -0
  163. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.js.map +1 -0
  164. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.d.ts +4 -0
  165. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.d.ts.map +1 -0
  166. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.js +6 -0
  167. package/node_modules/@earendil-works/pi-ai/dist/providers/bai.models.js.map +1 -0
  168. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  169. package/node_modules/@earendil-works/pi-ai/dist/providers/data/bai.json +1 -0
  170. package/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
  171. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  172. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  173. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  174. package/node_modules/@earendil-works/pi-ai/dist/providers/data/venice.json +1 -1
  175. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  176. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.d.ts +142 -1
  177. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.d.ts.map +1 -1
  178. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.js +156 -3
  179. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.models.js.map +1 -1
  180. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +1 -1
  181. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  182. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  183. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  184. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  185. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  186. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  187. package/package.json +7 -7
  188. package/dist/bundle/chunks/bun-extension-importer-SW7XGNSG.js +0 -10
  189. package/dist/bundle/chunks/chunk-AGXZF7RF.js +0 -2
  190. package/dist/bundle/chunks/chunk-F5JZNLDE.js +0 -8
  191. package/dist/bundle/chunks/cli-main-4TWJXJKM.js +0 -3
  192. package/dist/bundle/chunks/interactive-host-runtime-EDXG6A5L.js +0 -4
  193. package/dist/bundle/chunks/interactive-mode-PD7S7KFZ.js +0 -2
  194. package/dist/bundle/chunks/rpc-mode-TIJFUWXS.js +0 -2
  195. package/node_modules/@earendil-works/pi-ai/dist/providers/data/kimi-coding.json +0 -1
@@ -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{DEFAULT_HOST_IDLE_EXIT_MS,HOST_DAEMON_DIR_ENV,INTERNAL_SUPERVISOR_FLAG,MAX_SOCKET_PATH_BYTES,ProcessIdentityUnreadableError,clearHostRegistration,createDaemonDirectories,createHostDaemonPaths,createSocketSecret,generationBindPath,legacyHostIsLive,processIsLive,processMatchesPidFile,provenOwner,readHostRegistration,readHostSettings,readProcessStartTime,readSocketSecret,releaseGeneration,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath,statSocketIdentity,waitForStartTime,writeHostRegistration,writeHostSettings,writtenByThisProcess}from"./chunk-NLOZDJQX.js";import{CUSTOM_UNSUPPORTED_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,RPC_CLIENT_CAPABILITIES_ENV,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY}from"./chunk-U6Z6OBX4.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,attachJsonlLineReader,compareEngineOrdinal,engineBuildIdentity,hostLaunchProfile,serializeJsonLine}from"./chunk-QGBRSL64.js";import{sanitizeBinaryOutput}from"./chunk-2H3Y7EYQ.js";import{dropFailedAssistantTurns}from"./chunk-VRAYXSST.js";import{copyContextProvenance}from"./chunk-OYXTZDVT.js";import{APP_NAME,ENV_AGENT_DIR,getAgentDir,getSessionsDir,isBunBinary,normalizePath,resolvePath}from"./chunk-H5RK2RYZ.js";var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
2
+ import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-LF3XTYYF.js";import{attachJsonlLineReader,serializeJsonLine}from"./chunk-HSH674C6.js";import{sanitizeBinaryOutput}from"./chunk-2H3Y7EYQ.js";import{dropFailedAssistantTurns}from"./chunk-FDLVINNY.js";import{copyContextProvenance}from"./chunk-OYXTZDVT.js";import{APP_NAME,getAgentDir,getSessionsDir,normalizePath,resolvePath}from"./chunk-H5RK2RYZ.js";var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
3
3
 
4
4
  <summary>
5
5
  `,COMPACTION_SUMMARY_SUFFIX=`
@@ -31,13 +31,10 @@ Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(t
31
31
  `);return content.endsWith(`
32
32
  `)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
33
33
  `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
34
- `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str,maxBytes){let buf=Buffer.from(str,"utf-8");if(buf.length<=maxBytes)return str;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}import{randomBytes as randomBytes2}from"node:crypto";import{createWriteStream}from"node:fs";import{rm}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join4}from"node:path";function ansiRegex({onlyFirst=!1}={}){let pattern="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(pattern,onlyFirst?void 0:"g")}var regex=ansiRegex();function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(regex,"")}var NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS=5e3;async function executeBashWithOperations(command,cwd,operations,options){let outputChunks=[],callbackAbortController=new AbortController,executionSignal=options?.signal?AbortSignal.any([options.signal,callbackAbortController.signal]):callbackAbortController.signal,callbackError,hasCallbackError=!1,callbacksAbandoned=!1,callbackPromises=new Set,waitForCallbacks=async allowAbandonment=>{if(callbackPromises.size===0)return!0;let settled=Promise.allSettled([...callbackPromises]).then(()=>!0),timeout,bounded=new Promise(resolve4=>{timeout=setTimeout(resolve4,allowAbandonment?100:NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},outputChunkStart=0,outputBytes=0,maxOutputBytes=51200*2,tempFilePath,tempFileStream,tempFileError,totalBytes=0,compactOutputChunks=()=>{outputChunkStart<64||(outputChunks.splice(0,outputChunkStart),outputChunkStart=0)},outputText=()=>outputChunks.slice(outputChunkStart).join(""),ensureTempFile=()=>{if(tempFilePath)return;let id=randomBytes2(8).toString("hex");tempFilePath=join4(tmpdir(),`pi-bash-${id}.log`),tempFileStream=createWriteStream(tempFilePath),tempFileStream.on("error",error=>{tempFileError??=error});for(let i=outputChunkStart;i<outputChunks.length;i++){let chunk=outputChunks[i];chunk!==void 0&&tempFileStream.write(chunk)}},closeTempFileStream=async()=>{let stream=tempFileStream;if(tempFileStream=void 0,!!stream){if(tempFileError)throw await new Promise(resolve4=>{if(stream.closed){resolve4();return}stream.once("close",resolve4),stream.destroy()}),tempFileError;await new Promise((resolve4,reject)=>{let finished=!1,closed=!1,streamError,settle=()=>{closed&&(stream.off("finish",onFinish),stream.off("error",onError),stream.off("close",onClose),streamError?reject(streamError):finished?resolve4():reject(new Error("Bash spill stream closed before finish")))},onError=error=>{streamError??=error},onFinish=()=>{finished=!0},onClose=()=>{closed=!0,!finished&&!stream.destroyed&&stream.destroy(),settle()};stream.once("error",onError),stream.once("finish",onFinish),stream.once("close",onClose),stream.end()})}},removeTempFile=async()=>{if(!tempFilePath)return;await rm(tempFilePath,{force:!0}),tempFilePath=void 0},closeTempFileAndCleanup=async primaryError=>{let finalError=primaryError;try{await closeTempFileStream()}catch(closeError){finalError=new AggregateError([primaryError,closeError],"Bash output cleanup failed")}try{await removeTempFile()}catch(unlinkError){finalError=new AggregateError([finalError,unlinkError],"Bash output cleanup failed")}throw finalError},decoder=new TextDecoder,onData=data=>{if(callbackAbortController.signal.aborted)return;totalBytes+=data.length;let text=sanitizeBinaryOutput(stripAnsi(decoder.decode(data,{stream:!0}))).replace(/\r/g,"");for(totalBytes>51200&&ensureTempFile(),tempFileStream&&tempFileStream.write(text),outputChunks.push(text),outputBytes+=text.length;outputBytes>maxOutputBytes&&outputChunkStart<outputChunks.length-1;){let removed=outputChunks[outputChunkStart];if(removed===void 0)break;outputBytes-=removed.length,outputChunkStart++}if(compactOutputChunks(),options?.onChunk)try{let callbackResult=options.onChunk(text);if(callbackResult&&typeof callbackResult.then=="function"){let callbackPromise=Promise.resolve(callbackResult).then(()=>{},error=>{throw hasCallbackError||(callbackError=error,hasCallbackError=!0),callbacksAbandoned&&process.emitWarning(`Bash output callback rejected after the command timeout: ${error instanceof Error?error.message:String(error)}`,{code:"BASH_CALLBACK_ERROR"}),callbackAbortController.abort(),error});return callbackPromises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>callbackPromises.delete(callbackPromise)),callbackPromise}}catch(error){throw hasCallbackError||(callbackError=error,hasCallbackError=!0),callbackAbortController.abort(),error}},finishDecoder=()=>{let finalText=sanitizeBinaryOutput(stripAnsi(decoder.decode())).replace(/\r/g,"");finalText.length>0&&onData(Buffer.from(finalText,"utf-8"))},prepareFinalOutput=async()=>{try{finishDecoder();let fullOutput2=outputText(),truncationResult2=truncateTail(fullOutput2);return truncationResult2.truncated&&ensureTempFile(),{fullOutput:fullOutput2,truncationResult:truncationResult2}}catch(error){return await closeTempFileAndCleanup(error)}},result;try{result=await operations.exec(command,cwd,{onData,signal:executionSignal})}catch(err){if(await waitForCallbacks(options?.signal?.aborted===!0),hasCallbackError)return await closeTempFileAndCleanup(callbackError);if(options?.signal?.aborted){let{fullOutput:fullOutput2,truncationResult:truncationResult2}=await prepareFinalOutput();try{await closeTempFileStream()}catch(error){return await closeTempFileAndCleanup(error)}try{await removeTempFile()}catch(cleanupError){throw new AggregateError([cleanupError],"Bash output cleanup failed")}return{output:truncationResult2.truncated?truncationResult2.content:fullOutput2,exitCode:void 0,cancelled:!0,truncated:truncationResult2.truncated}}return await closeTempFileAndCleanup(err)}if(!await waitForCallbacks(!1))return callbacksAbandoned=!0,await closeTempFileAndCleanup(new Error(`Bash output callback did not settle within ${NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS}ms`));if(hasCallbackError)return await closeTempFileAndCleanup(callbackError);let{fullOutput,truncationResult}=await prepareFinalOutput();try{await closeTempFileStream()}catch(error){return await closeTempFileAndCleanup(error)}let cancelled=options?.signal?.aborted??!1;return{output:truncationResult.truncated?truncationResult.content:fullOutput,exitCode:cancelled?void 0:result.exitCode??void 0,cancelled,truncated:truncationResult.truncated,fullOutputPath:tempFilePath}}import{existsSync as existsSync4}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync4(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
34
+ `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str,maxBytes){let buf=Buffer.from(str,"utf-8");if(buf.length<=maxBytes)return str;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}import{randomBytes as randomBytes2}from"node:crypto";import{createWriteStream}from"node:fs";import{rm}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join4}from"node:path";function ansiRegex({onlyFirst=!1}={}){let pattern="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(pattern,onlyFirst?void 0:"g")}var regex=ansiRegex();function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(regex,"")}var NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS=5e3;async function executeBashWithOperations(command,cwd,operations,options){let outputChunks=[],callbackAbortController=new AbortController,executionSignal=options?.signal?AbortSignal.any([options.signal,callbackAbortController.signal]):callbackAbortController.signal,callbackError,hasCallbackError=!1,callbacksAbandoned=!1,callbackPromises=new Set,waitForCallbacks=async allowAbandonment=>{if(callbackPromises.size===0)return!0;let settled=Promise.allSettled([...callbackPromises]).then(()=>!0),timeout,bounded=new Promise(resolve3=>{timeout=setTimeout(resolve3,allowAbandonment?100:NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS,!1),timeout.unref?.()});try{return await Promise.race([settled,bounded])}finally{timeout&&clearTimeout(timeout)}},outputChunkStart=0,outputBytes=0,maxOutputBytes=51200*2,tempFilePath,tempFileStream,tempFileError,totalBytes=0,compactOutputChunks=()=>{outputChunkStart<64||(outputChunks.splice(0,outputChunkStart),outputChunkStart=0)},outputText=()=>outputChunks.slice(outputChunkStart).join(""),ensureTempFile=()=>{if(tempFilePath)return;let id=randomBytes2(8).toString("hex");tempFilePath=join4(tmpdir(),`pi-bash-${id}.log`),tempFileStream=createWriteStream(tempFilePath),tempFileStream.on("error",error=>{tempFileError??=error});for(let i=outputChunkStart;i<outputChunks.length;i++){let chunk=outputChunks[i];chunk!==void 0&&tempFileStream.write(chunk)}},closeTempFileStream=async()=>{let stream=tempFileStream;if(tempFileStream=void 0,!!stream){if(tempFileError)throw await new Promise(resolve3=>{if(stream.closed){resolve3();return}stream.once("close",resolve3),stream.destroy()}),tempFileError;await new Promise((resolve3,reject)=>{let finished=!1,closed=!1,streamError,settle=()=>{closed&&(stream.off("finish",onFinish),stream.off("error",onError),stream.off("close",onClose),streamError?reject(streamError):finished?resolve3():reject(new Error("Bash spill stream closed before finish")))},onError=error=>{streamError??=error},onFinish=()=>{finished=!0},onClose=()=>{closed=!0,!finished&&!stream.destroyed&&stream.destroy(),settle()};stream.once("error",onError),stream.once("finish",onFinish),stream.once("close",onClose),stream.end()})}},removeTempFile=async()=>{if(!tempFilePath)return;await rm(tempFilePath,{force:!0}),tempFilePath=void 0},closeTempFileAndCleanup=async primaryError=>{let finalError=primaryError;try{await closeTempFileStream()}catch(closeError){finalError=new AggregateError([primaryError,closeError],"Bash output cleanup failed")}try{await removeTempFile()}catch(unlinkError){finalError=new AggregateError([finalError,unlinkError],"Bash output cleanup failed")}throw finalError},decoder=new TextDecoder,onData=data=>{if(callbackAbortController.signal.aborted)return;totalBytes+=data.length;let text=sanitizeBinaryOutput(stripAnsi(decoder.decode(data,{stream:!0}))).replace(/\r/g,"");for(totalBytes>51200&&ensureTempFile(),tempFileStream&&tempFileStream.write(text),outputChunks.push(text),outputBytes+=text.length;outputBytes>maxOutputBytes&&outputChunkStart<outputChunks.length-1;){let removed=outputChunks[outputChunkStart];if(removed===void 0)break;outputBytes-=removed.length,outputChunkStart++}if(compactOutputChunks(),options?.onChunk)try{let callbackResult=options.onChunk(text);if(callbackResult&&typeof callbackResult.then=="function"){let callbackPromise=Promise.resolve(callbackResult).then(()=>{},error=>{throw hasCallbackError||(callbackError=error,hasCallbackError=!0),callbacksAbandoned&&process.emitWarning(`Bash output callback rejected after the command timeout: ${error instanceof Error?error.message:String(error)}`,{code:"BASH_CALLBACK_ERROR"}),callbackAbortController.abort(),error});return callbackPromises.add(callbackPromise),callbackPromise.catch(()=>{}).finally(()=>callbackPromises.delete(callbackPromise)),callbackPromise}}catch(error){throw hasCallbackError||(callbackError=error,hasCallbackError=!0),callbackAbortController.abort(),error}},finishDecoder=()=>{let finalText=sanitizeBinaryOutput(stripAnsi(decoder.decode())).replace(/\r/g,"");finalText.length>0&&onData(Buffer.from(finalText,"utf-8"))},prepareFinalOutput=async()=>{try{finishDecoder();let fullOutput2=outputText(),truncationResult2=truncateTail(fullOutput2);return truncationResult2.truncated&&ensureTempFile(),{fullOutput:fullOutput2,truncationResult:truncationResult2}}catch(error){return await closeTempFileAndCleanup(error)}},result;try{result=await operations.exec(command,cwd,{onData,signal:executionSignal})}catch(err){if(await waitForCallbacks(options?.signal?.aborted===!0),hasCallbackError)return await closeTempFileAndCleanup(callbackError);if(options?.signal?.aborted){let{fullOutput:fullOutput2,truncationResult:truncationResult2}=await prepareFinalOutput();try{await closeTempFileStream()}catch(error){return await closeTempFileAndCleanup(error)}try{await removeTempFile()}catch(cleanupError){throw new AggregateError([cleanupError],"Bash output cleanup failed")}return{output:truncationResult2.truncated?truncationResult2.content:fullOutput2,exitCode:void 0,cancelled:!0,truncated:truncationResult2.truncated}}return await closeTempFileAndCleanup(err)}if(!await waitForCallbacks(!1))return callbacksAbandoned=!0,await closeTempFileAndCleanup(new Error(`Bash output callback did not settle within ${NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS}ms`));if(hasCallbackError)return await closeTempFileAndCleanup(callbackError);let{fullOutput,truncationResult}=await prepareFinalOutput();try{await closeTempFileStream()}catch(error){return await closeTempFileAndCleanup(error)}let cancelled=options?.signal?.aborted??!1;return{output:truncationResult.truncated?truncationResult.content:fullOutput,exitCode:cancelled?void 0:result.exitCode??void 0,cancelled,truncated:truncationResult.truncated,fullOutputPath:tempFilePath}}import{existsSync as existsSync4}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync4(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
35
35
  Session file: ${issue.sessionFile}`:"";return`Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}
36
36
  Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`cwd from session file does not exist
37
37
  ${issue.sessionCwd}
38
38
 
39
39
  continue in current cwd
40
- ${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}function parseHostProtocolInfo(data){if(!isRecord(data)||typeof data.serverVersion!="string"||!Array.isArray(data.capabilities)||!data.capabilities.every(entry=>typeof entry=="string"))return;let ordinal=parseOrdinal(data.engineOrdinal),launchProfile=parseLaunchProfile(data.launch_profile);return{protocolVersion:typeof data.protocolVersion=="number"?data.protocolVersion:0,serverVersion:data.serverVersion,capabilities:data.capabilities,...typeof data.instanceId=="string"&&{instanceId:data.instanceId},...typeof data.generation=="number"&&Number.isSafeInteger(data.generation)&&{generation:data.generation},...typeof data.engineVersion=="string"&&{engineVersion:data.engineVersion},...ordinal&&{engineOrdinal:ordinal},...launchProfile&&{launch_profile:launchProfile}}}function parseOrdinal(value){if(!(!Array.isArray(value)||value.length!==5||!value.every(part=>typeof part=="number")))return[value[0],value[1],value[2],value[3],value[4]]}function parseLaunchProfile(value){if(!isRecord(value)||typeof value.profile_id!="string"||!isRecord(value.core))return;let{extensions,multi_session,session_runtime}=value.core;if(!(!Array.isArray(extensions)||!extensions.every(entry=>typeof entry=="string"))&&typeof multi_session=="boolean"&&!(session_runtime!=="in-process"&&session_runtime!=="worker"))return{profile_id:value.profile_id,core:{extensions,multi_session,session_runtime}}}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var HOST_PROTOCOL_VERSION=1,GENERATION_HANDOFF_CAPABILITY="generation_handoff",REQUIRED_HOST_CAPABILITIES=["multi_session",EXTENSION_EVENTS_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY],HostEnsureRefusedError=class extends Error{constructor(socket,reason,host){super(`RPC socket ${socket} refused: ${reason} - ${refusalDetail(reason,host)}`),this.name="HostEnsureRefusedError",this.socket=socket,this.reason=reason}};function refusalDetail(reason,host){switch(reason){case"protocol":return`the running host speaks protocol version ${host?.protocolVersion??"unknown"}, this build speaks ${HOST_PROTOCOL_VERSION}`;case"capability":{let missing=REQUIRED_HOST_CAPABILITIES.filter(capability=>!host?.capabilities.includes(capability));return`the running host is missing ${JSON.stringify(missing)}; it owns the socket, so no second host is started`}case"foreign_writer":return"its pidfile was written by another process, so this one may not signal it; stop that host explicitly instead";case"legacy_host":return"a host from before the per-socket daemon directory is still running on this endpoint; it is never signalled, and no second host is started beside it";default:return assertNever(reason)}}function decideHostAction(client,host,policy){if(host===void 0)return{action:"start",reason:client.startedByUs?"restart_own_host":"no_host",upgradeable:!1};if(host.protocolVersion!==client.protocolVersion)return{action:"refuse",reason:"protocol",upgradeable:!1};if(!client.requiredCapabilities.every(capability=>host.capabilities.includes(capability)))return policy==="fallback"?{action:"fallback",reason:"capability",upgradeable:!1}:{action:"refuse",reason:"capability",upgradeable:!1};let upgradeable=client.platform!=="win32"&&host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY);if(policy==="fallback"&&host.engineVersion!==client.identity.text)return{action:"fallback",reason:"engine_mismatch",upgradeable};let warning=profileWarning(client,host);return client.platform==="win32"?{action:"reuse",reason:"win32_attach_only",upgradeable:!1,...warning&&{warning}}:upgradeable?policy==="upgrade"&&client.launchProfile&&host.launch_profile&&supersedes(client,host)?{action:"handoff",reason:sameRelease(client.identity.ordinal,host.engineOrdinal)?"profile":"newer_engine",upgradeable:!0}:{action:"reuse",reason:"compatible",upgradeable,...warning&&{warning}}:{action:"reuse",reason:"handoff_unsupported",upgradeable:!1,...warning&&{warning}}}function supersedes(client,host){if(host.engineOrdinal===void 0)return!1;let hostIdentity={text:host.engineVersion??"",ordinal:host.engineOrdinal,scheme:host.engineOrdinal[4]>0?"epoch":"nodef"};return compareEngineOrdinal(client.identity,hostIdentity)<=0?!1:covers(client.launchProfile,host.launch_profile)}function profileWarning(client,host){if(client.launchProfile===void 0||host.launch_profile===void 0)return"profile_mismatch_attached";if(client.launchProfile.profile_id!==host.launch_profile.profile_id)return covers(client.launchProfile,host.launch_profile)?"profile_mismatch_attached":"profile_narrower_attached"}function covers(candidate,running){return candidate===void 0||running===void 0?!1:running.core.extensions.every(extension=>candidate.core.extensions.includes(extension))}function sameRelease(candidate,running){return running!==void 0&&candidate.slice(0,4).every((part,index)=>part===running[index])}function assertNever(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}import{createConnection}from"node:net";var DEFAULT_PROBE_TIMEOUT_MS=1e4,PROBE_REQUEST_ID="ensure-host-probe";function probeHost(options){return probeProtocolInfo(options.socket,options.timeoutMs??DEFAULT_PROBE_TIMEOUT_MS)}async function probeProtocolInfo(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info"},timeoutMs);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function probeSessionCount(socketPath,timeoutMs){let reply=await requestOnSocket(socketPath,{type:"list_sessions",include_workers:!0},timeoutMs);if(!(!isRecord2(reply)||!Array.isArray(reply.sessions)))return reply.sessions.length}function requestOnSocket(socketPath,command,timeoutMs){return connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,...command},timeoutMs)}async function connectAndAsk(socketPath,request,timeoutMs){let secret;if(process.platform==="win32")try{secret=await readSocketSecret(socketSecretPath(socketPath))}catch{return}return new Promise(resolveProbe=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),buffer="",settled=!1,finish=value=>{settled||(settled=!0,clearTimeout(timeout),socket.destroy(),resolveProbe(value))},timeout=setTimeout(()=>finish(),timeoutMs);socket.once("connect",()=>{socket.write(`${JSON.stringify(request)}
41
- `)}),socket.on("data",chunk=>{for(buffer+=chunk.toString("utf8");;){let newline=buffer.indexOf(`
42
- `);if(newline===-1)return;let line=buffer.slice(0,newline);buffer=buffer.slice(newline+1);let answer=readAnswer(line);if(answer!==void 0)return finish(answer)}}),socket.once("error",()=>finish()),socket.once("close",()=>finish()),secret&&sendSocketHandshake(socket,secret)})}function readAnswer(text){let parsed;try{parsed=JSON.parse(text)}catch{return}if(!(!isRecord2(parsed)||parsed.id!==PROBE_REQUEST_ID||parsed.success!==!0))return parsed.data??{}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{dirname,resolve as resolve3}from"node:path";import{fileURLToPath}from"node:url";var PINNED_HOST_CLIENT_CAPABILITIES=[EXTENSION_EVENTS_CAPABILITY,CUSTOM_UNSUPPORTED_CAPABILITY];function defaultHostLaunch(supervisorArgs,compiled=isBunBinary){return compiled?{command:process.execPath,args:[INTERNAL_SUPERVISOR_FLAG,...supervisorArgs]}:{command:process.execPath,args:[...process.execArgv,resolveHostLifecycleEntryPath(),...supervisorArgs]}}function resolveHostLifecycleEntryPath(){let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js";return resolve3(dirname(modulePath),`host-lifecycle${extension}`)}async function stopHost(options){let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}}),registered=await readHostRegistration(paths),owner=await provenOwner(registered,options.socket);if(!owner)return{action:"refuse",reason:"unknown_owner"};let host=await probeProtocolInfo(options.socket,options.timeoutMs??1e4);if(options.drain===!0)return!host?.capabilities.includes(GENERATION_HANDOFF_CAPABILITY)||process.platform==="win32"?{action:"refuse",reason:"drain_unsupported"}:(signalGeneration(owner.pid,"SIGUSR1"),{action:"drained",pid:owner.pid});let sessions=await probeSessionCount(options.socket,options.timeoutMs??1e4);return options.force!==!0&&host!==void 0&&sessions!==void 0&&sessions>0?{action:"refuse",reason:"sessions_live"}:(signalGeneration(owner.pid,"SIGTERM"),await releaseGeneration(paths,{instanceId:owner.instanceId,pid:owner.pid}),{action:"stopped",pid:owner.pid})}function signalGeneration(pid,signal){try{return process.kill(pid,signal),!0}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ESRCH")return!1;throw error}}import{spawn}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{open}from"node:fs/promises";var DEFAULT_HANDOFF_READINESS_MS=3e4;async function startSuccessor(context){let{options,paths,host,owner}=context,generation=(host.generation??0)+1,instanceId=randomUUID2(),bindSocket=generationBindPath(options.socket,generation);if(Buffer.byteLength(bindSocket)>MAX_SOCKET_PATH_BYTES)return{action:"refuse",reason:"socket_path_too_long",upgradeable:!0,detail:bindSocket};let replaced=await statSocketIdentity(options.socket);if(!replaced)return{action:"refuse",reason:"socket_replaced",upgradeable:!0};let running=await readHostSettings(paths);await writeHostSettings(paths,{socket:options.socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??running?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??running?.idleExitMs??DEFAULT_HOST_IDLE_EXIT_MS,generation,instanceId}),await options._test?.beforeSpawn?.();let argv=["--socket",options.socket,"--bind",bindSocket,"--replace",`${replaced.dev}:${replaced.ino}`,...options.hostArgs??[]],launch=options._test?.launch?.(argv)??defaultHostLaunch(argv),stderr=await open(paths.stderrLog,"a",384),child=spawn(launch.command,[...launch.args],{detached:!0,windowsHide:!0,env:successorEnv(options,{paths,generation,instanceId}),stdio:["ignore","ignore",stderr.fd]});await stderr.close();let exited=new Promise(resolve4=>child.once("exit",()=>resolve4()));try{if(child.pid===void 0)throw new Error("failed to spawn the successor generation");let answer=await awaitSuccessor(options,host,exited);if(!answer)return child.exitCode===null&&child.signalCode===null&&child.kill("SIGKILL"),{action:"refuse",reason:await abortReason(options.socket,replaced),upgradeable:!0};let processStartTime=await waitForStartTime(child.pid,1e4).catch(()=>{})??null;return await writeHostRegistration(paths,{record:{pid:child.pid,processStartTime},socket:options.socket,instanceId,generation,launchProfileId:hostLaunchProfile(["--mode","rpc","--multi-session",...options.hostArgs??[]],process.cwd()).profile_id}),child.unref(),signalGeneration(owner.pid,"SIGUSR1"),{action:"handoff",pid:child.pid,socket:options.socket,generation:answer.generation??generation,instanceId:answer.instanceId??""}}catch(cause){return child.exitCode===null&&child.signalCode===null&&child.kill("SIGKILL"),{action:"refuse",reason:"successor_unavailable",upgradeable:!0,detail:cause instanceof Error?cause.message:String(cause)}}}async function awaitSuccessor(options,previous,exited){let deadline=Date.now()+(options._test?.readinessTimeoutMs??DEFAULT_HANDOFF_READINESS_MS),childGone=!1;for(exited.then(()=>{childGone=!0});Date.now()<=deadline;){let answer=await probeProtocolInfo(options.socket,2e3);if(answer&&answer.instanceId!==void 0&&answer.instanceId!==previous.instanceId)return answer;if(childGone)return;await delay(50)}}async function abortReason(socket,replaced){let current=await statSocketIdentity(socket).catch(()=>{});return current===void 0||current.dev!==replaced.dev||current.ino!==replaced.ino?"socket_replaced":"successor_unavailable"}function successorEnv(options,successor){let env={...process.env,[HOST_GENERATION_ENV]:String(successor.generation),[HOST_INSTANCE_ID_ENV]:successor.instanceId,[HOST_DAEMON_DIR_ENV]:successor.paths.dir,[RPC_CLIENT_CAPABILITIES_ENV]:PINNED_HOST_CLIENT_CAPABILITIES.join(","),...options.agentDir?{[ENV_AGENT_DIR]:options.agentDir}:{}};for(let[key,value]of Object.entries(options.env??{}))value===null?delete env[key]:env[key]=value;return env}function delay(ms){return new Promise(resolve4=>setTimeout(resolve4,ms))}async function handoffHost(options){if((options._test?.platform??process.platform)==="win32")return{action:"refuse",reason:"upgrade_unsupported",upgradeable:!1};let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}});await createDaemonDirectories(paths);let host=await probeProtocolInfo(options.socket,1e4);if(!host)return{action:"refuse",reason:"no_host",upgradeable:!1};if(!host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY))return{action:"refuse",reason:"handoff_unsupported",upgradeable:!1};let registered=await readHostRegistration(paths),owner=await provenOwner(registered,options.socket);return owner?startSuccessor({options,paths,host,owner}):{action:"refuse",reason:"unknown_owner",upgradeable:!0}}import{spawn as spawn2}from"node:child_process";import{createHash as createHash2,randomUUID as randomUUID3}from"node:crypto";import{mkdir,open as open2,readdir as readdir3,readFile,rm as rm2,writeFile}from"node:fs/promises";import{tmpdir as tmpdir2}from"node:os";import{dirname as dirname2,join as join5}from"node:path";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(resolve4=>setTimeout(resolve4,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"}var SPAWNED_HOST_PROBE_TIMEOUT_MS=1e4,EXISTING_HOST_PROBE_TIMEOUT_MS=1e4,DEFAULT_READINESS_TIMEOUT_MS=1e4,DEFAULT_STOP_TIMEOUT_MS=1e4,SIGKILL_GRACE_MS=2e3,ENSURE_LOCK_WAIT_MS=EXISTING_HOST_PROBE_TIMEOUT_MS+DEFAULT_STOP_TIMEOUT_MS+SIGKILL_GRACE_MS+DEFAULT_READINESS_TIMEOUT_MS+1e4,LOCK_BUSY_WAIT_MS=100,lockOptions={retries:{retries:ENSURE_LOCK_WAIT_MS/LOCK_BUSY_WAIT_MS,minTimeout:20,maxTimeout:LOCK_BUSY_WAIT_MS}};async function ensureHost(options){let socket=normalizeSocketPath(options.socket),paths=createHostDaemonPaths({socket,...options.agentDir?{agentDir:options.agentDir}:{}});await createDaemonDirectories(paths);let lockTarget=join5(tmpdir2(),"senpi-rpc-host-locks",createSocketLockName(socket));await mkdir(dirname2(lockTarget),{recursive:!0}),await writeFile(lockTarget,"",{flag:"a",mode:384}),await reapOrphanedInternalHostDirs();let release=await acquireOwnershipSafeLock(`${lockTarget}.lock`,lockOptions);try{return await options._test?.afterLockAcquired?.(),await ensureHostLocked(paths,socket,options)}finally{await release()}}async function ensureHostLocked(paths,socket,options){let testOptions=options._test,registered=await readHostRegistration(paths),registeredHere=registersSocket(registered,socket),protocol=await probeProtocolInfo(socket,EXISTING_HOST_PROBE_TIMEOUT_MS),startedByUs=registeredHere&&await writtenByThisProcess(registered?.writer),attachedPid=registeredHere?registered?.record.pid??0:0,decision=decide(options,startedByUs,protocol);switch(decision.action){case"reuse":return{pid:attachedPid,socket,reused:!0};case"refuse":throw new HostEnsureRefusedError(socket,decision.reason,protocol);case"handoff":return upgradeGeneration(paths,socket,options,attachedPid);case"start":break;default:return assertNever2(decision)}let probe=testOptions?.readProcessStartTime??readProcessStartTime,pidMatches=registeredHere&&registered?await matchesPidFileOrUnknown(registered.record,probe):!1;if(registered&&pidMatches){if(!startedByUs)throw new HostEnsureRefusedError(socket,"foreign_writer",protocol);await stopManagedHost(registered.record,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS,probe)}if(await legacyHostIsLive(paths,probe))throw new HostEnsureRefusedError(socket,"legacy_host",protocol);return registeredHere&&await clearHostRegistration(paths),startHost(paths,socket,options)}function decide(options,startedByUs,protocol){if(options.upgrade!=="if-engine-differs")return decideHostAction(ensureClient(options,startedByUs),protocol,"never");let decision=decideHostAction(ensureClient(options,startedByUs),protocol,"upgrade");return decision.action==="fallback"?{action:"reuse",reason:"compatible",upgradeable:!1}:decision}async function upgradeGeneration(paths,socket,options,attachedPid){let result=await handoffHost({socket,agentDir:options.agentDir??getAgentDir(),hostArgs:options.hostArgs??[],...options.env?{env:options.env}:{},...options.policy?{policy:options.policy}:{},_test:{...options._test?.launch?{launch:options._test.launch}:{},...options._test?.readinessTimeoutMs?{readinessTimeoutMs:options._test.readinessTimeoutMs}:{}}});return result.action==="handoff"?{pid:result.pid,socket,reused:!1}:(await appendStderr(paths,`generation handoff refused: ${result.reason}${result.detail?` (${result.detail})`:""}`),{pid:attachedPid,socket,reused:!0})}function ensureClient(options,startedByUs){return{protocolVersion:HOST_PROTOCOL_VERSION,requiredCapabilities:REQUIRED_HOST_CAPABILITIES,identity:engineBuildIdentity(),...options.upgrade==="if-engine-differs"?{launchProfile:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd())}:{},startedByUs,platform:process.platform}}function hostChildArgv(hostArgs){return["--mode","rpc","--multi-session",...hostArgs]}function registersSocket(registered,socket){return registered===void 0?!1:registered.socket===void 0||registered.socket===socket}async function startHost(paths,socket,options){let testOptions=options._test,instanceId=randomUUID3();process.platform==="win32"&&await createSocketSecret(socketSecretPath(socket)),await writeHostSettings(paths,{socket,capabilities:PINNED_HOST_CLIENT_CAPABILITIES,coldStart:options.policy?.coldStart??"transient",idleExitMs:options.policy?.idleExitMs??DEFAULT_HOST_IDLE_EXIT_MS,generation:0,instanceId});let stderr=await open2(paths.stderrLog,"w",384),pidFile,child,exitedEarly,childExit;try{let supervisorArgs=["--socket",socket,...options.hostArgs??[]],launch=testOptions?.spawn??testOptions?.launch?.(supervisorArgs)??defaultHostLaunch(supervisorArgs);if(child=spawn2(launch.command,[...launch.args],{detached:!0,windowsHide:!0,env:hostEnv(options,{paths,instanceId}),stdio:["ignore","ignore",stderr.fd]}),childExit=new Promise(resolveExit=>{child.once("exit",(code,signal)=>{exitedEarly={code,signal},resolveExit(exitedEarly)})}),child.pid===void 0)throw new Error("failed to spawn RPC socket host");let probe=testOptions?.readProcessStartTime??readProcessStartTime,observedStartTime=await Promise.race([waitForStartTime(child.pid,1e4,probe),childExit.then(()=>{throw new Error("RPC socket host exited before its start time could be read")})]),unhurriedProbe=testOptions?.readProcessStartTime?testOptions.readProcessStartTime:pid=>readProcessStartTime(pid,process.platform,15e3),processStartTime=observedStartTime??await unhurriedProbe(child.pid).catch(()=>{});pidFile={pid:child.pid,processStartTime:processStartTime??null},await testOptions?.beforePidFileWrite?.(),await writeHostRegistration(paths,{record:pidFile,socket,instanceId,generation:0,launchProfileId:hostLaunchProfile(hostChildArgv(options.hostArgs??[]),process.cwd()).profile_id}),child.unref()}catch(error){let exitedBeforeCleanup=exitedEarly;if(!exitedBeforeCleanup&&child&&child.exitCode===null&&child.signalCode===null){try{child.kill("SIGTERM")}catch{}if(childExit&&await Promise.race([childExit,delay2(2e3)]),child.exitCode===null&&child.signalCode===null)try{child.kill("SIGKILL")}catch{}}if(!exitedBeforeCleanup)throw await clearHostRegistration(paths),error;let diagnostic2=await appendStderr(paths,`RPC socket host exited with code ${exitedBeforeCleanup.code??"null"}${exitedBeforeCleanup.signal?` (${exitedBeforeCleanup.signal})`:""} before answering get_protocol_info`);throw await clearHostRegistration(paths),new Error(diagnostic2)}finally{await stderr.close()}let readinessTimeoutMs=testOptions?.readinessTimeoutMs??DEFAULT_READINESS_TIMEOUT_MS,result=await pollProtocolInfo(socket,readinessTimeoutMs,childExit);if(isCompatible(result.protocol))return{pid:pidFile.pid,socket,reused:!1};let stopFailure=await stopSpawnedChild(child,childExit,testOptions?.stopTimeoutMs??DEFAULT_STOP_TIMEOUT_MS).then(()=>{},error=>error instanceof Error?error.message:String(error)),message=result.protocol?`RPC socket host answered get_protocol_info with protocolVersion ${result.protocol.protocolVersion}, serverVersion ${result.protocol.serverVersion} and capabilities ${JSON.stringify(result.protocol.capabilities)}, but is incompatible with protocol version ${HOST_PROTOCOL_VERSION} and required capabilities ${JSON.stringify(REQUIRED_HOST_CAPABILITIES)}`:result.exited?`RPC socket host exited with code ${result.exited.code??"null"}${result.exited.signal?` (${result.exited.signal})`:""} before answering get_protocol_info`:`spawned RPC socket host did not answer get_protocol_info within ${readinessTimeoutMs}ms`,diagnostic=await appendStderr(paths,stopFailure===void 0?message:`${message} (teardown also reported: ${stopFailure})`);throw await clearHostRegistration(paths),new Error(diagnostic)}async function matchesPidFileOrUnknown(pidFile,probe){try{return await processMatchesPidFile(pidFile,probe)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!1;throw error}}async function stopSpawnedChild(child,childExit,termTimeoutMs){let exited=()=>child.exitCode!==null||child.signalCode!==null;if(exited())return;let signal=name=>{try{child.kill(name)}catch(error){if(!isNodeErrorCode(error,"ESRCH"))throw error}},waitFor=ms=>Promise.race([childExit.then(()=>!0),delay2(ms).then(()=>exited())]);if(signal("SIGTERM"),!await waitFor(termTimeoutMs)&&(signal("SIGKILL"),!await waitFor(SIGKILL_GRACE_MS)))throw new Error(`RPC socket host pid ${child.pid??"?"} remained alive after SIGKILL`)}async function stopManagedHost(pidFile,termTimeoutMs,readStartTime=readProcessStartTime){if(await signalValidated(pidFile,"SIGTERM",readStartTime),!await waitForGone(pidFile,termTimeoutMs,readStartTime)&&(await signalValidated(pidFile,"SIGKILL",readStartTime),!await waitForGone(pidFile,SIGKILL_GRACE_MS,readStartTime)))throw new Error(`RPC socket host pid ${pidFile.pid} remained alive after SIGKILL`)}async function resolvePidFileOwnership(pidFile,readStartTime){try{return await processMatchesPidFile(pidFile,readStartTime,processIsLive,{attempts:1})?"owns":"gone"}catch(error){if(error instanceof ProcessIdentityUnreadableError)return"unknown";throw error}}async function signalValidated(pidFile,signal,readStartTime=readProcessStartTime){if(await resolvePidFileOwnership(pidFile,readStartTime)==="owns")try{process.kill(pidFile.pid,signal)}catch(error){if(!isNodeErrorCode(error,"ESRCH"))throw error}}async function waitForGone(pidFile,timeoutMs,readStartTime=readProcessStartTime){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await resolvePidFileOwnership(pidFile,readStartTime)==="gone")return!0;await delay2(50)}return await resolvePidFileOwnership(pidFile,readStartTime)==="gone"}async function pollProtocolInfo(socket,timeoutMs,childExit){let deadline=Date.now()+timeoutMs,lastProtocol;for(;Date.now()<=deadline;){let probe=probeProtocolInfo(socket,Math.min(SPAWNED_HOST_PROBE_TIMEOUT_MS,Math.max(1,deadline-Date.now()))),raced=childExit?await Promise.race([probe,childExit]):await probe;if(isChildExit(raced)){let info=await probe;if(info){if(lastProtocol=info,isCompatible(info))return{protocol:info}}else return{protocol:lastProtocol,exited:raced}}else if(raced&&(lastProtocol=raced,isCompatible(raced)))return{protocol:raced};await delay2(50)}return{protocol:lastProtocol}}function isChildExit(value){return!!value&&"code"in value&&"signal"in value}function isCompatible(protocol){return decideHostAction(ensureClient({socket:""},!1),protocol,"never").action==="reuse"}function hostEnv(options,generation){let env={...process.env};for(let[key,value]of Object.entries(options.env??{}))value===null?delete env[key]:env[key]=value;return env[ENV_AGENT_DIR]=options.agentDir??getAgentDir(),env[RPC_CLIENT_CAPABILITIES_ENV]=PINNED_HOST_CLIENT_CAPABILITIES.join(","),env[HOST_INSTANCE_ID_ENV]=generation.instanceId,env[HOST_GENERATION_ENV]="0",env[HOST_DAEMON_DIR_ENV]=generation.paths.dir,env}async function reapOrphanedInternalHostDirs(){try{let entries=await readdir3(tmpdir2(),{withFileTypes:!0});await Promise.all(entries.filter(entry=>entry.isDirectory()&&entry.name.startsWith("senpi-rpc-host-internal-")).map(async entry=>{try{let owner=JSON.parse(await readFile(join5(tmpdir2(),entry.name,".owner"),"utf8"));typeof owner.pid=="number"&&typeof owner.processStartTime=="string"&&typeof owner.createdAt=="number"&&owner.processStartTime.length>0&&owner.createdAt<Date.now()-6e4&&(await readdir3(join5(tmpdir2(),entry.name))).length===1&&!await processMatchesPidFile({pid:owner.pid,processStartTime:owner.processStartTime}).catch(error=>{if(error instanceof ProcessIdentityUnreadableError)return!0;throw error})&&await rm2(join5(tmpdir2(),entry.name),{recursive:!0,force:!0})}catch{}}))}catch{}}async function appendStderr(paths,message){try{let stderr=(await readFile(paths.stderrLog,"utf8")).trim();return stderr?`${message}
43
- ${stderr}`:message}catch(error){if(isNodeErrorCode(error,"ENOENT"))return message;throw error}}function createSocketLockName(socket){return createHash2("sha256").update(resolveSocketTransportAddress(socket,process.platform),"utf8").digest("hex").slice(0,32)}function normalizeSocketPath(value){return value.startsWith("unix://")?value.slice(7):value}function delay2(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}function assertNever2(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}import{spawn as spawn3}from"node:child_process";import{createConnection as createConnection2}from"node:net";var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.pendingRequests=new Map,this.requestId=0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.options=options}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn3("node",[cliPath,...args],{cwd:this.options.cwd,env:{...process.env,SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve4=>setTimeout(resolve4,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}async stop(){if(this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.process.kill("SIGTERM"),await new Promise(resolve4=>{let timeout=setTimeout(()=>{this.process?.kill("SIGKILL"),resolve4()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve4()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let secret=process.platform==="win32"?await readSocketSecret(socketSecretPath(path)):void 0,socket=createConnection2(resolveSocketTransportAddress(path,process.platform,secret));this.socket=socket,await new Promise((resolve4,reject)=>{let onConnect=()=>{cleanup(),resolve4()},onError=error=>{cleanup(),this.socket=null,reject(error)},cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)}),secret&&sendSocketHandshake(socket,secret),this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let response=await this.send({type:"open_session",...options},!1),opened=this.getData(response);return this.sessionId=opened.sessionId,this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async closeSession(sessionId=this.sessionId){if(sessionId){try{await this.send({type:"close_session",sessionId},!1)}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0)}}async listSessions(){let response=await this.send({type:"list_sessions"},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success)throw new Error(response.error)}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async steer(message,images,recovery){await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder})}async followUp(message,images,recovery){await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder})}async abort(){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since){let response=await this.send({type:"get_entries",since});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async removeProviderAccount(provider,name){await this.send({type:"account_remove",provider,name})}waitForIdle(timeout=6e4){return new Promise((resolve4,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve4())})})}collectEvents(timeout=6e4){return new Promise((resolve4,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="session_replaced"||event.type==="session_parked"||(events.push(event),event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve4(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(data.type==="response"&&data.id&&this.pendingRequests.has(data.id)){let pending=this.pendingRequests.get(data.id);this.pendingRequests.delete(data.id),pending.onResponse?.(data),pending.resolve(data);return}if(typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of this.eventListeners)listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of this.eventListeners)listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{}};return expectResponse?new Promise((resolve4,reject)=>{let timeout=setTimeout(()=>{let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id);let timeoutError=new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`);pending?.onReject?.(timeoutError),reject(timeoutError)},3e4);this.pendingRequests.set(id,{resolve:response=>{clearTimeout(timeout),resolve4(response)},reject:error=>{clearTimeout(timeout),reject(error)},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}}):(stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0}))}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{stripAnsi,reserveSessionWrite,unregisterSessionWriter,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,SessionManager,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,executeBashWithOperations,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,parseHostProtocolInfo,HOST_PROTOCOL_VERSION,GENERATION_HANDOFF_CAPABILITY,REQUIRED_HOST_CAPABILITIES,HostEnsureRefusedError,decideHostAction,probeHost,PINNED_HOST_CLIENT_CAPABILITIES,stopHost,handoffHost,acquireOwnershipSafeLock,ensureHost,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};
40
+ ${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}import{spawn}from"node:child_process";import{createConnection}from"node:net";var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.pendingRequests=new Map,this.requestId=0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.options=options}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn("node",[cliPath,...args],{cwd:this.options.cwd,env:{...process.env,SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve3=>setTimeout(resolve3,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}async stop(){if(this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.process.kill("SIGTERM"),await new Promise(resolve3=>{let timeout=setTimeout(()=>{this.process?.kill("SIGKILL"),resolve3()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve3()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let secret=process.platform==="win32"?await readSocketSecret(socketSecretPath(path)):void 0,socket=createConnection(resolveSocketTransportAddress(path,process.platform,secret));this.socket=socket,await new Promise((resolve3,reject)=>{let onConnect=()=>{cleanup(),resolve3()},onError=error=>{cleanup(),this.socket=null,reject(error)},cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)}),secret&&sendSocketHandshake(socket,secret),this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let response=await this.send({type:"open_session",...options},!1),opened=this.getData(response);return this.sessionId=opened.sessionId,this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async closeSession(sessionId=this.sessionId){if(sessionId){try{await this.send({type:"close_session",sessionId},!1)}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0)}}async listSessions(){let response=await this.send({type:"list_sessions"},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success)throw new Error(response.error)}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async steer(message,images,recovery){await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder})}async followUp(message,images,recovery){await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder})}async abort(){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since){let response=await this.send({type:"get_entries",since});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async removeProviderAccount(provider,name){await this.send({type:"account_remove",provider,name})}waitForIdle(timeout=6e4){return new Promise((resolve3,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3())})})}collectEvents(timeout=6e4){return new Promise((resolve3,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="session_replaced"||event.type==="session_parked"||(events.push(event),event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(data.type==="response"&&data.id&&this.pendingRequests.has(data.id)){let pending=this.pendingRequests.get(data.id);this.pendingRequests.delete(data.id),pending.onResponse?.(data),pending.resolve(data);return}if(typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of this.eventListeners)listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of this.eventListeners)listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{}};return expectResponse?new Promise((resolve3,reject)=>{let timeout=setTimeout(()=>{let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id);let timeoutError=new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`);pending?.onReject?.(timeoutError),reject(timeoutError)},3e4);this.pendingRequests.set(id,{resolve:response=>{clearTimeout(timeout),resolve3(response)},reject:error=>{clearTimeout(timeout),reject(error)},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}}):(stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0}))}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{stripAnsi,reserveSessionWrite,unregisterSessionWriter,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,SessionManager,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,executeBashWithOperations,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};
@@ -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{getShellConfig}from"./chunk-2H3Y7EYQ.js";import{getOverflowPatterns}from"./chunk-VRAYXSST.js";import{normalizeProviderError}from"./chunk-PRC5XIIH.js";import{PROVIDER_NOT_CONFIGURED_PREFIX}from"./chunk-I3F6VZZF.js";import{extract429RetryAfterMs}from"./chunk-BPX6QWPD.js";import{spawn}from"child_process";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"))})})}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}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 TURN_RETRY_SUPPRESSION_PREFIX="senpi:no-turn-retry:",DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;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,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={}){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"}};if(status===429||RATE_LIMIT_TEXT.test(text)){let hint=extract429RetryAfterMs({status:status??429,bodyText:text});return{kind:"failover",block:{reason:"rate_limit",...rateLimitCooldown(failureCount,hint,{baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs})}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}: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(`${options.suppressTurnRetry?TURN_RETRY_SUPPRESSION_PREFIX:""}${detail}`,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.suppressTurnRetry=options.suppressTurnRetry,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;for(;;){let slots=await options.listSlots(),candidates=slots.filter(slot2=>!attempted.has(slot2.name)&&isAvailable(slot2,now()));if(candidates.length===0){let retryAt=soonestRetryAt(slots,now());throw lastError!==void 0&&lastOriginal!==void 0?new CredentialFailoverError(lastError.action,lastOriginal,{suppressTurnRetry:lastError.suppressTurnRetry,...retryAt===void 0?{}:{retryAt}}):new CredentialFailoverError({kind:"fail_request"},new Error("No credential slots available"),{suppressTurnRetry:!1,...retryAt===void 0?{}:{retryAt}})}let slot=options.select(candidates),committedOutput=!1,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw failure;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,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts)continue;throw new CredentialFailoverError(action,error,{suppressTurnRetry:!1})}if(action.kind!=="failover")throw new CredentialFailoverError(action,error,{suppressTurnRetry:committedOutput});await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error,{suppressTurnRetry:committedOutput});if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput)throw failure}}}export{sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,TURN_RETRY_SUPPRESSION_PREFIX,rendezvousOrder,classifyCredentialFailure,CredentialFailoverError,runCredentialFailover};
2
+ import{getShellConfig}from"./chunk-2H3Y7EYQ.js";import{getOverflowPatterns}from"./chunk-FDLVINNY.js";import{normalizeProviderError}from"./chunk-PRC5XIIH.js";import{PROVIDER_NOT_CONFIGURED_PREFIX}from"./chunk-I3F6VZZF.js";import{extract429RetryAfterMs}from"./chunk-BPX6QWPD.js";import{spawn}from"child_process";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"))})})}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}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 TURN_RETRY_SUPPRESSION_PREFIX="senpi:no-turn-retry:",DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;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,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={}){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"}};if(status===429||RATE_LIMIT_TEXT.test(text)){let hint=extract429RetryAfterMs({status:status??429,bodyText:text});return{kind:"failover",block:{reason:"rate_limit",...rateLimitCooldown(failureCount,hint,{baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs})}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}: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(`${options.suppressTurnRetry?TURN_RETRY_SUPPRESSION_PREFIX:""}${detail}`,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.suppressTurnRetry=options.suppressTurnRetry,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;for(;;){let slots=await options.listSlots(),candidates=slots.filter(slot2=>!attempted.has(slot2.name)&&isAvailable(slot2,now()));if(candidates.length===0){let retryAt=soonestRetryAt(slots,now());throw lastError!==void 0&&lastOriginal!==void 0?new CredentialFailoverError(lastError.action,lastOriginal,{suppressTurnRetry:lastError.suppressTurnRetry,...retryAt===void 0?{}:{retryAt}}):new CredentialFailoverError({kind:"fail_request"},new Error("No credential slots available"),{suppressTurnRetry:!1,...retryAt===void 0?{}:{retryAt}})}let slot=options.select(candidates),committedOutput=!1,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw failure;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,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts)continue;throw new CredentialFailoverError(action,error,{suppressTurnRetry:!1})}if(action.kind!=="failover")throw new CredentialFailoverError(action,error,{suppressTurnRetry:committedOutput});await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error,{suppressTurnRetry:committedOutput});if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput)throw failure}}}export{sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,TURN_RETRY_SUPPRESSION_PREFIX,rendezvousOrder,classifyCredentialFailure,CredentialFailoverError,runCredentialFailover};
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
3
+ import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-KKDSBABY.js";import"./chunk-3FRTRCR6.js";import"./chunk-EONVPHVX.js";import"./chunk-3Q4WGKFA.js";import"./chunk-W4SRGDQ4.js";import"./chunk-GFUZPFHN.js";import"./chunk-NARL7XFO.js";import"./chunk-RLRLQRI2.js";import"./chunk-YRN3PCTM.js";import{configureHttpDispatcher}from"./chunk-PLZK7ABD.js";import"./chunk-QOBJEPJZ.js";import"./chunk-BMX2U22F.js";import"./chunk-IUZUN32Z.js";import"./chunk-P7PWCGLJ.js";import"./chunk-U6Z6OBX4.js";import"./chunk-LF3XTYYF.js";import"./chunk-HSH674C6.js";import"./chunk-BQVRDBW6.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-XK24AFYU.js";import"./chunk-MUC3MZTV.js";import"./chunk-2H3Y7EYQ.js";import"./chunk-FDLVINNY.js";import"./chunk-56TWFZ2C.js";import"./chunk-34GCWLNV.js";import"./chunk-7X72IACK.js";import"./chunk-3XHLKHSK.js";import"./chunk-X4Q5YSTE.js";import"./chunk-WVGCQOLJ.js";import"./chunk-IXAUDPOK.js";import"./chunk-EAMTSSEH.js";import"./chunk-RFB5CBW7.js";import"./chunk-OYXTZDVT.js";import"./chunk-V55B77HQ.js";import"./chunk-FC7R7NOV.js";import"./chunk-PRC5XIIH.js";import"./chunk-I3F6VZZF.js";import"./chunk-BPX6QWPD.js";import"./chunk-WDTJ6JKE.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-TVOODZJH.js";import"./chunk-I7YUNMWH.js";import"./chunk-2SOVDETB.js";import"./chunk-U7RQY7MH.js";import"./chunk-UAYBYTFN.js";import"./chunk-QPIXPR6I.js";import"./chunk-HGAX6JZ7.js";import"./chunk-26UBFF6N.js";import"./chunk-3P23SBT3.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-H5RK2RYZ.js";import"./chunk-TDTKQR7C.js";import"./chunk-VR4X5O2Z.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));