@code-yeongyu/senpi 2026.11.10-1 → 2026.11.10-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/bundle/chunks/{args-77GYOPEO.js → args-HFYB6URH.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-YFZ734T3.js → azure-openai-responses-MNN2TINI.js} +1 -1
  4. package/dist/bundle/chunks/{chunk-ZUQCYIRY.js → chunk-2ODGHBUD.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-YPAQXRP3.js → chunk-47T6YMI2.js} +2 -2
  6. package/dist/bundle/chunks/{chunk-I5ASHSLZ.js → chunk-4JMGWVRH.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-MSDBBOB2.js → chunk-5H43O4MA.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-3IYWH6RO.js → chunk-6Q7Y2G5A.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-X4XWAB3J.js → chunk-AC6MDRAE.js} +81 -81
  10. package/dist/bundle/chunks/{chunk-33MZJTQ3.js → chunk-B4WD5XHP.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-V5FSENW6.js → chunk-COKX65TE.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-LHEP3ACI.js → chunk-DEQLHN2J.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-EJB5E2JK.js → chunk-DHAAWL2H.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-2EJ4BGBM.js → chunk-DHORIIVQ.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-GPXZTSEX.js → chunk-DIHIEJFV.js} +3 -3
  16. package/dist/bundle/chunks/{chunk-NH7SYIGN.js → chunk-DLPV4B3R.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-RCHIMH7N.js → chunk-DQY26AX3.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-Y7Z7XPUF.js → chunk-DZQA5LVN.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-2CNSCMYC.js → chunk-E5O4SP5I.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-3Q5ZENSD.js → chunk-E6ZBTSC6.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-HI5JSLG5.js → chunk-H3VJVKUK.js} +4 -4
  22. package/dist/bundle/chunks/{chunk-L6NRDUWJ.js → chunk-HZDKQOWB.js} +1 -1
  23. package/dist/bundle/chunks/chunk-IREUIMFE.js +11 -0
  24. package/dist/bundle/chunks/{chunk-FAFIGBUD.js → chunk-JSD6O3RJ.js} +2 -2
  25. package/dist/bundle/chunks/{chunk-BELNOPAI.js → chunk-L3KVP7VJ.js} +3 -3
  26. package/dist/bundle/chunks/{chunk-7MN7YNO5.js → chunk-L7DGTA3L.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-J2NGJKXL.js → chunk-LXINMDMX.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-H33A33M4.js → chunk-M2VJVJMK.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-ARUV3US4.js → chunk-NN7NESW2.js} +1 -1
  30. package/dist/bundle/chunks/{chunk-2U6HXWXS.js → chunk-NNQ34ZDW.js} +1 -1
  31. package/dist/bundle/chunks/chunk-NQKCJQHB.js +2 -0
  32. package/dist/bundle/chunks/{chunk-TGW4R7SI.js → chunk-O5WJVIEU.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-O3FG6HML.js → chunk-PJI5GT7U.js} +1 -1
  34. package/dist/bundle/chunks/{chunk-BPNSOZ2C.js → chunk-QUVSIW2R.js} +1 -1
  35. package/dist/bundle/chunks/{chunk-WXYMAUFX.js → chunk-QX7WD3IM.js} +1 -1
  36. package/dist/bundle/chunks/{chunk-Y4ONXQMR.js → chunk-RGHVPUUX.js} +1 -1
  37. package/dist/bundle/chunks/{chunk-RYPM5BZQ.js → chunk-S7NAJQB3.js} +1 -1
  38. package/dist/bundle/chunks/{chunk-LT353NSF.js → chunk-T4CUD7RF.js} +1 -1
  39. package/dist/bundle/chunks/{chunk-J7FW7MED.js → chunk-TCZORL3V.js} +1 -1
  40. package/dist/bundle/chunks/{chunk-KU72IKV5.js → chunk-VGSWOLIY.js} +1 -1
  41. package/dist/bundle/chunks/{chunk-DBQBJTMF.js → chunk-VUY4BZDI.js} +1 -1
  42. package/dist/bundle/chunks/chunk-XI6THO4F.js +2 -0
  43. package/dist/bundle/chunks/{chunk-THYEZBUG.js → chunk-Z2C5N2LM.js} +2 -2
  44. package/dist/bundle/chunks/{cli-main-VG3C2EXI.js → cli-main-ZTT3N4DO.js} +1 -1
  45. package/dist/bundle/chunks/{credential-accounts-LVVPKFEY.js → credential-accounts-5KHVGSCY.js} +1 -1
  46. package/dist/bundle/chunks/{dispatch-EP35KKJ3.js → dispatch-YUYZQXRP.js} +1 -1
  47. package/dist/bundle/chunks/{hand-entry-3LQKUTYS.js → hand-entry-UV5XPMBF.js} +3 -3
  48. package/dist/bundle/chunks/{headless-host-HKGNJGYT.js → headless-host-53UMJMM6.js} +1 -1
  49. package/dist/bundle/chunks/{health-write-FBF74QJ7.js → health-write-JLSF5EVV.js} +1 -1
  50. package/dist/bundle/chunks/{help-fast-path-5SCPY3OH.js → help-fast-path-552QLMWT.js} +1 -1
  51. package/dist/bundle/chunks/{host-command-CCASS7W4.js → host-command-BZN7WYYV.js} +1 -1
  52. package/dist/bundle/chunks/{host-lifecycle-WWC7HXQ6.js → host-lifecycle-TNHASSFJ.js} +1 -1
  53. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  54. package/dist/bundle/chunks/{host-session-command-YJB2FLKU.js → host-session-command-O5WYHZXH.js} +1 -1
  55. package/dist/bundle/chunks/{host-socket-request-DMYXC56U.js → host-socket-request-QN4Q2P5E.js} +1 -1
  56. package/dist/bundle/chunks/{interactive-mode-CUN3WMUF.js → interactive-mode-OCU4NDPC.js} +1 -1
  57. package/dist/bundle/chunks/{login-health-EVXVLHB2.js → login-health-TOSQT5RG.js} +1 -1
  58. package/dist/bundle/chunks/{main-P7XRC2OI.js → main-CNDP6HCF.js} +1 -1
  59. package/dist/bundle/chunks/{multi-session-host-244X3P6L.js → multi-session-host-ODGJAGJP.js} +11 -8
  60. package/dist/bundle/chunks/openai-codex-responses-VRGOAFEG.js +10 -0
  61. package/dist/bundle/chunks/{openai-responses-NIVBWE2H.js → openai-responses-I7PXRWCM.js} +2 -2
  62. package/dist/bundle/chunks/{package-manager-cli-UVWJOQA3.js → package-manager-cli-HSPUG4RJ.js} +1 -1
  63. package/dist/bundle/chunks/{role-HQUN4XXK.js → role-AEOLJRTP.js} +1 -1
  64. package/dist/bundle/chunks/{rotation-stream-F3BEMXBE.js → rotation-stream-E3FJFHXJ.js} +1 -1
  65. package/dist/bundle/chunks/rpc-mode-KOZPXU3U.js +2 -0
  66. package/dist/bundle/chunks/{rpc-monitor-source-C6VQ3BC4.js → rpc-monitor-source-PGTDSGWP.js} +1 -1
  67. package/dist/bundle/chunks/{run-attached-tui-R3RB5P7G.js → run-attached-tui-4AENRP7P.js} +1 -1
  68. package/dist/bundle/chunks/{schedule-command-5FG2OKSR.js → schedule-command-SG44FE23.js} +1 -1
  69. package/dist/bundle/chunks/session-control-endpoint-5A24JYPE.js +3 -0
  70. package/dist/bundle/chunks/{session-picker-2FZSNFS7.js → session-picker-73YRS3GE.js} +1 -1
  71. package/dist/bundle/chunks/{session-slot-CZGQQCOC.js → session-slot-RH7JLO3F.js} +1 -1
  72. package/dist/bundle/chunks/session-worker.js +199 -196
  73. package/dist/bundle/chunks/{state-store-S7QAESIF.js → state-store-IECVTYXC.js} +1 -1
  74. package/dist/bundle/cli.js +2 -2
  75. package/dist/bundle/host-supervisor.js +1 -1
  76. package/dist/bundle/index.js +1 -1
  77. package/dist/bundle/rpc-entry.js +1 -1
  78. package/dist/bundle/runtime-manifest.json +1 -1
  79. package/dist/core/agent-session-runtime.d.ts +2 -0
  80. package/dist/core/agent-session-runtime.js +5 -0
  81. package/dist/core/agent-session.d.ts +13 -3
  82. package/dist/core/agent-session.js +89 -18
  83. package/dist/core/assistant-error-redaction.d.ts +9 -0
  84. package/dist/core/assistant-error-redaction.js +27 -0
  85. package/dist/core/config-reference-redaction.js +90 -10
  86. package/dist/core/context-files.d.ts +10 -0
  87. package/dist/core/context-files.js +58 -12
  88. package/dist/core/egress/wire.d.ts +13 -0
  89. package/dist/core/extensions/builtin/config-reload/change-groups.js +6 -2
  90. package/dist/core/extensions/builtin/mcp/auth/catalog-identity.js +32 -8
  91. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.d.ts +43 -0
  92. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.js +196 -0
  93. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +4 -17
  94. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +64 -75
  95. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.d.ts +1 -1
  96. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +25 -4
  97. package/dist/core/extensions/builtin/mcp/auth/oauth.js +10 -7
  98. package/dist/core/extensions/builtin/mcp/auth/token-store.d.ts +18 -0
  99. package/dist/core/extensions/builtin/mcp/auth/token-store.js +3 -0
  100. package/dist/core/extensions/builtin/mcp/catalog-cache.js +7 -6
  101. package/dist/core/extensions/builtin/mcp/catalog.js +3 -2
  102. package/dist/core/extensions/builtin/mcp/invocation.js +6 -0
  103. package/dist/core/extensions/builtin/mcp/service-register.js +16 -2
  104. package/dist/core/extensions/builtin/mcp/service-tools-changed.js +61 -54
  105. package/dist/core/extensions/builtin/mcp/startup-race.d.ts +2 -0
  106. package/dist/core/extensions/builtin/mcp/startup-race.js +25 -7
  107. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-2.js +6 -6
  108. package/dist/core/extensions/loader.js +24 -4
  109. package/dist/core/extensions/runner.d.ts +9 -1
  110. package/dist/core/extensions/runner.js +9 -4
  111. package/dist/core/extensions/types.d.ts +17 -3
  112. package/dist/core/hand/hook-advertise.d.ts +41 -0
  113. package/dist/core/hand/hook-advertise.js +98 -0
  114. package/dist/core/hand/hook-contract.d.ts +66 -0
  115. package/dist/core/hand/hook-contract.js +138 -0
  116. package/dist/core/open-timing.d.ts +2 -0
  117. package/dist/core/open-timing.js +7 -1
  118. package/dist/core/resource-loader.js +2 -0
  119. package/dist/core/retry-fallback/log.d.ts +7 -1
  120. package/dist/core/retry-fallback/log.js +82 -5
  121. package/dist/core/retry-fallback/model-config-error.js +2 -1
  122. package/dist/core/session-manager.d.ts +2 -0
  123. package/dist/core/session-manager.js +15 -1
  124. package/dist/core/settings-manager.d.ts +6 -0
  125. package/dist/core/settings-manager.js +8 -0
  126. package/dist/core/turn-origin.d.ts +19 -13
  127. package/dist/core/turn-origin.js +34 -30
  128. package/dist/core/ultrafast-lanes.d.ts +1 -0
  129. package/dist/core/ultrafast-lanes.js +4 -2
  130. package/dist/modes/interactive/components/footer.d.ts +23 -5
  131. package/dist/modes/interactive/components/footer.js +45 -16
  132. package/dist/modes/interactive/interactive-mode.js +9 -1
  133. package/dist/modes/interactive/session-control-rpc-commands.d.ts +1 -1
  134. package/dist/modes/interactive/session-control-rpc-commands.js +5 -0
  135. package/dist/modes/rpc/admit-external-message-command.d.ts +2 -2
  136. package/dist/modes/rpc/admit-external-message-command.js +2 -10
  137. package/dist/modes/rpc/compact-admission-validation.js +4 -1
  138. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  139. package/dist/modes/rpc/connection-handler.js +20 -8
  140. package/dist/modes/rpc/connection-roles.d.ts +2 -0
  141. package/dist/modes/rpc/connection-roles.js +4 -0
  142. package/dist/modes/rpc/custom-capability.d.ts +4 -0
  143. package/dist/modes/rpc/custom-capability.js +4 -0
  144. package/dist/modes/rpc/delegated-drive-origin.d.ts +6 -6
  145. package/dist/modes/rpc/delegated-drive-origin.js +7 -8
  146. package/dist/modes/rpc/delegation-declaration.d.ts +2 -0
  147. package/dist/modes/rpc/delegation-declaration.js +5 -1
  148. package/dist/modes/rpc/effect-commands.d.ts +21 -0
  149. package/dist/modes/rpc/host-capabilities.d.ts +1 -0
  150. package/dist/modes/rpc/host-capabilities.js +5 -1
  151. package/dist/modes/rpc/host-observe-request.d.ts +2 -0
  152. package/dist/modes/rpc/host-observe-request.js +6 -1
  153. package/dist/modes/rpc/host-park-ledger.d.ts +19 -0
  154. package/dist/modes/rpc/host-park-ledger.js +110 -0
  155. package/dist/modes/rpc/lifecycle-delivery.js +4 -1
  156. package/dist/modes/rpc/loopless-tool-handlers.d.ts +6 -0
  157. package/dist/modes/rpc/loopless-tool-handlers.js +14 -1
  158. package/dist/modes/rpc/media-placeholders.js +1 -0
  159. package/dist/modes/rpc/method-classes-schema-host.d.ts +42 -1
  160. package/dist/modes/rpc/method-classes-schema-host.js +24 -21
  161. package/dist/modes/rpc/method-classes-schema.d.ts +42 -1
  162. package/dist/modes/rpc/method-classes-schema.js +5 -2
  163. package/dist/modes/rpc/method-classes.d.ts +2 -0
  164. package/dist/modes/rpc/method-classes.js +3 -0
  165. package/dist/modes/rpc/multi-session-host.js +1 -1
  166. package/dist/modes/rpc/rpc-host-command-types.d.ts +14 -1
  167. package/dist/modes/rpc/rpc-host-response-types.d.ts +21 -0
  168. package/dist/modes/rpc/session-attachment-gate.js +2 -0
  169. package/dist/modes/rpc/session-binding.d.ts +1 -0
  170. package/dist/modes/rpc/session-binding.js +6 -1
  171. package/dist/modes/rpc/session-connection-context.d.ts +2 -0
  172. package/dist/modes/rpc/session-connection-context.js +4 -0
  173. package/dist/modes/rpc/session-registry-attach.d.ts +2 -0
  174. package/dist/modes/rpc/session-registry-attach.js +15 -11
  175. package/dist/modes/rpc/session-registry-claims.js +2 -0
  176. package/dist/modes/rpc/session-registry-open.js +13 -7
  177. package/dist/modes/rpc/session-registry-opening.js +2 -1
  178. package/dist/modes/rpc/session-registry-types.d.ts +4 -0
  179. package/dist/modes/rpc/session-registry.d.ts +3 -0
  180. package/dist/modes/rpc/session-registry.js +27 -3
  181. package/dist/modes/rpc/session-router-close.js +1 -0
  182. package/dist/modes/rpc/session-router-context.d.ts +4 -2
  183. package/dist/modes/rpc/session-router-context.js +3 -0
  184. package/dist/modes/rpc/session-router-host-reads.js +1 -0
  185. package/dist/modes/rpc/session-router-occupancy.js +10 -1
  186. package/dist/modes/rpc/session-router-open-result.d.ts +12 -0
  187. package/dist/modes/rpc/session-router-open-result.js +63 -0
  188. package/dist/modes/rpc/session-router-open.d.ts +3 -0
  189. package/dist/modes/rpc/session-router-open.js +15 -63
  190. package/dist/modes/rpc/session-router-park.d.ts +15 -0
  191. package/dist/modes/rpc/session-router-park.js +176 -0
  192. package/dist/modes/rpc/session-router-routing.d.ts +1 -1
  193. package/dist/modes/rpc/session-router-routing.js +7 -0
  194. package/dist/modes/rpc/session-status-source.js +2 -2
  195. package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
  196. package/docs/engine-socket/fixtures/rpc-inbound-samples.json +22 -2
  197. package/docs/extensions.md +10 -0
  198. package/docs/rpc.md +50 -0
  199. package/docs/settings.md +1 -0
  200. package/docs/usage.md +1 -1
  201. package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
  202. package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
  203. package/package.json +6 -6
  204. package/dist/bundle/chunks/chunk-436DNN4Z.js +0 -2
  205. package/dist/bundle/chunks/chunk-DLAY7CIU.js +0 -2
  206. package/dist/bundle/chunks/chunk-XH2MWTXA.js +0 -11
  207. package/dist/bundle/chunks/openai-codex-responses-ABB2J43U.js +0 -10
  208. package/dist/bundle/chunks/rpc-mode-G4I3HHPB.js +0 -2
  209. package/dist/bundle/chunks/session-control-endpoint-XWCFLJYC.js +0 -3
@@ -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{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,exitAfterOutput,isPackageCommandArgv}from"./chunk-3IYWH6RO.js";import{APP_NAME,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,ENV_PREFIX,brandEnvNames,getAgentDir}from"./chunk-SODMQEHO.js";import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import{homedir as homedir2}from"node:os";import{join}from"node:path";async function dispatchAgentDirectoryCommand(args){if(!(args[0]!=="config"||args[1]!=="agent-dir")){(args.length!==3||args[2]!=="--json")&&await exitAfterOutput(`${JSON.stringify({version:1,ok:!1,code:"invalid_arguments",message:`Usage: ${APP_NAME} config agent-dir --json`})}
2
+ import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,exitAfterOutput,isPackageCommandArgv}from"./chunk-6Q7Y2G5A.js";import{APP_NAME,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,ENV_PREFIX,brandEnvNames,getAgentDir}from"./chunk-SODMQEHO.js";import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import{homedir as homedir2}from"node:os";import{join}from"node:path";async function dispatchAgentDirectoryCommand(args){if(!(args[0]!=="config"||args[1]!=="agent-dir")){(args.length!==3||args[2]!=="--json")&&await exitAfterOutput(`${JSON.stringify({version:1,ok:!1,code:"invalid_arguments",message:`Usage: ${APP_NAME} config agent-dir --json`})}
3
3
  `,2);try{let dir=getAgentDir(),selector=brandEnvNames("CODING_AGENT_DIR").find(name=>process.env[name]!==void 0),explicit=selector!==void 0&&process.env[selector]?selector:void 0,homeDefault=CONFIG_FLAT_LAYOUT?join(homedir2(),CONFIG_DIR_NAME):join(homedir2(),CONFIG_DIR_NAME,"agent"),rule=explicit!==void 0?"environment":dir===homeDefault?"home-default":"project-local";await exitAfterOutput(`${JSON.stringify({version:1,ok:!0,dir,source:explicit??(rule==="project-local"?"project-local":"default"),rule,brandedPrefix:ENV_PREFIX})}
4
4
  `,0)}catch(error){await exitAfterOutput(`${JSON.stringify({version:1,ok:!1,code:"selection_failed",message:error instanceof Error?error.message:"Unable to resolve the agent directory."})}
5
- `,1)}}}import*as nodeModule from"node:module";async function enableStartupCompileCache(){let enable=nodeModule.enableCompileCache;if(typeof enable!="function")return;let args=process.argv.slice(2);if(!isPackageCommandArgv(args)&&args[0]!==CONFIG_COMMAND_ARGV&&(args.includes("--version")||args.includes("-v")))return;let scheduleWatch=!1;if(args[0]===SCHEDULE_COMMAND_ARGV&&args[1]==="run")for(let index=2;index<args.length;index++){let arg=args[index];arg==="--watch"?scheduleWatch=!0:["--exec","--poll-seconds","--timeout-seconds","--concurrency"].includes(arg??"")&&index++}if(!(isPackageCommandArgv(args)||args[0]===HOST_COMMAND_ARGV||args[0]===SCHEDULE_COMMAND_ARGV&&!scheduleWatch)){if(!scheduleWatch&&args.some(arg=>["--help","-h","--export","--list-models","--list-tips"].includes(arg)))try{let{parseArgs}=await import("./args-77GYOPEO.js"),parsed=parseArgs(args);if(parsed.version||parsed.export||parsed.listModels!==void 0||parsed.listTips||parsed.help&&!(parsed.mode==="rpc"&&parsed.multiSession))return}catch{}try{let result=enable();result.directory!==void 0&&process.env.NODE_COMPILE_CACHE===void 0&&(process.env.NODE_COMPILE_CACHE=result.directory)}catch{}}}export{dispatchAgentDirectoryCommand,enableStartupCompileCache};
5
+ `,1)}}}import*as nodeModule from"node:module";async function enableStartupCompileCache(){let enable=nodeModule.enableCompileCache;if(typeof enable!="function")return;let args=process.argv.slice(2);if(!isPackageCommandArgv(args)&&args[0]!==CONFIG_COMMAND_ARGV&&(args.includes("--version")||args.includes("-v")))return;let scheduleWatch=!1;if(args[0]===SCHEDULE_COMMAND_ARGV&&args[1]==="run")for(let index=2;index<args.length;index++){let arg=args[index];arg==="--watch"?scheduleWatch=!0:["--exec","--poll-seconds","--timeout-seconds","--concurrency"].includes(arg??"")&&index++}if(!(isPackageCommandArgv(args)||args[0]===HOST_COMMAND_ARGV||args[0]===SCHEDULE_COMMAND_ARGV&&!scheduleWatch)){if(!scheduleWatch&&args.some(arg=>["--help","-h","--export","--list-models","--list-tips"].includes(arg)))try{let{parseArgs}=await import("./args-HFYB6URH.js"),parsed=parseArgs(args);if(parsed.version||parsed.export||parsed.listModels!==void 0||parsed.listTips||parsed.help&&!(parsed.mode==="rpc"&&parsed.multiSession))return}catch{}try{let result=enable();result.directory!==void 0&&process.env.NODE_COMPILE_CACHE===void 0&&(process.env.NODE_COMPILE_CACHE=result.directory)}catch{}}}export{dispatchAgentDirectoryCommand,enableStartupCompileCache};
@@ -1,3 +1,3 @@
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{emitProviderAccountsChanged,slotsOfOwnKind,subscriptionLimits}from"./chunk-GILDYS3O.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{discoverEnvSlots}from"./chunk-C4AHHZ6P.js";import{CredentialSlotRepository,applicableStoredState}from"./chunk-J7FW7MED.js";import{roundRobinState}from"./chunk-WHQ2QPP5.js";import{applyAccountOrder,isAvailable,isSlotBlocked,orderAccounts,preferHeadroom,withoutOrderedAccount}from"./chunk-J2NGJKXL.js";import{activeModelBlockUntil,modelBlockApplies,pruneModelBlocks}from"./chunk-NJ43NBSP.js";import{accountDisplayName,listSlots,normalizeProviderId,pinSlot,projectSlot,removeSlot,renameSlotDisplayName}from"./chunk-OH5TKHW7.js";import{getAgentDir}from"./chunk-SODMQEHO.js";import{lstat as lstat2}from"node:fs/promises";import{dirname as dirname3,join as join4}from"node:path";function isForeignAuthBlock(slot){let fields=slot;if(fields.store!=="claude-cli"||fields.blockReason!=="auth_error"||fields.signInRequired==="login_expired")return!1;let verdict=fields.authVerdict;return verdict?.dirId!==fields.dirId||verdict?.at!==fields.blockedAt}function withoutForeignAuthBlock(slot){if(!isForeignAuthBlock(slot))return slot;let{blockedUntil:_until,blockReason:_reason,blockedAt:_at,authVerdict:_verdict,...rest}=slot;return rest}function isEnvSlot(slot){return slot.store===void 0}var SENTINEL_OAUTH_FIELDS={access:"claude-sdk-oauth-managed",refresh:"claude-sdk-oauth-managed",expires:41024448e5};function emptyCredential(){return{type:"oauth",...SENTINEL_OAUTH_FIELDS,accounts:[]}}function storedSlots(credential){return credential.accounts??[]}function isListedStoredSlot(slot){let candidate=slot,name=candidate.name;return candidate.store==="claude-cli"&&typeof name=="string"&&name.trim()!==""}function unusableStoredSlotCount(credential){if(credential===null||typeof credential!="object"||!("accounts"in credential))return 0;let stored=credential.accounts;return Array.isArray(stored)?stored.filter(slot=>slot!==null&&typeof slot=="object"&&slot.store==="claude-cli"&&!isListedStoredSlot(slot)).length:0}function listAccounts(credential,env){let slots=storedSlots(credential).filter(isListedStoredSlot).map(withoutForeignAuthBlock);if(env){let state=credential.slotState??{};for(let slot of envSlots(env)){let persisted=state[slot.name];slots.push(persisted?{...slot,...persisted}:slot)}}return slots}var ACCOUNT_NAME_PATTERN=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;function assertValidAccountName(name){if(!ACCOUNT_NAME_PATTERN.test(name))throw new Error(`Invalid account name '${name}': use letters, digits, '-' or '_', starting with a letter or digit`)}function pinAccount(credential,name){return{...credential,pinned:name}}function envSlots(env){let slots=[],read=suffix=>env(suffix===void 0?"CLAUDE_CODE_OAUTH_TOKEN":`CLAUDE_CODE_OAUTH_TOKEN_${suffix}`),names=[{slot:"env"}];for(let index=2;index<=16;index++)names.push({suffix:String(index),slot:`env-${index}`});for(let{suffix,slot}of names)read(suffix)&&slots.push({name:slot,refresh:"",access:"",expires:0,source:"env"});return slots}function envSlotToken(env,slotName){let match=/^env(?:-(\d+))?$/.exec(slotName);if(!match)return;let suffix=match[1];return env(suffix===void 0?"CLAUDE_CODE_OAUTH_TOKEN":`CLAUDE_CODE_OAUTH_TOKEN_${suffix}`)}import{createHash}from"node:crypto";var DEFAULT_AFFINITY_KEY="claude-sdk-oauth-default";function describeAccountState(state){let until=state.until===void 0?"re-login":new Date(state.until).toISOString(),login=state.reason==="auth_error"?` (run /login anthropic-subscription for ${state.name})`:"";return`${state.name}: ${state.reason} until ${until}${login}`}var AllAccountsBlockedError=class extends Error{constructor(soonestUnblockAt2,blockReason,limitedModel2,unavailableAccount,accounts=[],rateLimitedUntil){let until=soonestUnblockAt2===void 0?void 0:new Date(soonestUnblockAt2).toISOString(),summary=limitedModel2!==void 0&&until!==void 0?`All Anthropic Subscription accounts have hit the usage limit for model ${limitedModel2} until ${until}.`:until===void 0?"All Anthropic Subscription accounts are blocked until re-login.":`All Anthropic Subscription accounts are blocked until ${until}.`;super(accounts.length===0?summary:`${summary} Accounts: ${accounts.map(describeAccountState).join("; ")}.`),this.accounts=accounts,this.limitedModel=limitedModel2,this.name="AllAccountsBlockedError",this.soonestUnblockAt=soonestUnblockAt2,this.blockReason=blockReason,this.unavailableAccount=unavailableAccount,this.rateLimitedUntil=rateLimitedUntil}};function getAffinityKey(options){return options.affinityKey??options.sessionId??DEFAULT_AFFINITY_KEY}function score(key,accountName){return createHash("sha256").update(`${key}\0${accountName}`).digest().readBigUInt64BE(0)}function rendezvousOrder(key,accounts){return[...accounts].map(account=>({account,score:score(key,account.name)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({account})=>account)}function isAccountBlocked(account,now){return account.blockedUntil!==void 0&&account.blockedUntil>now}function isBlockedFor(account,now,model){return isAccountBlocked(account,now)||activeModelBlockUntil(account.modelBlocks,model,now)!==void 0}function clearExpiredBlocks(accounts,now=Date.now()){return accounts.map(account=>{let available=account;if(account.blockReason!==void 0&&(account.blockedUntil===void 0||account.blockedUntil<=now)){let{blockedUntil:_blockedUntil,blockReason:_blockReason,blockedAt:_blockedAt,authVerdict:_authVerdict,...rest2}=account;available=rest2}if(available.modelBlocks===void 0)return available;let{modelBlocks,...rest}=available,live=pruneModelBlocks(modelBlocks,now);return live===void 0?rest:{...rest,modelBlocks:live}})}function selectUnblocked(accounts,options,now,roundRobinOffset=0){let pinned=options.pinnedAccount===void 0?void 0:accounts.find(account=>account.name===options.pinnedAccount);if(pinned&&!isBlockedFor(pinned,now,options.model))return pinned;let preferred=options.preferredAccount===void 0?void 0:accounts.find(account=>account.name===options.preferredAccount),usable=orderAccounts(accounts,rendezvousOrder(getAffinityKey(options),accounts),options.accountOrder,options.accountStrategy,roundRobinOffset).filter(account=>!isBlockedFor(account,now,options.model));return preferHeadroom(usable,"anthropic-subscription",subscriptionLimits.snapshot(),now,preferred?.name)[0]}function unblockAt(account,now,model){let accountUntil=account.blockedUntil!==void 0&&account.blockedUntil>now?account.blockedUntil:void 0,modelUntil=activeModelBlockUntil(account.modelBlocks,model,now);return accountUntil===void 0?modelUntil:modelUntil===void 0?accountUntil:Math.max(accountUntil,modelUntil)}function soonestUnblockAt(accounts,now,model){let candidates=accounts.map(account=>unblockAt(account,now,model)).filter(value=>value!==void 0);return candidates.length===0?void 0:Math.min(...candidates)}var OUT_OF_POOL_REASONS=new Set(["billing","org_not_allowed","auth_error"]);function poolRateLimitedUntil(accounts,now,model){let waiting=accounts.filter(account=>!(isAccountBlocked(account,now)&&OUT_OF_POOL_REASONS.has(account.blockReason??""))),resets=[];for(let account of waiting){let rateLimited=isAccountBlocked(account,now)?account.blockReason==="rate_limit":activeModelBlockUntil(account.modelBlocks,model,now)!==void 0,until=unblockAt(account,now,model);if(!rateLimited||until===void 0)return;resets.push(until)}return resets.length===0?void 0:Math.min(...resets)}function limitedModel(accounts,now,model){return accounts.some(account=>!isAccountBlocked(account,now)&&activeModelBlockUntil(account.modelBlocks,model,now)!==void 0)?model:void 0}function selectAccount(accounts,requestedOptions={}){let roundRobin=requestedOptions.accountStrategy==="round-robin"?roundRobinState.session("anthropic-subscription",getAffinityKey(requestedOptions)):void 0,options=roundRobin?.account!==void 0&&requestedOptions.preferredAccount===void 0?{...requestedOptions,preferredAccount:roundRobin.account}:requestedOptions,now=options.now??Date.now(),candidates=accounts,unavailableAccount;if(options.accountFallback===!1){let name=options.pinnedAccount??options.preferredAccount??orderAccounts(accounts,rendezvousOrder(getAffinityKey(options),accounts),options.accountOrder,options.accountStrategy,roundRobin?.offset)[0]?.name;candidates=accounts.filter(account=>account.name===name);let pinnedBy=options.pinnedAccount!==void 0?options.pinSource:void 0;name!==void 0&&(unavailableAccount={name,configured:candidates.length>0,...pinnedBy===void 0?{}:{pinnedBy}})}let selected=selectUnblocked(candidates,options,now,roundRobin?.offset);if(selected)return roundRobin!==void 0&&(roundRobin.account=selected.name),selected;let cleared=clearExpiredBlocks(candidates,now),afterClear=selectUnblocked(cleared,options,now,roundRobin?.offset);if(afterClear)return roundRobin!==void 0&&(roundRobin.account=afterClear.name),afterClear;throw new AllAccountsBlockedError(soonestUnblockAt(candidates,now,options.model),candidates.length>0&&candidates.every(account=>account.blockReason==="auth_error")?"auth_error":void 0,limitedModel(candidates,now,options.model),unavailableAccount,candidates.map(account=>({name:account.name,reason:account.blockReason??(isAccountBlocked(account,now)?"blocked":"model_limit"),until:unblockAt(account,now,options.model)})),poolRateLimitedUntil(candidates,now,options.model))}import{randomBytes}from"node:crypto";import{chmodSync,constants,lstatSync,mkdirSync,readlinkSync,symlinkSync,unlinkSync}from"node:fs";import{lstat,mkdir,open,rm,unlink}from"node:fs/promises";import{homedir}from"node:os";import{join,resolve}from"node:path";import{spawn}from"node:child_process";function isClaudeOauthTokenName(name){return name==="CLAUDE_CODE_OAUTH_TOKEN"||/^CLAUDE_CODE_OAUTH_TOKEN_\d+$/.test(name)}function hasRequestOauthToken(requestEnvironment){return Object.entries(requestEnvironment??{}).some(([name,value])=>isClaudeOauthTokenName(name)&&!!value)}function mergeRequestAuthEnvironment(hostEnvironment,requestEnvironment){let environment={...hostEnvironment},requestTokens=Object.entries(requestEnvironment??{}).filter(([name])=>isClaudeOauthTokenName(name));if(requestTokens.length===0)return environment;for(let name of Object.keys(environment))isClaudeOauthTokenName(name)&&delete environment[name];for(let[name,value]of requestTokens)environment[name]=value;return environment}function stripManagedAuthEnvironment(parent){let{ANTHROPIC_API_KEY:_apiKey,ANTHROPIC_AUTH_TOKEN:_authToken,ANTHROPIC_BASE_URL:_gateway,ANTHROPIC_CUSTOM_HEADERS:_customHeaders,CLAUDE_CODE_OAUTH_TOKEN:_oauthToken,CLAUDE_CODE_USE_BEDROCK:_bedrock,CLAUDE_CODE_USE_FOUNDRY:_foundry,CLAUDE_CODE_USE_GATEWAY:_gatewayMode,CLAUDE_CODE_USE_VERTEX:_vertex,...environment}=parent;for(let name of Object.keys(environment))/^CLAUDE_CODE_OAUTH_TOKEN_\d+$/.test(name)&&delete environment[name],name.startsWith("SENPI_")&&delete environment[name];return environment}var HOST_REDIRECT_NAMES=["CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CONFIG_DIR","BROWSER"],INHERITED_CREDENTIAL_DESCRIPTORS=["CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR","CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR"];function buildClaudeCliEnvironment(parent,options){let environment=stripManagedAuthEnvironment(parent);for(let name of[...HOST_REDIRECT_NAMES,...INHERITED_CREDENTIAL_DESCRIPTORS])delete environment[name];return environment.CLAUDE_CONFIG_DIR=options.configDir,environment.NO_COLOR="1",options.browser!==void 0&&(environment.BROWSER=options.browser),environment}function spawnClaudeCli(run,args,browser){return spawn(run.executable,[...args],{cwd:run.configDir,env:buildClaudeCliEnvironment(run.parentEnv??process.env,{configDir:run.configDir,...browser===void 0?{}:{browser}}),stdio:["pipe","pipe","pipe"],windowsHide:!0})}function stopClaudeCli(child,graceMs){if(child.exitCode!==null||child.signalCode!==null)return;signalSpawnedChild(child,"SIGTERM");let escalate=setTimeout(()=>signalSpawnedChild(child,"SIGKILL"),graceMs);escalate.unref?.(),child.once("close",()=>clearTimeout(escalate))}var DEFAULT_SHORT_COMMAND_TIMEOUT_MS=1e4;function runClaudeCliToExit(run,args,timeoutMs=DEFAULT_SHORT_COMMAND_TIMEOUT_MS,signal){return signal?.aborted?Promise.resolve(void 0):new Promise(resolve2=>{let child=spawnClaudeCli(run,args);child.stdin?.end();let stdout="";child.stdout?.setEncoding("utf8"),child.stdout?.on("data",chunk=>{stdout+=chunk}),child.stderr?.resume();let deadline=setTimeout(()=>{signalSpawnedChild(child,"SIGKILL"),resolve2(void 0)},timeoutMs);deadline.unref?.();let onAbort=()=>{clearTimeout(deadline),signalSpawnedChild(child,"SIGKILL"),resolve2(void 0)};signal?.addEventListener("abort",onAbort,{once:!0}),child.once("error",()=>{clearTimeout(deadline),signal?.removeEventListener("abort",onAbort),resolve2(void 0)}),child.once("close",exitCode=>{clearTimeout(deadline),signal?.removeEventListener("abort",onAbort),resolve2({exitCode,stdout})})})}function stringField(record,name){let value=record[name];return typeof value=="string"&&value.length>0?value:void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseClaudeCliAuthStatus(stdout,exitCode){let parsed;try{parsed=JSON.parse(stdout)}catch{return{state:"unreadable"}}if(!isRecord(parsed)||typeof parsed.loggedIn!="boolean")return{state:"unreadable"};if(!parsed.loggedIn)return exitCode===0?{state:"unreadable"}:{state:"signed_out"};if(exitCode!==0)return{state:"unreadable"};if(parsed.authMethod!=="claude.ai")return{state:"rejected",reason:"auth_method"};if(parsed.apiProvider!=="firstParty")return{state:"rejected",reason:"api_provider"};let email=stringField(parsed,"email"),orgName=stringField(parsed,"orgName"),subscriptionType=stringField(parsed,"subscriptionType");return{state:"signed_in",profile:{...email===void 0?{}:{email},...orgName===void 0?{}:{orgName},...subscriptionType===void 0?{}:{subscriptionType}}}}async function readClaudeCliAuthStatus(run,timeoutMs){let exit=await runClaudeCliToExit(run,["auth","status","--json"],timeoutMs);return exit===void 0?{state:"unreadable"}:parseClaudeCliAuthStatus(exit.stdout,exit.exitCode)}async function logoutClaudeCli(run,timeoutMs,signal){return(await runClaudeCliToExit(run,["auth","logout"],timeoutMs,signal))?.exitCode===0}var CLAUDE_CLI_SHARED_LINKS=["projects","settings.json","CLAUDE.md","agents","commands","skills","output-styles"],SHARED_FILES=new Set(["settings.json","CLAUDE.md"]),DIR_ID_PATTERN=/^[0-9a-f]{32}$/;function newAccountDirId(){return randomBytes(16).toString("hex")}function isValidAccountDirId(dirId){return DIR_ID_PATTERN.test(dirId)}function accountDirFor(agentDir,dirId){if(!isValidAccountDirId(dirId))throw new Error("Invalid Claude account dir id");return join(agentDir,"anthropic-subscription-claude",dirId)}async function readClaudeCliAccessToken(accountDir,now){let file=join(accountDir,".credentials.json"),parsed;try{let[dirStats,fileStats]=await Promise.all([lstat(accountDir),lstat(file)]);if(!dirStats.isDirectory()||!fileStats.isFile())return;let handle=await open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let opened=await handle.stat();if(!opened.isFile()||opened.ino!==fileStats.ino||opened.dev!==fileStats.dev)return;parsed=JSON.parse(await handle.readFile("utf8"))}finally{await handle.close()}let dirAfter=await lstat(accountDir);if(!dirAfter.isDirectory()||dirAfter.ino!==dirStats.ino||dirAfter.dev!==dirStats.dev)return}catch{return}let oauth=typeof parsed=="object"&&parsed!==null?parsed.claudeAiOauth:void 0;if(typeof oauth!="object"||oauth===null)return;let{accessToken,expiresAt}=oauth;if(!(typeof accessToken!="string"||accessToken==="")&&!(typeof expiresAt=="number"&&expiresAt<=now))return accessToken}function claudeCliSharedRoot(env){let inherited=env.CLAUDE_CONFIG_DIR;return inherited?resolve(inherited):join(homedir(),".claude")}function isLink(path){try{return lstatSync(path).isSymbolicLink()}catch{return!1}}function exists(path){try{return lstatSync(path),!0}catch{return!1}}async function lstatOrUndefined(path){try{return await lstat(path)}catch(error){if(error.code==="ENOENT")return;throw error}}function linkEntry(entry,target,path){if(!SHARED_FILES.has(entry)){mkdirSync(target,{recursive:!0}),symlinkSync(target,path,process.platform==="win32"?"junction":"dir");return}if(exists(target))try{symlinkSync(target,path,"file")}catch(error){if(process.platform!=="win32")throw error}}function ensureAccountDir(options){let accountDir=accountDirFor(options.agentDir,options.dirId);mkdirSync(accountDir,{recursive:!0,mode:448}),process.platform!=="win32"&&chmodSync(accountDir,448);for(let entry of CLAUDE_CLI_SHARED_LINKS){let path=join(accountDir,entry),target=join(options.sharedRoot,entry);if(isLink(path)){if(resolve(accountDir,readlinkSync(path))===resolve(target))continue;unlinkSync(path)}else if(exists(path))continue;linkEntry(entry,target,path)}return accountDir}async function removeAccountDir(options){let accountDir=accountDirFor(options.agentDir,options.dirId);if(options.signal?.throwIfAborted(),await lstatOrUndefined(accountDir)===void 0&&await mkdir(accountDir,{recursive:!0,mode:448}),!(await lstatOrUndefined(accountDir))?.isDirectory())return"not_an_account_dir";let signedOut=options.executable!==void 0&&await logoutClaudeCli({executable:options.executable,configDir:accountDir,...options.parentEnv===void 0?{}:{parentEnv:options.parentEnv}},void 0,options.signal).catch(()=>!1);options.signal?.throwIfAborted();for(let entry of CLAUDE_CLI_SHARED_LINKS){let path=join(accountDir,entry);(await lstatOrUndefined(path))?.isSymbolicLink()&&await unlink(path)}return await rm(accountDir,{recursive:!0,force:!0}),signedOut?"removed":"removed_without_sign_out"}import{readFileSync as readFileSync3,statSync}from"node:fs";import{createRequire}from"node:module";import{dirname as dirname2,posix as posix2,win32 as win322}from"node:path";import{createHash as createHash2,randomBytes as randomBytes2}from"crypto";import{chmodSync as chmodSync2,closeSync,constants as fsConstants,fchmodSync,fstatSync,lstatSync as lstatSync2,mkdirSync as mkdirSync2,openSync,readFileSync,readSync,renameSync,unlinkSync as unlinkSync2,writeFileSync}from"fs";import{tmpdir as osTmpdir}from"os";import{basename,join as join2}from"path";function tmpdir(){return process.env.CLAUDE_CODE_TMPDIR?process.env.CLAUDE_CODE_TMPDIR:process.platform==="darwin"?"/tmp":osTmpdir()}function safeTempBase(){let dir=join2(tmpdir(),process.platform==="win32"?"claude-agent-sdk":`claude-agent-sdk-${process.getuid?.()??0}`);if(typeof process.getuid=="function"){mkdirSync2(dir,{recursive:!0,mode:448});let uid=process.getuid(),st=lstatSync2(dir);if(!st.isDirectory())throw new Error(`Temp directory ${dir} is not a directory (may be an attacker-planted symlink). Refusing to use it.`);if(st.uid!==uid)throw new Error(`Temp directory ${dir} is owned by uid ${st.uid}, expected ${uid}. Refusing to use it \u2014 another user may have pre-created it.`);(st.mode&511)!==448&&chmodSync2(dir,448)}else try{mkdirSync2(dir,{recursive:!0,mode:448})}catch{}return dir}function isNoFileId(ino){return ino===0n||ino===-1n||ino===0xffffffffffffffffn||ino===1n<<64n}function isExtractedCopy(file,content){let fd,inoAtPath;try{if(typeof process.getuid=="function")fd=openSync(file,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK);else{let atPath=lstatSync2(file,{bigint:!0});if(!atPath.isFile())return!1;inoAtPath=atPath.ino,fd=openSync(file,"r")}let st=fstatSync(fd,{bigint:!0});if(!st.isFile()||Number(st.nlink)!==1||Number(st.size)!==content.length||inoAtPath!==void 0&&!isNoFileId(inoAtPath)&&!isNoFileId(st.ino)&&st.ino!==inoAtPath)return!1;let chunk=Buffer.allocUnsafe(1<<20),offset=0;for(;offset<content.length;){let n=readSync(fd,chunk,0,chunk.length,offset);if(n<=0||!chunk.subarray(0,n).equals(content.subarray(offset,offset+n)))return!1;offset+=n}return!0}catch{return!1}finally{fd!==void 0&&closeSync(fd)}}function extractFromBunfs(embeddedPath){if(!embeddedPath.includes("$bunfs")&&!embeddedPath.includes("~BUN"))return embeddedPath;try{let content=readFileSync(embeddedPath),hash=createHash2("sha256").update(content).digest("hex").slice(0,16),tmpDir=join2(safeTempBase(),`claude-agent-sdk-${hash}`),fileName=basename(embeddedPath),tmpPath=join2(tmpDir,fileName);if(mkdirSync2(tmpDir,{recursive:!0,mode:448}),!lstatSync2(tmpDir).isDirectory())throw new Error("The claude-agent-sdk-<hash> folder under the temp directory is a symlink or not a directory, possibly planted; delete it and restart");if(isExtractedCopy(tmpPath,content))return tmpPath;let tmpFile=join2(tmpDir,`${fileName}.tmp.${process.pid}.${randomBytes2(8).toString("hex")}`),fd=openSync(tmpFile,"wx",448),renamed=!1;try{try{writeFileSync(fd,content),fchmodSync(fd,493)}finally{closeSync(fd)}try{renameSync(tmpFile,tmpPath)}catch(e){if(e.code!=="EEXIST"&&e.code!=="EPERM"&&e.code!=="EBUSY")throw e;if(isExtractedCopy(tmpPath,content))return tmpPath;try{unlinkSync2(tmpPath)}catch(unlinkError){if(unlinkError.code!=="ENOENT")throw unlinkError}try{renameSync(tmpFile,tmpPath)}catch{if(isExtractedCopy(tmpPath,content))return tmpPath;throw e}}return renamed=!0,tmpPath}finally{if(!renamed)try{unlinkSync2(tmpFile)}catch{}}}catch(err){return console.warn(`[claude-agent-sdk] Failed to extract CLI from $bunfs: ${err.message}. Child processes cannot access $bunfs paths \u2014 the CLI will likely fail to start.`),embeddedPath}}import{posix,win32}from"node:path";var WIN32_BATCH_EXTENSIONS=new Set([".bat",".cmd"]),CMD_SHIM_NATIVE_TARGET=/"%~?dp0%?\\([^"%]+?\.exe)"/i;function nativeTargetOfBatchFile(batchPath,deps){let text=deps.readText?.(batchPath),match=text===void 0?null:CMD_SHIM_NATIVE_TARGET.exec(text);if(!match?.[1])return;let target=win32.join(win32.dirname(batchPath),match[1]);return deps.isFile(target)?target:void 0}var WIN32_DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function namesToProbe(name,platform,pathext){return platform!=="win32"?[name]:(pathext??WIN32_DEFAULT_PATHEXT).split(";").filter(extension=>extension.length>0).map(extension=>extension.toLowerCase()).map(extension=>`${name}${extension}`)}function pathDirectories(platform,path){if(path===void 0)return[];let delimiter=platform==="win32"?";":":";return path.split(delimiter).map(entry=>platform==="win32"?entry.replace(/^"(.*)"$/,"$1"):entry).filter(entry=>entry.length>0)}function findExecutableOnPath(name,deps){let join5=deps.platform==="win32"?win32.join:posix.join,names=namesToProbe(name,deps.platform,deps.env("PATHEXT"));for(let directory of pathDirectories(deps.platform,deps.env("PATH")))for(let candidate of names){let path=join5(directory,candidate);if(!deps.isFile(path))continue;if(deps.platform!=="win32"||!WIN32_BATCH_EXTENSIONS.has(win32.extname(path).toLowerCase()))return path;let target=nativeTargetOfBatchFile(path,deps);if(target!==void 0)return target;deps.onSkip?.(path)}}import{execFileSync}from"node:child_process";import{readFileSync as readFileSync2}from"node:fs";import{dirname,join as join3}from"node:path";import{fileURLToPath}from"node:url";var VERSION_PATTERN=/(\d+)\.(\d+)\.(\d+)/,VERSION_PROBE_TIMEOUT_MS=5e3;function parseClaudeCodeVersion(text){let match=text===void 0?null:VERSION_PATTERN.exec(text);if(match)return[Number(match[1]),Number(match[2]),Number(match[3])]}function isNewerClaudeCodeVersion(candidate,baseline){let left=parseClaudeCodeVersion(candidate),right=parseClaudeCodeVersion(baseline);if(left===void 0||right===void 0)return!1;for(let index=0;index<3;index++)if(left[index]!==right[index])return left[index]>right[index];return!1}var probedVersions=new Map;function probeClaudeCodeVersion(executable){if(probedVersions.has(executable))return probedVersions.get(executable);let version;try{let output=execFileSync(executable,["--version"],{encoding:"utf8",timeout:VERSION_PROBE_TIMEOUT_MS,windowsHide:!0,stdio:["ignore","pipe","ignore"]});version=VERSION_PATTERN.exec(output)?.[0]}catch{version=void 0}return probedVersions.set(executable,version),version}function bundledClaudeCodeVersion(){try{let entry=fileURLToPath(import.meta.resolve("@anthropic-ai/claude-agent-sdk")),manifest=JSON.parse(readFileSync2(join3(dirname(entry),"package.json"),"utf8"));return typeof manifest!="object"||manifest===null||!("claudeCodeVersion"in manifest)?void 0:typeof manifest.claudeCodeVersion=="string"?manifest.claudeCodeVersion:void 0}catch{return}}function claudeCodeExecutableCandidates(platform,arch,preferMusl=!1){let ext=platform==="win32"?".exe":"";if(platform==="linux"){let glibc=`@anthropic-ai/claude-agent-sdk-linux-${arch}/claude${ext}`,musl=`@anthropic-ai/claude-agent-sdk-linux-${arch}-musl/claude${ext}`;return preferMusl?[musl,glibc]:[glibc,musl]}return[`@anthropic-ai/claude-agent-sdk-${platform}-${arch}/claude${ext}`]}function spawnableSpelling(platform,candidate){return platform==="win32"?win322.toNamespacedPath(win322.resolve(candidate)):posix2.resolve(candidate)}function describeClaudeCodeExecutable(deps){let tried=[],accept=candidate=>{let spelled=spawnableSpelling(deps.platform,candidate);return tried.push(spelled),deps.isFile(spelled)?spelled:void 0},done=(executable,source)=>({executable,source,tried}),override=deps.env("CLAUDE_CODE_EXECUTABLE");if(override){let accepted=accept(override);if(accepted!==void 0)return done(accepted,"override")}let candidates=claudeCodeExecutableCandidates(deps.platform,deps.arch,deps.platform==="linux"&&deps.isMusl?.()===!0),bundled=acceptBundled(deps,candidates,accept,tried);if(bundled!==void 0){let newer=newerClaudeOnPath(deps,bundled);return newer===void 0?done(bundled,"bundled"):(tried.push(newer),done(newer,"path"))}let onPath=findExecutableOnPath("claude",{...deps,onSkip:batchFile=>tried.push(`${batchFile} (batch file wrapping no native binary)`)});if(onPath!==void 0){let accepted=accept(onPath);if(accepted!==void 0)return done(accepted,"path")}else tried.push(deps.env("PATH")?"claude on PATH":"claude on PATH (PATH is unset)");return{executable:void 0,source:void 0,tried}}function acceptBundled(deps,candidates,accept,tried){if(deps.isCompiledBun?.()&&deps.extractFromBunfs)for(let candidate of candidates){let extracted;try{extracted=deps.extractFromBunfs(deps.resolve(candidate))}catch{continue}let accepted=accept(extracted);if(accepted!==void 0)return accepted}for(let candidate of candidates){let resolved;try{resolved=deps.resolve(candidate)}catch{tried.push(candidate);continue}let accepted=accept(resolved);if(accepted!==void 0)return accepted}let executableDir=deps.isCompiledBun?.()?deps.executableDir?.():void 0;if(executableDir!==void 0){let path=deps.platform==="win32"?win322:posix2;for(let candidate of candidates){let accepted=accept(path.join(executableDir,"node_modules",...candidate.split("/")));if(accepted!==void 0)return accepted}}}function newerClaudeOnPath(deps,bundled){let versionOf=deps.versionOf;if(versionOf===void 0)return;let onPath=findExecutableOnPath("claude",deps);if(onPath===void 0)return;let spelled=spawnableSpelling(deps.platform,onPath);if(spelled===bundled||!deps.isFile(spelled))return;let pathVersion=versionOf(spelled);if(pathVersion===void 0)return;let bundledVersion=deps.bundledVersion?.()??versionOf(bundled);return isNewerClaudeCodeVersion(pathVersion,bundledVersion)?spelled:void 0}function resolveClaudeCodeExecutable(deps){return resolveClaudeCodeRun(deps).executable}function resolveClaudeCodeRun(deps){let resolution=describeClaudeCodeExecutable(deps);if(resolution.executable!==void 0&&resolution.source!==void 0)return{executable:resolution.executable,source:resolution.source};throw new Error([`Claude Code executable not found for ${deps.platform}-${deps.arch}. Tried:`,...resolution.tried.map(candidate=>` - ${candidate}`),"Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, install Claude Code so `claude` is on PATH, or set CLAUDE_CODE_EXECUTABLE to the binary."].join(`
2
+ import{emitProviderAccountsChanged,slotsOfOwnKind,subscriptionLimits}from"./chunk-GILDYS3O.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{discoverEnvSlots}from"./chunk-C4AHHZ6P.js";import{CredentialSlotRepository,applicableStoredState}from"./chunk-TCZORL3V.js";import{roundRobinState}from"./chunk-WHQ2QPP5.js";import{applyAccountOrder,isAvailable,isSlotBlocked,orderAccounts,preferHeadroom,withoutOrderedAccount}from"./chunk-LXINMDMX.js";import{activeModelBlockUntil,modelBlockApplies,pruneModelBlocks}from"./chunk-NJ43NBSP.js";import{accountDisplayName,listSlots,normalizeProviderId,pinSlot,projectSlot,removeSlot,renameSlotDisplayName}from"./chunk-OH5TKHW7.js";import{getAgentDir}from"./chunk-SODMQEHO.js";import{lstat as lstat2}from"node:fs/promises";import{dirname as dirname3,join as join4}from"node:path";function isForeignAuthBlock(slot){let fields=slot;if(fields.store!=="claude-cli"||fields.blockReason!=="auth_error"||fields.signInRequired==="login_expired")return!1;let verdict=fields.authVerdict;return verdict?.dirId!==fields.dirId||verdict?.at!==fields.blockedAt}function withoutForeignAuthBlock(slot){if(!isForeignAuthBlock(slot))return slot;let{blockedUntil:_until,blockReason:_reason,blockedAt:_at,authVerdict:_verdict,...rest}=slot;return rest}function isEnvSlot(slot){return slot.store===void 0}var SENTINEL_OAUTH_FIELDS={access:"claude-sdk-oauth-managed",refresh:"claude-sdk-oauth-managed",expires:41024448e5};function emptyCredential(){return{type:"oauth",...SENTINEL_OAUTH_FIELDS,accounts:[]}}function storedSlots(credential){return credential.accounts??[]}function isListedStoredSlot(slot){let candidate=slot,name=candidate.name;return candidate.store==="claude-cli"&&typeof name=="string"&&name.trim()!==""}function unusableStoredSlotCount(credential){if(credential===null||typeof credential!="object"||!("accounts"in credential))return 0;let stored=credential.accounts;return Array.isArray(stored)?stored.filter(slot=>slot!==null&&typeof slot=="object"&&slot.store==="claude-cli"&&!isListedStoredSlot(slot)).length:0}function listAccounts(credential,env){let slots=storedSlots(credential).filter(isListedStoredSlot).map(withoutForeignAuthBlock);if(env){let state=credential.slotState??{};for(let slot of envSlots(env)){let persisted=state[slot.name];slots.push(persisted?{...slot,...persisted}:slot)}}return slots}var ACCOUNT_NAME_PATTERN=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;function assertValidAccountName(name){if(!ACCOUNT_NAME_PATTERN.test(name))throw new Error(`Invalid account name '${name}': use letters, digits, '-' or '_', starting with a letter or digit`)}function pinAccount(credential,name){return{...credential,pinned:name}}function envSlots(env){let slots=[],read=suffix=>env(suffix===void 0?"CLAUDE_CODE_OAUTH_TOKEN":`CLAUDE_CODE_OAUTH_TOKEN_${suffix}`),names=[{slot:"env"}];for(let index=2;index<=16;index++)names.push({suffix:String(index),slot:`env-${index}`});for(let{suffix,slot}of names)read(suffix)&&slots.push({name:slot,refresh:"",access:"",expires:0,source:"env"});return slots}function envSlotToken(env,slotName){let match=/^env(?:-(\d+))?$/.exec(slotName);if(!match)return;let suffix=match[1];return env(suffix===void 0?"CLAUDE_CODE_OAUTH_TOKEN":`CLAUDE_CODE_OAUTH_TOKEN_${suffix}`)}import{createHash}from"node:crypto";var DEFAULT_AFFINITY_KEY="claude-sdk-oauth-default";function describeAccountState(state){let until=state.until===void 0?"re-login":new Date(state.until).toISOString(),login=state.reason==="auth_error"?` (run /login anthropic-subscription for ${state.name})`:"";return`${state.name}: ${state.reason} until ${until}${login}`}var AllAccountsBlockedError=class extends Error{constructor(soonestUnblockAt2,blockReason,limitedModel2,unavailableAccount,accounts=[],rateLimitedUntil){let until=soonestUnblockAt2===void 0?void 0:new Date(soonestUnblockAt2).toISOString(),summary=limitedModel2!==void 0&&until!==void 0?`All Anthropic Subscription accounts have hit the usage limit for model ${limitedModel2} until ${until}.`:until===void 0?"All Anthropic Subscription accounts are blocked until re-login.":`All Anthropic Subscription accounts are blocked until ${until}.`;super(accounts.length===0?summary:`${summary} Accounts: ${accounts.map(describeAccountState).join("; ")}.`),this.accounts=accounts,this.limitedModel=limitedModel2,this.name="AllAccountsBlockedError",this.soonestUnblockAt=soonestUnblockAt2,this.blockReason=blockReason,this.unavailableAccount=unavailableAccount,this.rateLimitedUntil=rateLimitedUntil}};function getAffinityKey(options){return options.affinityKey??options.sessionId??DEFAULT_AFFINITY_KEY}function score(key,accountName){return createHash("sha256").update(`${key}\0${accountName}`).digest().readBigUInt64BE(0)}function rendezvousOrder(key,accounts){return[...accounts].map(account=>({account,score:score(key,account.name)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({account})=>account)}function isAccountBlocked(account,now){return account.blockedUntil!==void 0&&account.blockedUntil>now}function isBlockedFor(account,now,model){return isAccountBlocked(account,now)||activeModelBlockUntil(account.modelBlocks,model,now)!==void 0}function clearExpiredBlocks(accounts,now=Date.now()){return accounts.map(account=>{let available=account;if(account.blockReason!==void 0&&(account.blockedUntil===void 0||account.blockedUntil<=now)){let{blockedUntil:_blockedUntil,blockReason:_blockReason,blockedAt:_blockedAt,authVerdict:_authVerdict,...rest2}=account;available=rest2}if(available.modelBlocks===void 0)return available;let{modelBlocks,...rest}=available,live=pruneModelBlocks(modelBlocks,now);return live===void 0?rest:{...rest,modelBlocks:live}})}function selectUnblocked(accounts,options,now,roundRobinOffset=0){let pinned=options.pinnedAccount===void 0?void 0:accounts.find(account=>account.name===options.pinnedAccount);if(pinned&&!isBlockedFor(pinned,now,options.model))return pinned;let preferred=options.preferredAccount===void 0?void 0:accounts.find(account=>account.name===options.preferredAccount),usable=orderAccounts(accounts,rendezvousOrder(getAffinityKey(options),accounts),options.accountOrder,options.accountStrategy,roundRobinOffset).filter(account=>!isBlockedFor(account,now,options.model));return preferHeadroom(usable,"anthropic-subscription",subscriptionLimits.snapshot(),now,preferred?.name)[0]}function unblockAt(account,now,model){let accountUntil=account.blockedUntil!==void 0&&account.blockedUntil>now?account.blockedUntil:void 0,modelUntil=activeModelBlockUntil(account.modelBlocks,model,now);return accountUntil===void 0?modelUntil:modelUntil===void 0?accountUntil:Math.max(accountUntil,modelUntil)}function soonestUnblockAt(accounts,now,model){let candidates=accounts.map(account=>unblockAt(account,now,model)).filter(value=>value!==void 0);return candidates.length===0?void 0:Math.min(...candidates)}var OUT_OF_POOL_REASONS=new Set(["billing","org_not_allowed","auth_error"]);function poolRateLimitedUntil(accounts,now,model){let waiting=accounts.filter(account=>!(isAccountBlocked(account,now)&&OUT_OF_POOL_REASONS.has(account.blockReason??""))),resets=[];for(let account of waiting){let rateLimited=isAccountBlocked(account,now)?account.blockReason==="rate_limit":activeModelBlockUntil(account.modelBlocks,model,now)!==void 0,until=unblockAt(account,now,model);if(!rateLimited||until===void 0)return;resets.push(until)}return resets.length===0?void 0:Math.min(...resets)}function limitedModel(accounts,now,model){return accounts.some(account=>!isAccountBlocked(account,now)&&activeModelBlockUntil(account.modelBlocks,model,now)!==void 0)?model:void 0}function selectAccount(accounts,requestedOptions={}){let roundRobin=requestedOptions.accountStrategy==="round-robin"?roundRobinState.session("anthropic-subscription",getAffinityKey(requestedOptions)):void 0,options=roundRobin?.account!==void 0&&requestedOptions.preferredAccount===void 0?{...requestedOptions,preferredAccount:roundRobin.account}:requestedOptions,now=options.now??Date.now(),candidates=accounts,unavailableAccount;if(options.accountFallback===!1){let name=options.pinnedAccount??options.preferredAccount??orderAccounts(accounts,rendezvousOrder(getAffinityKey(options),accounts),options.accountOrder,options.accountStrategy,roundRobin?.offset)[0]?.name;candidates=accounts.filter(account=>account.name===name);let pinnedBy=options.pinnedAccount!==void 0?options.pinSource:void 0;name!==void 0&&(unavailableAccount={name,configured:candidates.length>0,...pinnedBy===void 0?{}:{pinnedBy}})}let selected=selectUnblocked(candidates,options,now,roundRobin?.offset);if(selected)return roundRobin!==void 0&&(roundRobin.account=selected.name),selected;let cleared=clearExpiredBlocks(candidates,now),afterClear=selectUnblocked(cleared,options,now,roundRobin?.offset);if(afterClear)return roundRobin!==void 0&&(roundRobin.account=afterClear.name),afterClear;throw new AllAccountsBlockedError(soonestUnblockAt(candidates,now,options.model),candidates.length>0&&candidates.every(account=>account.blockReason==="auth_error")?"auth_error":void 0,limitedModel(candidates,now,options.model),unavailableAccount,candidates.map(account=>({name:account.name,reason:account.blockReason??(isAccountBlocked(account,now)?"blocked":"model_limit"),until:unblockAt(account,now,options.model)})),poolRateLimitedUntil(candidates,now,options.model))}import{randomBytes}from"node:crypto";import{chmodSync,constants,lstatSync,mkdirSync,readlinkSync,symlinkSync,unlinkSync}from"node:fs";import{lstat,mkdir,open,rm,unlink}from"node:fs/promises";import{homedir}from"node:os";import{join,resolve}from"node:path";import{spawn}from"node:child_process";function isClaudeOauthTokenName(name){return name==="CLAUDE_CODE_OAUTH_TOKEN"||/^CLAUDE_CODE_OAUTH_TOKEN_\d+$/.test(name)}function hasRequestOauthToken(requestEnvironment){return Object.entries(requestEnvironment??{}).some(([name,value])=>isClaudeOauthTokenName(name)&&!!value)}function mergeRequestAuthEnvironment(hostEnvironment,requestEnvironment){let environment={...hostEnvironment},requestTokens=Object.entries(requestEnvironment??{}).filter(([name])=>isClaudeOauthTokenName(name));if(requestTokens.length===0)return environment;for(let name of Object.keys(environment))isClaudeOauthTokenName(name)&&delete environment[name];for(let[name,value]of requestTokens)environment[name]=value;return environment}function stripManagedAuthEnvironment(parent){let{ANTHROPIC_API_KEY:_apiKey,ANTHROPIC_AUTH_TOKEN:_authToken,ANTHROPIC_BASE_URL:_gateway,ANTHROPIC_CUSTOM_HEADERS:_customHeaders,CLAUDE_CODE_OAUTH_TOKEN:_oauthToken,CLAUDE_CODE_USE_BEDROCK:_bedrock,CLAUDE_CODE_USE_FOUNDRY:_foundry,CLAUDE_CODE_USE_GATEWAY:_gatewayMode,CLAUDE_CODE_USE_VERTEX:_vertex,...environment}=parent;for(let name of Object.keys(environment))/^CLAUDE_CODE_OAUTH_TOKEN_\d+$/.test(name)&&delete environment[name],name.startsWith("SENPI_")&&delete environment[name];return environment}var HOST_REDIRECT_NAMES=["CLAUDE_SECURESTORAGE_CONFIG_DIR","CLAUDE_CONFIG_DIR","BROWSER"],INHERITED_CREDENTIAL_DESCRIPTORS=["CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR","CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR"];function buildClaudeCliEnvironment(parent,options){let environment=stripManagedAuthEnvironment(parent);for(let name of[...HOST_REDIRECT_NAMES,...INHERITED_CREDENTIAL_DESCRIPTORS])delete environment[name];return environment.CLAUDE_CONFIG_DIR=options.configDir,environment.NO_COLOR="1",options.browser!==void 0&&(environment.BROWSER=options.browser),environment}function spawnClaudeCli(run,args,browser){return spawn(run.executable,[...args],{cwd:run.configDir,env:buildClaudeCliEnvironment(run.parentEnv??process.env,{configDir:run.configDir,...browser===void 0?{}:{browser}}),stdio:["pipe","pipe","pipe"],windowsHide:!0})}function stopClaudeCli(child,graceMs){if(child.exitCode!==null||child.signalCode!==null)return;signalSpawnedChild(child,"SIGTERM");let escalate=setTimeout(()=>signalSpawnedChild(child,"SIGKILL"),graceMs);escalate.unref?.(),child.once("close",()=>clearTimeout(escalate))}var DEFAULT_SHORT_COMMAND_TIMEOUT_MS=1e4;function runClaudeCliToExit(run,args,timeoutMs=DEFAULT_SHORT_COMMAND_TIMEOUT_MS,signal){return signal?.aborted?Promise.resolve(void 0):new Promise(resolve2=>{let child=spawnClaudeCli(run,args);child.stdin?.end();let stdout="";child.stdout?.setEncoding("utf8"),child.stdout?.on("data",chunk=>{stdout+=chunk}),child.stderr?.resume();let deadline=setTimeout(()=>{signalSpawnedChild(child,"SIGKILL"),resolve2(void 0)},timeoutMs);deadline.unref?.();let onAbort=()=>{clearTimeout(deadline),signalSpawnedChild(child,"SIGKILL"),resolve2(void 0)};signal?.addEventListener("abort",onAbort,{once:!0}),child.once("error",()=>{clearTimeout(deadline),signal?.removeEventListener("abort",onAbort),resolve2(void 0)}),child.once("close",exitCode=>{clearTimeout(deadline),signal?.removeEventListener("abort",onAbort),resolve2({exitCode,stdout})})})}function stringField(record,name){let value=record[name];return typeof value=="string"&&value.length>0?value:void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseClaudeCliAuthStatus(stdout,exitCode){let parsed;try{parsed=JSON.parse(stdout)}catch{return{state:"unreadable"}}if(!isRecord(parsed)||typeof parsed.loggedIn!="boolean")return{state:"unreadable"};if(!parsed.loggedIn)return exitCode===0?{state:"unreadable"}:{state:"signed_out"};if(exitCode!==0)return{state:"unreadable"};if(parsed.authMethod!=="claude.ai")return{state:"rejected",reason:"auth_method"};if(parsed.apiProvider!=="firstParty")return{state:"rejected",reason:"api_provider"};let email=stringField(parsed,"email"),orgName=stringField(parsed,"orgName"),subscriptionType=stringField(parsed,"subscriptionType");return{state:"signed_in",profile:{...email===void 0?{}:{email},...orgName===void 0?{}:{orgName},...subscriptionType===void 0?{}:{subscriptionType}}}}async function readClaudeCliAuthStatus(run,timeoutMs){let exit=await runClaudeCliToExit(run,["auth","status","--json"],timeoutMs);return exit===void 0?{state:"unreadable"}:parseClaudeCliAuthStatus(exit.stdout,exit.exitCode)}async function logoutClaudeCli(run,timeoutMs,signal){return(await runClaudeCliToExit(run,["auth","logout"],timeoutMs,signal))?.exitCode===0}var CLAUDE_CLI_SHARED_LINKS=["projects","settings.json","CLAUDE.md","agents","commands","skills","output-styles"],SHARED_FILES=new Set(["settings.json","CLAUDE.md"]),DIR_ID_PATTERN=/^[0-9a-f]{32}$/;function newAccountDirId(){return randomBytes(16).toString("hex")}function isValidAccountDirId(dirId){return DIR_ID_PATTERN.test(dirId)}function accountDirFor(agentDir,dirId){if(!isValidAccountDirId(dirId))throw new Error("Invalid Claude account dir id");return join(agentDir,"anthropic-subscription-claude",dirId)}async function readClaudeCliAccessToken(accountDir,now){let file=join(accountDir,".credentials.json"),parsed;try{let[dirStats,fileStats]=await Promise.all([lstat(accountDir),lstat(file)]);if(!dirStats.isDirectory()||!fileStats.isFile())return;let handle=await open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let opened=await handle.stat();if(!opened.isFile()||opened.ino!==fileStats.ino||opened.dev!==fileStats.dev)return;parsed=JSON.parse(await handle.readFile("utf8"))}finally{await handle.close()}let dirAfter=await lstat(accountDir);if(!dirAfter.isDirectory()||dirAfter.ino!==dirStats.ino||dirAfter.dev!==dirStats.dev)return}catch{return}let oauth=typeof parsed=="object"&&parsed!==null?parsed.claudeAiOauth:void 0;if(typeof oauth!="object"||oauth===null)return;let{accessToken,expiresAt}=oauth;if(!(typeof accessToken!="string"||accessToken==="")&&!(typeof expiresAt=="number"&&expiresAt<=now))return accessToken}function claudeCliSharedRoot(env){let inherited=env.CLAUDE_CONFIG_DIR;return inherited?resolve(inherited):join(homedir(),".claude")}function isLink(path){try{return lstatSync(path).isSymbolicLink()}catch{return!1}}function exists(path){try{return lstatSync(path),!0}catch{return!1}}async function lstatOrUndefined(path){try{return await lstat(path)}catch(error){if(error.code==="ENOENT")return;throw error}}function linkEntry(entry,target,path){if(!SHARED_FILES.has(entry)){mkdirSync(target,{recursive:!0}),symlinkSync(target,path,process.platform==="win32"?"junction":"dir");return}if(exists(target))try{symlinkSync(target,path,"file")}catch(error){if(process.platform!=="win32")throw error}}function ensureAccountDir(options){let accountDir=accountDirFor(options.agentDir,options.dirId);mkdirSync(accountDir,{recursive:!0,mode:448}),process.platform!=="win32"&&chmodSync(accountDir,448);for(let entry of CLAUDE_CLI_SHARED_LINKS){let path=join(accountDir,entry),target=join(options.sharedRoot,entry);if(isLink(path)){if(resolve(accountDir,readlinkSync(path))===resolve(target))continue;unlinkSync(path)}else if(exists(path))continue;linkEntry(entry,target,path)}return accountDir}async function removeAccountDir(options){let accountDir=accountDirFor(options.agentDir,options.dirId);if(options.signal?.throwIfAborted(),await lstatOrUndefined(accountDir)===void 0&&await mkdir(accountDir,{recursive:!0,mode:448}),!(await lstatOrUndefined(accountDir))?.isDirectory())return"not_an_account_dir";let signedOut=options.executable!==void 0&&await logoutClaudeCli({executable:options.executable,configDir:accountDir,...options.parentEnv===void 0?{}:{parentEnv:options.parentEnv}},void 0,options.signal).catch(()=>!1);options.signal?.throwIfAborted();for(let entry of CLAUDE_CLI_SHARED_LINKS){let path=join(accountDir,entry);(await lstatOrUndefined(path))?.isSymbolicLink()&&await unlink(path)}return await rm(accountDir,{recursive:!0,force:!0}),signedOut?"removed":"removed_without_sign_out"}import{readFileSync as readFileSync3,statSync}from"node:fs";import{createRequire}from"node:module";import{dirname as dirname2,posix as posix2,win32 as win322}from"node:path";import{createHash as createHash2,randomBytes as randomBytes2}from"crypto";import{chmodSync as chmodSync2,closeSync,constants as fsConstants,fchmodSync,fstatSync,lstatSync as lstatSync2,mkdirSync as mkdirSync2,openSync,readFileSync,readSync,renameSync,unlinkSync as unlinkSync2,writeFileSync}from"fs";import{tmpdir as osTmpdir}from"os";import{basename,join as join2}from"path";function tmpdir(){return process.env.CLAUDE_CODE_TMPDIR?process.env.CLAUDE_CODE_TMPDIR:process.platform==="darwin"?"/tmp":osTmpdir()}function safeTempBase(){let dir=join2(tmpdir(),process.platform==="win32"?"claude-agent-sdk":`claude-agent-sdk-${process.getuid?.()??0}`);if(typeof process.getuid=="function"){mkdirSync2(dir,{recursive:!0,mode:448});let uid=process.getuid(),st=lstatSync2(dir);if(!st.isDirectory())throw new Error(`Temp directory ${dir} is not a directory (may be an attacker-planted symlink). Refusing to use it.`);if(st.uid!==uid)throw new Error(`Temp directory ${dir} is owned by uid ${st.uid}, expected ${uid}. Refusing to use it \u2014 another user may have pre-created it.`);(st.mode&511)!==448&&chmodSync2(dir,448)}else try{mkdirSync2(dir,{recursive:!0,mode:448})}catch{}return dir}function isNoFileId(ino){return ino===0n||ino===-1n||ino===0xffffffffffffffffn||ino===1n<<64n}function isExtractedCopy(file,content){let fd,inoAtPath;try{if(typeof process.getuid=="function")fd=openSync(file,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK);else{let atPath=lstatSync2(file,{bigint:!0});if(!atPath.isFile())return!1;inoAtPath=atPath.ino,fd=openSync(file,"r")}let st=fstatSync(fd,{bigint:!0});if(!st.isFile()||Number(st.nlink)!==1||Number(st.size)!==content.length||inoAtPath!==void 0&&!isNoFileId(inoAtPath)&&!isNoFileId(st.ino)&&st.ino!==inoAtPath)return!1;let chunk=Buffer.allocUnsafe(1<<20),offset=0;for(;offset<content.length;){let n=readSync(fd,chunk,0,chunk.length,offset);if(n<=0||!chunk.subarray(0,n).equals(content.subarray(offset,offset+n)))return!1;offset+=n}return!0}catch{return!1}finally{fd!==void 0&&closeSync(fd)}}function extractFromBunfs(embeddedPath){if(!embeddedPath.includes("$bunfs")&&!embeddedPath.includes("~BUN"))return embeddedPath;try{let content=readFileSync(embeddedPath),hash=createHash2("sha256").update(content).digest("hex").slice(0,16),tmpDir=join2(safeTempBase(),`claude-agent-sdk-${hash}`),fileName=basename(embeddedPath),tmpPath=join2(tmpDir,fileName);if(mkdirSync2(tmpDir,{recursive:!0,mode:448}),!lstatSync2(tmpDir).isDirectory())throw new Error("The claude-agent-sdk-<hash> folder under the temp directory is a symlink or not a directory, possibly planted; delete it and restart");if(isExtractedCopy(tmpPath,content))return tmpPath;let tmpFile=join2(tmpDir,`${fileName}.tmp.${process.pid}.${randomBytes2(8).toString("hex")}`),fd=openSync(tmpFile,"wx",448),renamed=!1;try{try{writeFileSync(fd,content),fchmodSync(fd,493)}finally{closeSync(fd)}try{renameSync(tmpFile,tmpPath)}catch(e){if(e.code!=="EEXIST"&&e.code!=="EPERM"&&e.code!=="EBUSY")throw e;if(isExtractedCopy(tmpPath,content))return tmpPath;try{unlinkSync2(tmpPath)}catch(unlinkError){if(unlinkError.code!=="ENOENT")throw unlinkError}try{renameSync(tmpFile,tmpPath)}catch{if(isExtractedCopy(tmpPath,content))return tmpPath;throw e}}return renamed=!0,tmpPath}finally{if(!renamed)try{unlinkSync2(tmpFile)}catch{}}}catch(err){return console.warn(`[claude-agent-sdk] Failed to extract CLI from $bunfs: ${err.message}. Child processes cannot access $bunfs paths \u2014 the CLI will likely fail to start.`),embeddedPath}}import{posix,win32}from"node:path";var WIN32_BATCH_EXTENSIONS=new Set([".bat",".cmd"]),CMD_SHIM_NATIVE_TARGET=/"%~?dp0%?\\([^"%]+?\.exe)"/i;function nativeTargetOfBatchFile(batchPath,deps){let text=deps.readText?.(batchPath),match=text===void 0?null:CMD_SHIM_NATIVE_TARGET.exec(text);if(!match?.[1])return;let target=win32.join(win32.dirname(batchPath),match[1]);return deps.isFile(target)?target:void 0}var WIN32_DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function namesToProbe(name,platform,pathext){return platform!=="win32"?[name]:(pathext??WIN32_DEFAULT_PATHEXT).split(";").filter(extension=>extension.length>0).map(extension=>extension.toLowerCase()).map(extension=>`${name}${extension}`)}function pathDirectories(platform,path){if(path===void 0)return[];let delimiter=platform==="win32"?";":":";return path.split(delimiter).map(entry=>platform==="win32"?entry.replace(/^"(.*)"$/,"$1"):entry).filter(entry=>entry.length>0)}function findExecutableOnPath(name,deps){let join5=deps.platform==="win32"?win32.join:posix.join,names=namesToProbe(name,deps.platform,deps.env("PATHEXT"));for(let directory of pathDirectories(deps.platform,deps.env("PATH")))for(let candidate of names){let path=join5(directory,candidate);if(!deps.isFile(path))continue;if(deps.platform!=="win32"||!WIN32_BATCH_EXTENSIONS.has(win32.extname(path).toLowerCase()))return path;let target=nativeTargetOfBatchFile(path,deps);if(target!==void 0)return target;deps.onSkip?.(path)}}import{execFileSync}from"node:child_process";import{readFileSync as readFileSync2}from"node:fs";import{dirname,join as join3}from"node:path";import{fileURLToPath}from"node:url";var VERSION_PATTERN=/(\d+)\.(\d+)\.(\d+)/,VERSION_PROBE_TIMEOUT_MS=5e3;function parseClaudeCodeVersion(text){let match=text===void 0?null:VERSION_PATTERN.exec(text);if(match)return[Number(match[1]),Number(match[2]),Number(match[3])]}function isNewerClaudeCodeVersion(candidate,baseline){let left=parseClaudeCodeVersion(candidate),right=parseClaudeCodeVersion(baseline);if(left===void 0||right===void 0)return!1;for(let index=0;index<3;index++)if(left[index]!==right[index])return left[index]>right[index];return!1}var probedVersions=new Map;function probeClaudeCodeVersion(executable){if(probedVersions.has(executable))return probedVersions.get(executable);let version;try{let output=execFileSync(executable,["--version"],{encoding:"utf8",timeout:VERSION_PROBE_TIMEOUT_MS,windowsHide:!0,stdio:["ignore","pipe","ignore"]});version=VERSION_PATTERN.exec(output)?.[0]}catch{version=void 0}return probedVersions.set(executable,version),version}function bundledClaudeCodeVersion(){try{let entry=fileURLToPath(import.meta.resolve("@anthropic-ai/claude-agent-sdk")),manifest=JSON.parse(readFileSync2(join3(dirname(entry),"package.json"),"utf8"));return typeof manifest!="object"||manifest===null||!("claudeCodeVersion"in manifest)?void 0:typeof manifest.claudeCodeVersion=="string"?manifest.claudeCodeVersion:void 0}catch{return}}function claudeCodeExecutableCandidates(platform,arch,preferMusl=!1){let ext=platform==="win32"?".exe":"";if(platform==="linux"){let glibc=`@anthropic-ai/claude-agent-sdk-linux-${arch}/claude${ext}`,musl=`@anthropic-ai/claude-agent-sdk-linux-${arch}-musl/claude${ext}`;return preferMusl?[musl,glibc]:[glibc,musl]}return[`@anthropic-ai/claude-agent-sdk-${platform}-${arch}/claude${ext}`]}function spawnableSpelling(platform,candidate){return platform==="win32"?win322.toNamespacedPath(win322.resolve(candidate)):posix2.resolve(candidate)}function describeClaudeCodeExecutable(deps){let tried=[],accept=candidate=>{let spelled=spawnableSpelling(deps.platform,candidate);return tried.push(spelled),deps.isFile(spelled)?spelled:void 0},done=(executable,source)=>({executable,source,tried}),override=deps.env("CLAUDE_CODE_EXECUTABLE");if(override){let accepted=accept(override);if(accepted!==void 0)return done(accepted,"override")}let candidates=claudeCodeExecutableCandidates(deps.platform,deps.arch,deps.platform==="linux"&&deps.isMusl?.()===!0),bundled=acceptBundled(deps,candidates,accept,tried);if(bundled!==void 0){let newer=newerClaudeOnPath(deps,bundled);return newer===void 0?done(bundled,"bundled"):(tried.push(newer),done(newer,"path"))}let onPath=findExecutableOnPath("claude",{...deps,onSkip:batchFile=>tried.push(`${batchFile} (batch file wrapping no native binary)`)});if(onPath!==void 0){let accepted=accept(onPath);if(accepted!==void 0)return done(accepted,"path")}else tried.push(deps.env("PATH")?"claude on PATH":"claude on PATH (PATH is unset)");return{executable:void 0,source:void 0,tried}}function acceptBundled(deps,candidates,accept,tried){if(deps.isCompiledBun?.()&&deps.extractFromBunfs)for(let candidate of candidates){let extracted;try{extracted=deps.extractFromBunfs(deps.resolve(candidate))}catch{continue}let accepted=accept(extracted);if(accepted!==void 0)return accepted}for(let candidate of candidates){let resolved;try{resolved=deps.resolve(candidate)}catch{tried.push(candidate);continue}let accepted=accept(resolved);if(accepted!==void 0)return accepted}let executableDir=deps.isCompiledBun?.()?deps.executableDir?.():void 0;if(executableDir!==void 0){let path=deps.platform==="win32"?win322:posix2;for(let candidate of candidates){let accepted=accept(path.join(executableDir,"node_modules",...candidate.split("/")));if(accepted!==void 0)return accepted}}}function newerClaudeOnPath(deps,bundled){let versionOf=deps.versionOf;if(versionOf===void 0)return;let onPath=findExecutableOnPath("claude",deps);if(onPath===void 0)return;let spelled=spawnableSpelling(deps.platform,onPath);if(spelled===bundled||!deps.isFile(spelled))return;let pathVersion=versionOf(spelled);if(pathVersion===void 0)return;let bundledVersion=deps.bundledVersion?.()??versionOf(bundled);return isNewerClaudeCodeVersion(pathVersion,bundledVersion)?spelled:void 0}function resolveClaudeCodeExecutable(deps){return resolveClaudeCodeRun(deps).executable}function resolveClaudeCodeRun(deps){let resolution=describeClaudeCodeExecutable(deps);if(resolution.executable!==void 0&&resolution.source!==void 0)return{executable:resolution.executable,source:resolution.source};throw new Error([`Claude Code executable not found for ${deps.platform}-${deps.arch}. Tried:`,...resolution.tried.map(candidate=>` - ${candidate}`),"Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, install Claude Code so `claude` is on PATH, or set CLAUDE_CODE_EXECUTABLE to the binary."].join(`
3
3
  `))}var defaultRequire=null,isCompiledBunBinary=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN");function isMuslLinuxRuntime(){if(process.platform!=="linux"||typeof process.report?.getReport!="function")return!1;let report=process.report.getReport();return report===null||!("header"in report)||typeof report.header!="object"||report.header===null?!1:!("glibcVersionRuntime"in report.header)||report.header.glibcVersionRuntime===void 0}function readBatchFileText(path){try{return readFileSync3(path,"utf8")}catch{return}}function isRegularFile(path){try{return statSync(path).isFile()}catch{return!1}}var defaultDeps={platform:process.platform,arch:process.arch,env:name=>process.env[name],isFile:isRegularFile,readText:readBatchFileText,isMusl:isMuslLinuxRuntime,isCompiledBun:()=>isCompiledBunBinary,extractFromBunfs,bundledVersion:bundledClaudeCodeVersion,versionOf:probeClaudeCodeVersion,executableDir:()=>dirname2(process.execPath),resolve:spec=>(defaultRequire||(defaultRequire=createRequire(import.meta.resolve("@anthropic-ai/claude-agent-sdk"))),defaultRequire.resolve(spec))},activeDeps=defaultDeps;function defaultExecutableDeps(){return activeDeps}function accountCanServe(account,modelId,now){return account.blocked||account.signedOut===!0?!1:!(account.blockedModels??[]).some(block=>block.until>now&&modelBlockApplies(block.model,modelId))}function objectField(value,key){let found=Object.entries(value).find(([candidate])=>candidate===key)?.[1];return typeof found=="object"&&found!==null&&!Array.isArray(found)?found:void 0}function storedCheck(slot){let check=objectField(slot,"check");if(check===void 0)return;let model=stringField2(check,"model"),outcome=stringField2(check,"outcome"),at=numberField(check,"at");if(model===void 0||at===void 0||outcome!=="ok"&&outcome!=="failed")return;let reason=stringField2(check,"reason");return{model,outcome,...reason===void 0?{}:{reason},at}}function claudeCliSlotFields(slot){if(stringField2(slot,"store")!=="claude-cli")return{};let profile=objectField(slot,"profile")??{},signedInAt=numberField(slot,"signedInAt"),email=stringField2(profile,"email"),orgName=stringField2(profile,"orgName"),subscriptionType=stringField2(profile,"subscriptionType"),check=storedCheck(slot);return{store:"claude-cli",...signedInAt===void 0?{}:{signedInAt},...email===void 0?{}:{email},...orgName===void 0?{}:{orgName},...subscriptionType===void 0?{}:{subscriptionType},...check===void 0?{}:{check},signIn:stringField2(slot,"signInRequired")===void 0?"signed_in":"needs_sign_in"}}var ACCOUNT_NAME_PATTERN2=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;function assertValidAccountName2(name){if(!ACCOUNT_NAME_PATTERN2.test(name))throw new Error(`Invalid account name '${name}': use letters, digits, '-' or '_', starting with a letter or digit`)}function selectedOAuthAccount(storage,provider,name){assertValidAccountName2(name);let credential=projectSlot(storage.get(provider),name);if(credential?.type!=="oauth")throw new Error(`OAuth account not found: ${name}`);return credential}function pooledFrom(credential){return credential===void 0?void 0:credential}function pinnedName(credential){return credential?.pinned}function numberField(value,key){let found=Object.entries(value).find(([candidate])=>candidate===key)?.[1];return typeof found=="number"?found:void 0}function credentialPoolRepository(storage){let authPath=storage.getStoragePath();return new CredentialSlotRepository(authPath?join4(dirname3(authPath),"credential-pool-state.json"):void 0)}function stringField2(value,key){let found=Object.entries(value).find(([candidate])=>candidate===key)?.[1];return typeof found=="string"?found:void 0}var UNBLOCKED={blocked:!1};function accountBlockedReason(reason){switch(reason){case"auth_error":case"rate_limit":return reason;case"account_disabled":return"disabled";default:return}}function liveBlock(reason,blockedUntil,now){let blockedReason=accountBlockedReason(reason);return blockedReason==="disabled"?{blocked:!0,blockedReason}:blockedUntil===void 0||blockedUntil<=now?UNBLOCKED:{blocked:!0,...blockedReason===void 0?{}:{blockedReason},blockedUntil}}function sidecarBlock(sidecar,now){return sidecar?.usageLimit?{blocked:!0,paused:!0,usageUrl:"https://chatgpt.com/settings/usage"}:sidecar===void 0||isAvailable(sidecar,now)?UNBLOCKED:liveBlock(sidecar?.blockReason,sidecar?.blockedUntil,now)}function storedSlotBlock(provider,slot,now){let blockReason=stringField2(slot,"blockReason"),blockedUntil=numberField(slot,"blockedUntil"),blockedReason=accountBlockedReason(blockReason);return blockedReason==="disabled"?{blocked:!0,blockedReason}:normalizeProviderId(provider)==="anthropic-subscription"&&isForeignAuthBlock(slot)||!(normalizeProviderId(provider)==="anthropic-subscription"?isAccountBlocked({blockedUntil},now):isSlotBlocked({blockReason,blockedUntil},now))?UNBLOCKED:{blocked:!0,...blockedReason===void 0?{}:{blockedReason},...blockedUntil===void 0||blockedUntil<=now?{}:{blockedUntil}}}function slotBlocked(provider,slot,sidecar,now){let fromSidecar=sidecarBlock(sidecar,now),lane=normalizeProviderId(provider);if(lane!=="cursor-cli-oauth"&&lane!=="anthropic-subscription")return fromSidecar;let fromSlot=storedSlotBlock(provider,slot,now);if(fromSlot.blockedReason==="disabled")return fromSlot;if(fromSidecar.blockedReason==="disabled"||!fromSlot.blocked)return fromSidecar;if(!fromSidecar.blocked||fromSlot.blockedUntil===void 0)return fromSlot;let later=(fromSlot.blockedUntil??0)>(fromSidecar.blockedUntil??0)?fromSlot:fromSidecar;return[fromSidecar,fromSlot].some(block=>block.blockedReason==="auth_error")?{...later,blockedReason:"auth_error"}:later}function storedModelBlocks(slot){let found=Object.entries(slot).find(([candidate])=>candidate==="modelBlocks")?.[1];if(found===null||typeof found!="object")return;let entries=Object.entries(found).flatMap(([model,block])=>{let until=block!==null&&typeof block=="object"?numberField(block,"blockedUntil"):void 0;return until===void 0?[]:[[model,{blockedUntil:until}]]});return entries.length===0?void 0:Object.fromEntries(entries)}function blockedModels(now,...sources){let until=new Map;for(let blocks of sources)for(let[model,block]of Object.entries(pruneModelBlocks(blocks,now)??{}))until.set(model,Math.max(until.get(model)??0,block.blockedUntil));return until.size===0?{}:{blockedModels:[...until].map(([model,at])=>({model,until:at}))}}async function getCredentialAccounts(storage,provider,env=process.env,repository,activeName){let accounts=await summarizeCredentialAccounts(provider,storage.get(provider),env,repository??credentialPoolRepository(storage));return normalizeProviderId(provider)!=="chatgpt-subscription"?accounts:accounts.map(account=>account.name===activeName&&!account.blocked&&!account.signedOut&&!account.unused?{...account,active:!0}:account)}async function summarizeCredentialAccounts(provider,stored,env=process.env,repository=new CredentialSlotRepository){let credential=pooledFrom(stored);return applyAccountOrder(credential?.order,await summarizeInStoredOrder(provider,credential,env,repository))}async function summarizeInStoredOrder(provider,credential,env,repository){let now=Date.now(),pinned=pinnedName(credential),summaries=[];if(credential){let state2=await repository.listSlots(provider,"stored"),isClaudeSubscription=normalizeProviderId(provider)==="anthropic-subscription",storedAccounts=isClaudeSubscription?Array.isArray(credential.accounts)?listSlots(credential).filter(isListedStoredSlot):[]:listSlots(credential),usable=new Set(slotsOfOwnKind(credential).map(slot=>slot.name));for(let slot of storedAccounts){let displayName=accountDisplayName(slot.displayName),persisted=state2[slot.name],revisions=await repository.storedSlotRevisions(provider,slot.name,{key:slot.key,access:slot.access,refresh:slot.refresh}),applicable=applicableStoredState(persisted,revisions);summaries.push({name:slot.name,...normalizeProviderId(provider)==="chatgpt-subscription"&&credential.type==="oauth"?{route:slot.route==="siwc"?"siwc":"legacy",...slot.route==="siwc"&&typeof slot.planUsageEnabled=="boolean"?{planUsageEnabled:slot.planUsageEnabled}:{},...slot.signedOut===!0?{signedOut:!0}:{}}:{},...displayName===void 0?{}:{displayName},source:slot.source??"login",...slotBlocked(provider,slot,applicable,now),pinned:pinned===slot.name,...blockedModels(now,applicable?.modelBlocks,storedModelBlocks(slot)),...usable.has(slot.name)?{}:{unused:!0},...isClaudeSubscription?claudeCliSlotFields(slot):{}})}if(normalizeProviderId(provider)!=="anthropic-subscription")return summaries}let state=await repository.listSlots(provider,"env");for(let slot of discoverEnvSlots(provider,name=>env[name])){let persisted=state[slot.name],revision=await repository.envCredentialRevision(slot.envVarName,slot.key),applicable=persisted?.credentialRevision===revision?persisted:void 0;summaries.push({name:slot.name,source:"env",...sidecarBlock(applicable,now),pinned:pinned===slot.name,...blockedModels(now,applicable?.modelBlocks)})}return summaries}async function renameCredentialAccount(storage,provider,name,displayName){await storage.modify(provider,async current=>{if(!current)throw new Error(`No stored credential for provider: ${provider}`);if(current.type==="oauth"&&!Array.isArray(current.accounts)&&current.access===current.refresh&&current.access.endsWith("-managed"))throw new Error(`Stored provider account not found: ${name}`);return renameSlotDisplayName(current,name,displayName)}),emitProviderAccountsChanged(provider)}async function pinCredentialAccount(storage,provider,name,env=process.env,repository){let repo=repository??credentialPoolRepository(storage);if(name!==null){assertValidAccountName2(name);let account=(await getCredentialAccounts(storage,provider,env,repo)).find(candidate=>candidate.name===name);if(!account)throw new Error(`Provider account not found: ${name}`);if(account.unused)throw new Error(`Account ${name} holds a login of the other kind and is never used, so it cannot be pinned. To switch ${provider} to it, save it again with /login.`)}await storage.modify(provider,async current=>{if(current===void 0){if(normalizeProviderId(provider)!=="anthropic-subscription"||name===null)throw new Error(`No stored credential for provider: ${provider}`);return pinSlot({type:"oauth",...SENTINEL_OAUTH_FIELDS,accounts:[]},name)}if(name===null){if(pinnedName(current)===void 0)return current;let{pinned:_pinned,...unpinned}={...current,pinned:void 0};return unpinned}return pinSlot(current,name)}),emitProviderAccountsChanged(provider)}async function removeCredentialAccount(storage,provider,name,env=process.env,repository){let repo=repository??credentialPoolRepository(storage),account=(await getCredentialAccounts(storage,provider,env,repo)).find(candidate=>candidate.name===name);if(!account)throw new Error(`Provider account not found: ${name}`);if(account.source==="env")throw new Error(`Environment provider account cannot be removed: ${name}`);let notice=await signOutAndDropSlot(storage,provider,name,env,repo);return emitProviderAccountsChanged(provider),notice===void 0?{}:{notice}}async function dropStoredSlot(storage,provider,name,repo){let removed=removeSlot(await storage.read(provider),name),remaining=removed===void 0?void 0:withoutOrderedAccount(removed,name);remaining===void 0?await storage.delete(provider):await storage.modify(provider,async()=>remaining),await repo.mutateSlotState(provider,"stored",name,()=>{})}async function pathExists(path){try{return await lstat2(path),!0}catch{return!1}}async function signOutAndDropSlot(storage,provider,name,env,repo,signal){let credential=await storage.read(provider);if(credential===void 0)throw new Error(`No stored credential for provider: ${provider}`);let notice;if(normalizeProviderId(provider)==="anthropic-subscription"){let accountDir=claudeCliAccountDir(storage,credential,name),dirExisted=accountDir!==void 0&&await pathExists(accountDir);try{notice=await signOutClaudeCliSlot(storage,credential,name,env,signal)}catch(error){throw dirExisted&&!await pathExists(accountDir)&&await dropStoredSlot(storage,provider,name,repo),error}}return await dropStoredSlot(storage,provider,name,repo),notice}async function signOutClaudeCliSlotsForLogout(storage,provider,env=process.env,signal,slotName){if(normalizeProviderId(provider)!=="anthropic-subscription")return[];let credential=await storage.read(provider);if(credential===void 0)return[];let repo=credentialPoolRepository(storage),notices=[],dropped=!1;try{for(let slot of listSlots(credential)){if(stringField2(slot,"store")!=="claude-cli"||slotName!==void 0&&slot.name!==slotName)continue;signal?.throwIfAborted();let notice=await signOutAndDropSlot(storage,provider,slot.name,env,repo,signal);dropped=!0,notice!==void 0&&notices.push(notice)}}finally{dropped&&emitProviderAccountsChanged(provider)}return notices}function claudeCliAgentDir(storage){let authPath=storage.getStoragePath();return authPath?dirname3(authPath):getAgentDir()}function claudeCliAccountDir(storage,credential,name){let slot=listSlots(credential).find(candidate=>candidate.name===name);if(slot===void 0||stringField2(slot,"store")!=="claude-cli")return;let dirId=stringField2(slot,"dirId");return dirId!==void 0&&isValidAccountDirId(dirId)?accountDirFor(claudeCliAgentDir(storage),dirId):void 0}async function signOutClaudeCliSlot(storage,credential,name,env,signal){let slot=listSlots(credential).find(candidate=>candidate.name===name);if(slot===void 0||stringField2(slot,"store")!=="claude-cli")return;let dirId=stringField2(slot,"dirId"),agentDir=claudeCliAgentDir(storage);if(dirId===void 0||!isValidAccountDirId(dirId))return`Removed Claude account ${name} without a Claude sign-out: it names no valid account dir.`;let executable;try{executable=resolveClaudeCodeExecutable({...defaultExecutableDeps(),env:key=>env[key]})}catch{executable=void 0}let outcome=await removeAccountDir({agentDir,dirId,executable,parentEnv:env,...signal===void 0?{}:{signal}});if(outcome!=="removed")return outcome==="removed_without_sign_out"?`Removed Claude account ${name}, but the Claude CLI sign-out could not run; its stored sign-in may remain in the Claude CLI's credential store.`:`Removed Claude account ${name} without a Claude sign-out: its account dir is a link or a file, left untouched at ${accountDirFor(agentDir,dirId)}.`}export{isEnvSlot,SENTINEL_OAUTH_FIELDS,emptyCredential,isListedStoredSlot,unusableStoredSlotCount,listAccounts,assertValidAccountName,pinAccount,envSlotToken,hasRequestOauthToken,mergeRequestAuthEnvironment,stripManagedAuthEnvironment,buildClaudeCliEnvironment,spawnClaudeCli,stopClaudeCli,readClaudeCliAuthStatus,logoutClaudeCli,CLAUDE_CLI_SHARED_LINKS,newAccountDirId,isValidAccountDirId,accountDirFor,readClaudeCliAccessToken,claudeCliSharedRoot,ensureAccountDir,removeAccountDir,AllAccountsBlockedError,isBlockedFor,clearExpiredBlocks,selectAccount,resolveClaudeCodeExecutable,resolveClaudeCodeRun,defaultExecutableDeps,accountCanServe,assertValidAccountName2,selectedOAuthAccount,credentialPoolRepository,getCredentialAccounts,summarizeCredentialAccounts,renameCredentialAccount,pinCredentialAccount,removeCredentialAccount,signOutClaudeCliSlotsForLogout};
@@ -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{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import{appendDebugLogEntry}from"./chunk-MSDBBOB2.js";import{__toESM}from"./chunk-IKOFCODM.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHash}from"node:crypto";import{basename}from"node:path";var FileLockLostError=class extends Error{constructor(path,cause){super(`File lock on ${basename(path)} was lost before the write committed: the lock was removed or reclaimed by another process. The write was skipped.`,{cause}),this.code="ELOCKLOST",this.name="FileLockLostError",this.path=path}};function lockLogFields(path){return{lock:basename(path),lockId:createHash("sha256").update(path).digest("hex").slice(0,12)}}function logLockEvent(header,fields){try{appendDebugLogEntry(header,JSON.stringify(fields))}catch{}}async function lockWithLossHandling(path,options={}){let{onLost,...lockOptions}=options,released=!1,lostError,releaseLock=await import_proper_lockfile.default.lock(path,{...lockOptions,onCompromised:error=>{if(released||lostError!==void 0)return;lostError=error;let fields=lockLogFields(lockOptions.lockfilePath??`${path}.lock`);logLockEvent("file lock lost while held",{event:"file_lock_lost",...fields,code:error.code});try{onLost?.(error)}catch(callbackError){logLockEvent("file lock onLost callback threw",{event:"file_lock_on_lost_threw",...fields,name:callbackError instanceof Error?callbackError.name:typeof callbackError,code:callbackError?.code})}}});return{release:async()=>{released||(released=!0,lostError===void 0&&await releaseLock())},lost:()=>lostError!==void 0,assertHeld:()=>{if(lostError!==void 0)throw new FileLockLostError(path,lostError)}}}export{lockWithLossHandling};
2
+ import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import{appendDebugLogEntry}from"./chunk-5H43O4MA.js";import{__toESM}from"./chunk-IKOFCODM.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHash}from"node:crypto";import{basename}from"node:path";var FileLockLostError=class extends Error{constructor(path,cause){super(`File lock on ${basename(path)} was lost before the write committed: the lock was removed or reclaimed by another process. The write was skipped.`,{cause}),this.code="ELOCKLOST",this.name="FileLockLostError",this.path=path}};function lockLogFields(path){return{lock:basename(path),lockId:createHash("sha256").update(path).digest("hex").slice(0,12)}}function logLockEvent(header,fields){try{appendDebugLogEntry(header,JSON.stringify(fields))}catch{}}async function lockWithLossHandling(path,options={}){let{onLost,...lockOptions}=options,released=!1,lostError,releaseLock=await import_proper_lockfile.default.lock(path,{...lockOptions,onCompromised:error=>{if(released||lostError!==void 0)return;lostError=error;let fields=lockLogFields(lockOptions.lockfilePath??`${path}.lock`);logLockEvent("file lock lost while held",{event:"file_lock_lost",...fields,code:error.code});try{onLost?.(error)}catch(callbackError){logLockEvent("file lock onLost callback threw",{event:"file_lock_on_lost_threw",...fields,name:callbackError instanceof Error?callbackError.name:typeof callbackError,code:callbackError?.code})}}});return{release:async()=>{released||(released=!0,lostError===void 0&&await releaseLock())},lost:()=>lostError!==void 0,assertHeld:()=>{if(lostError!==void 0)throw new FileLockLostError(path,lostError)}}}export{lockWithLossHandling};