@iaforged/context-code 2.1.7 → 2.1.8

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 (408) hide show
  1. package/dist/src/Task.js +1 -1
  2. package/dist/src/constants/oauth.js +1 -1
  3. package/dist/src/context/mailbox.js +1 -1
  4. package/dist/src/context/voice.js +1 -1
  5. package/dist/src/hooks/useTerminalSize.js +1 -1
  6. package/dist/src/ink/Ansi.js +1 -1
  7. package/dist/src/ink/clearTerminal.js +1 -1
  8. package/dist/src/ink/colorize.js +1 -1
  9. package/dist/src/ink/components/App.js +1 -1
  10. package/dist/src/ink/components/Button.js +1 -1
  11. package/dist/src/ink/components/ClockContext.js +1 -1
  12. package/dist/src/ink/components/CursorDeclarationContext.js +1 -1
  13. package/dist/src/ink/components/Link.js +1 -1
  14. package/dist/src/ink/components/StdinContext.js +1 -1
  15. package/dist/src/ink/components/TerminalFocusContext.js +1 -1
  16. package/dist/src/ink/dom.js +1 -1
  17. package/dist/src/ink/events/keyboard-event.js +1 -1
  18. package/dist/src/ink/hit-test.js +1 -1
  19. package/dist/src/ink/hooks/use-animation-frame.js +1 -1
  20. package/dist/src/ink/hooks/use-app.js +1 -1
  21. package/dist/src/ink/hooks/use-input.js +1 -1
  22. package/dist/src/ink/hooks/use-interval.js +1 -1
  23. package/dist/src/ink/hooks/use-selection.js +1 -1
  24. package/dist/src/ink/hooks/use-tab-status.js +1 -1
  25. package/dist/src/ink/hooks/use-terminal-focus.js +1 -1
  26. package/dist/src/ink/hooks/use-terminal-title.js +1 -1
  27. package/dist/src/ink/hooks/use-terminal-viewport.js +1 -1
  28. package/dist/src/ink/ink.js +1 -1
  29. package/dist/src/ink/layout/yoga.js +1 -1
  30. package/dist/src/ink/line-width-cache.js +1 -1
  31. package/dist/src/ink/log-update.js +1 -1
  32. package/dist/src/ink/measure-text.js +1 -1
  33. package/dist/src/ink/output.js +1 -1
  34. package/dist/src/ink/parse-keypress.js +1 -1
  35. package/dist/src/ink/reconciler.js +1 -1
  36. package/dist/src/ink/render-border.js +1 -1
  37. package/dist/src/ink/render-node-to-output.js +1 -1
  38. package/dist/src/ink/render-to-screen.js +1 -1
  39. package/dist/src/ink/renderer.js +1 -1
  40. package/dist/src/ink/root.js +1 -1
  41. package/dist/src/ink/screen.js +1 -1
  42. package/dist/src/ink/searchHighlight.js +1 -1
  43. package/dist/src/ink/selection.js +1 -1
  44. package/dist/src/ink/squash-text-nodes.js +1 -1
  45. package/dist/src/ink/stringWidth.js +1 -1
  46. package/dist/src/ink/tabstops.js +1 -1
  47. package/dist/src/ink/terminal.js +1 -1
  48. package/dist/src/ink/termio/osc.js +1 -1
  49. package/dist/src/ink/termio/parser.js +1 -1
  50. package/dist/src/ink/termio/tokenize.js +1 -1
  51. package/dist/src/ink/useTerminalNotification.js +1 -1
  52. package/dist/src/ink/warn.js +1 -1
  53. package/dist/src/ink/widest-line.js +1 -1
  54. package/dist/src/ink/wrap-text.js +1 -1
  55. package/dist/src/ink/wrapAnsi.js +1 -1
  56. package/dist/src/native-ts/yoga-layout/index.js +1 -1
  57. package/dist/src/schemas/hooks.js +1 -1
  58. package/dist/src/services/SessionMemory/sessionMemoryUtils.js +1 -1
  59. package/dist/src/services/api/client.js +1 -1
  60. package/dist/src/services/api/dumpPrompts.js +1 -1
  61. package/dist/src/services/api/errorUtils.js +1 -1
  62. package/dist/src/services/api/promptCacheBreakDetection.js +1 -1
  63. package/dist/src/services/api/withRetry.js +1 -1
  64. package/dist/src/services/autoDream/consolidationLock.js +1 -1
  65. package/dist/src/services/mcp/elicitationHandler.js +1 -1
  66. package/dist/src/services/mcp/mcpStringUtils.js +1 -1
  67. package/dist/src/services/mcp/oauthPort.js +1 -1
  68. package/dist/src/services/mcp/vscodeSdkMcp.js +1 -1
  69. package/dist/src/services/oauth/client.js +1 -1
  70. package/dist/src/services/oauth/getOauthProfile.js +1 -1
  71. package/dist/src/services/objetivo/types.js +1 -1
  72. package/dist/src/services/rateLimitMocking.js +1 -1
  73. package/dist/src/services/remoteManagedSettings/syncCacheState.js +1 -1
  74. package/dist/src/skills/bundledSkills.js +1 -1
  75. package/dist/src/tasks/DreamTask/DreamTask.js +1 -1
  76. package/dist/src/tools/AgentTool/agentMemory.js +1 -1
  77. package/dist/src/tools/AgentTool/forkSubagent.js +1 -1
  78. package/dist/src/tools/BashTool/BashToolResultMessage.js +1 -1
  79. package/dist/src/tools/BashTool/UI.js +1 -1
  80. package/dist/src/tools/BashTool/sedEditParser.js +1 -1
  81. package/dist/src/tools/BashTool/utils.js +1 -1
  82. package/dist/src/tools/FileReadTool/imageProcessor.js +1 -1
  83. package/dist/src/tools/FileReadTool/prompt.js +1 -1
  84. package/dist/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +1 -1
  85. package/dist/src/tools/ListMcpResourcesTool/UI.js +1 -1
  86. package/dist/src/tools/MCPTool/MCPTool.js +1 -1
  87. package/dist/src/tools/MCPTool/UI.js +1 -1
  88. package/dist/src/tools/McpAuthTool/McpAuthTool.js +1 -1
  89. package/dist/src/tools/NotebookEditTool/prompt.js +1 -1
  90. package/dist/src/tools/PowerShellTool/PowerShellTool.js +1 -1
  91. package/dist/src/tools/PowerShellTool/UI.js +1 -1
  92. package/dist/src/tools/PowerShellTool/gitSafety.js +1 -1
  93. package/dist/src/tools/PowerShellTool/modeValidation.js +1 -1
  94. package/dist/src/tools/PowerShellTool/pathValidation.js +1 -1
  95. package/dist/src/tools/PowerShellTool/powershellPermissions.js +1 -1
  96. package/dist/src/tools/PowerShellTool/powershellSecurity.js +1 -1
  97. package/dist/src/tools/PowerShellTool/prompt.js +1 -1
  98. package/dist/src/tools/PowerShellTool/readOnlyValidation.js +1 -1
  99. package/dist/src/tools/REPLTool/constants.js +1 -1
  100. package/dist/src/tools/REPLTool/primitiveTools.js +1 -1
  101. package/dist/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +1 -1
  102. package/dist/src/tools/ReadMcpResourceTool/UI.js +1 -1
  103. package/dist/src/tools/ScheduleCronTool/prompt.js +1 -1
  104. package/dist/src/tools/SkillTool/prompt.js +1 -1
  105. package/dist/src/tools/TodoWriteTool/TodoWriteTool.js +1 -1
  106. package/dist/src/tools/ToolSearchTool/prompt.js +1 -1
  107. package/dist/src/tools/WebSearchTool/prompt.js +1 -1
  108. package/dist/src/tools/shared/gitOperationTracking.js +1 -1
  109. package/dist/src/types/permissions.js +1 -1
  110. package/dist/src/utils/Cursor.js +1 -1
  111. package/dist/src/utils/QueryGuard.js +1 -1
  112. package/dist/src/utils/Shell.js +1 -1
  113. package/dist/src/utils/ShellCommand.js +1 -1
  114. package/dist/src/utils/activityManager.js +1 -1
  115. package/dist/src/utils/advisor.js +1 -1
  116. package/dist/src/utils/appleTerminalBackup.js +1 -1
  117. package/dist/src/utils/argumentSubstitution.js +1 -1
  118. package/dist/src/utils/authFileDescriptor.js +1 -1
  119. package/dist/src/utils/autoUpdater.js +1 -1
  120. package/dist/src/utils/background/remote/preconditions.js +1 -1
  121. package/dist/src/utils/background/remote/remoteSession.js +1 -1
  122. package/dist/src/utils/bash/ShellSnapshot.js +1 -1
  123. package/dist/src/utils/bash/ast.js +1 -1
  124. package/dist/src/utils/bash/bashParser.js +1 -1
  125. package/dist/src/utils/bash/bashPipeCommand.js +1 -1
  126. package/dist/src/utils/bash/parser.js +1 -1
  127. package/dist/src/utils/bash/shellQuote.js +1 -1
  128. package/dist/src/utils/bash/shellQuoting.js +1 -1
  129. package/dist/src/utils/billing.js +1 -1
  130. package/dist/src/utils/caCerts.js +1 -1
  131. package/dist/src/utils/claudeInChrome/common.js +1 -1
  132. package/dist/src/utils/claudeInChrome/setupPortable.js +1 -1
  133. package/dist/src/utils/claudemd.js +1 -1
  134. package/dist/src/utils/collapseBackgroundBashNotifications.js +1 -1
  135. package/dist/src/utils/collapseReadSearch.js +1 -1
  136. package/dist/src/utils/completionCache.js +1 -1
  137. package/dist/src/utils/computerUse/common.js +1 -1
  138. package/dist/src/utils/concurrentSessions.js +1 -1
  139. package/dist/src/utils/context.js +1 -1
  140. package/dist/src/utils/cron.js +1 -1
  141. package/dist/src/utils/cronTasks.js +1 -1
  142. package/dist/src/utils/cwd.js +1 -1
  143. package/dist/src/utils/debug.js +1 -1
  144. package/dist/src/utils/debugFilter.js +1 -1
  145. package/dist/src/utils/detectRepository.js +1 -1
  146. package/dist/src/utils/diagLogs.js +1 -1
  147. package/dist/src/utils/diff.js +1 -1
  148. package/dist/src/utils/directMemberMessage.js +1 -1
  149. package/dist/src/utils/doctorDiagnostic.js +1 -1
  150. package/dist/src/utils/dxt/helpers.js +1 -1
  151. package/dist/src/utils/dxt/zip.js +1 -1
  152. package/dist/src/utils/earlyInput.js +1 -1
  153. package/dist/src/utils/editor.js +1 -1
  154. package/dist/src/utils/effort.js +1 -1
  155. package/dist/src/utils/embeddedTools.js +1 -1
  156. package/dist/src/utils/envDynamic.js +1 -1
  157. package/dist/src/utils/envUtils.js +1 -1
  158. package/dist/src/utils/execFileNoThrowPortable.js +1 -1
  159. package/dist/src/utils/execSyncWrapper.js +1 -1
  160. package/dist/src/utils/exportRenderer.js +1 -1
  161. package/dist/src/utils/extraUsage.js +1 -1
  162. package/dist/src/utils/fastMode.js +1 -1
  163. package/dist/src/utils/fileOperationAnalytics.js +1 -1
  164. package/dist/src/utils/fileRead.js +1 -1
  165. package/dist/src/utils/findExecutable.js +1 -1
  166. package/dist/src/utils/format.js +1 -1
  167. package/dist/src/utils/frontmatterParser.js +1 -1
  168. package/dist/src/utils/fsOperations.js +1 -1
  169. package/dist/src/utils/fullscreen.js +1 -1
  170. package/dist/src/utils/genericProcessUtils.js +1 -1
  171. package/dist/src/utils/getWorktreePaths.js +1 -1
  172. package/dist/src/utils/git/gitConfigParser.js +1 -1
  173. package/dist/src/utils/git/gitFilesystem.js +1 -1
  174. package/dist/src/utils/git/gitignore.js +1 -1
  175. package/dist/src/utils/gitDiff.js +1 -1
  176. package/dist/src/utils/gitSettings.js +1 -1
  177. package/dist/src/utils/glob.js +1 -1
  178. package/dist/src/utils/gracefulShutdown.js +1 -1
  179. package/dist/src/utils/groupToolUses.js +1 -1
  180. package/dist/src/utils/handlePromptSubmit.js +1 -1
  181. package/dist/src/utils/hash.js +1 -1
  182. package/dist/src/utils/hooks/fileChangedWatcher.js +1 -1
  183. package/dist/src/utils/hooks/hooksSettings.js +1 -1
  184. package/dist/src/utils/hooks/registerSkillHooks.js +1 -1
  185. package/dist/src/utils/hooks/sessionHooks.js +1 -1
  186. package/dist/src/utils/http.js +1 -1
  187. package/dist/src/utils/hyperlink.js +1 -1
  188. package/dist/src/utils/ide.js +1 -1
  189. package/dist/src/utils/idePathConversion.js +1 -1
  190. package/dist/src/utils/imagePaste.js +1 -1
  191. package/dist/src/utils/imageResizer.js +1 -1
  192. package/dist/src/utils/imageStore.js +1 -1
  193. package/dist/src/utils/inProcessTeammateHelpers.js +1 -1
  194. package/dist/src/utils/ink.js +1 -1
  195. package/dist/src/utils/jetbrains.js +1 -1
  196. package/dist/src/utils/json.js +1 -1
  197. package/dist/src/utils/listSessionsImpl.js +1 -1
  198. package/dist/src/utils/localInstaller.js +1 -1
  199. package/dist/src/utils/lockfile.js +1 -1
  200. package/dist/src/utils/logoV2Utils.js +1 -1
  201. package/dist/src/utils/markdown.js +1 -1
  202. package/dist/src/utils/mcp/dateTimeParser.js +1 -1
  203. package/dist/src/utils/mcpOutputStorage.js +1 -1
  204. package/dist/src/utils/mcpValidation.js +1 -1
  205. package/dist/src/utils/memoize.js +1 -1
  206. package/dist/src/utils/memory/types.js +1 -1
  207. package/dist/src/utils/memoryFileDetection.js +1 -1
  208. package/dist/src/utils/messageQueueManager.js +1 -1
  209. package/dist/src/utils/messages/mappers.js +1 -1
  210. package/dist/src/utils/messages/systemInit.js +1 -1
  211. package/dist/src/utils/model/antModels.js +1 -1
  212. package/dist/src/utils/model/check1mAccess.js +1 -1
  213. package/dist/src/utils/model/contextWindowUpgradeCheck.js +1 -1
  214. package/dist/src/utils/model/model.js +1 -1
  215. package/dist/src/utils/model/modelAllowlist.js +1 -1
  216. package/dist/src/utils/model/modelCapabilities.js +1 -1
  217. package/dist/src/utils/model/modelOptions.js +1 -1
  218. package/dist/src/utils/model/modelStrings.js +1 -1
  219. package/dist/src/utils/model/providerModels.js +1 -1
  220. package/dist/src/utils/model/providerProfiles.js +1 -1
  221. package/dist/src/utils/model/providerProfilesDb.js +1 -1
  222. package/dist/src/utils/model/providerSwitch.js +1 -1
  223. package/dist/src/utils/model/providers.js +1 -1
  224. package/dist/src/utils/modelCost.js +1 -1
  225. package/dist/src/utils/modifiers.js +1 -1
  226. package/dist/src/utils/mtls.js +1 -1
  227. package/dist/src/utils/nativeInstaller/download.js +1 -1
  228. package/dist/src/utils/nativeInstaller/installer.js +1 -1
  229. package/dist/src/utils/nativeInstaller/packageManagers.js +1 -1
  230. package/dist/src/utils/nativeInstaller/pidLock.js +1 -1
  231. package/dist/src/utils/notebook.js +1 -1
  232. package/dist/src/utils/pasteStore.js +1 -1
  233. package/dist/src/utils/path.js +1 -1
  234. package/dist/src/utils/permissions/PermissionMode.js +1 -1
  235. package/dist/src/utils/permissions/PermissionPromptToolResultSchema.js +1 -1
  236. package/dist/src/utils/permissions/PermissionUpdate.js +1 -1
  237. package/dist/src/utils/permissions/PermissionUpdateSchema.js +1 -1
  238. package/dist/src/utils/permissions/autoModeState.js +1 -1
  239. package/dist/src/utils/permissions/bypassPermissionsKillswitch.js +1 -1
  240. package/dist/src/utils/permissions/filesystem.js +1 -1
  241. package/dist/src/utils/permissions/getNextPermissionMode.js +1 -1
  242. package/dist/src/utils/permissions/pathValidation.js +1 -1
  243. package/dist/src/utils/permissions/permissionRuleParser.js +1 -1
  244. package/dist/src/utils/permissions/permissionsDb.js +1 -1
  245. package/dist/src/utils/permissions/permissionsLoader.js +1 -1
  246. package/dist/src/utils/permissions/shellRuleMatching.js +1 -1
  247. package/dist/src/utils/planModeV2.js +1 -1
  248. package/dist/src/utils/plans.js +1 -1
  249. package/dist/src/utils/platform.js +1 -1
  250. package/dist/src/utils/plugins/addDirPluginSettings.js +1 -1
  251. package/dist/src/utils/plugins/cacheUtils.js +1 -1
  252. package/dist/src/utils/plugins/dependencyResolver.js +1 -1
  253. package/dist/src/utils/plugins/fetchTelemetry.js +1 -1
  254. package/dist/src/utils/plugins/gitAvailability.js +1 -1
  255. package/dist/src/utils/plugins/hintRecommendation.js +1 -1
  256. package/dist/src/utils/plugins/installedPluginsManager.js +1 -1
  257. package/dist/src/utils/plugins/loadPluginAgents.js +1 -1
  258. package/dist/src/utils/plugins/loadPluginCommands.js +1 -1
  259. package/dist/src/utils/plugins/loadPluginHooks.js +1 -1
  260. package/dist/src/utils/plugins/loadPluginOutputStyles.js +1 -1
  261. package/dist/src/utils/plugins/lspPluginIntegration.js +1 -1
  262. package/dist/src/utils/plugins/lspRecommendation.js +1 -1
  263. package/dist/src/utils/plugins/managedPlugins.js +1 -1
  264. package/dist/src/utils/plugins/marketplaceHelpers.js +1 -1
  265. package/dist/src/utils/plugins/marketplaceManager.js +1 -1
  266. package/dist/src/utils/plugins/mcpPluginIntegration.js +1 -1
  267. package/dist/src/utils/plugins/mcpbHandler.js +1 -1
  268. package/dist/src/utils/plugins/officialMarketplaceGcs.js +1 -1
  269. package/dist/src/utils/plugins/officialMarketplaceStartupCheck.js +1 -1
  270. package/dist/src/utils/plugins/orphanedPluginFilter.js +1 -1
  271. package/dist/src/utils/plugins/performStartupChecks.js +1 -1
  272. package/dist/src/utils/plugins/pluginAutoupdate.js +1 -1
  273. package/dist/src/utils/plugins/pluginBlocklist.js +1 -1
  274. package/dist/src/utils/plugins/pluginDirectories.js +1 -1
  275. package/dist/src/utils/plugins/pluginFlagging.js +1 -1
  276. package/dist/src/utils/plugins/pluginInstallationHelpers.js +1 -1
  277. package/dist/src/utils/plugins/pluginLoader.js +1 -1
  278. package/dist/src/utils/plugins/pluginOptionsStorage.js +1 -1
  279. package/dist/src/utils/plugins/pluginPolicy.js +1 -1
  280. package/dist/src/utils/plugins/pluginStartupCheck.js +1 -1
  281. package/dist/src/utils/plugins/pluginVersioning.js +1 -1
  282. package/dist/src/utils/plugins/reconciler.js +1 -1
  283. package/dist/src/utils/plugins/refresh.js +1 -1
  284. package/dist/src/utils/plugins/schemas.js +1 -1
  285. package/dist/src/utils/plugins/walkPluginMarkdown.js +1 -1
  286. package/dist/src/utils/plugins/zipCache.js +1 -1
  287. package/dist/src/utils/powershell/parser.js +1 -1
  288. package/dist/src/utils/processUserInput/processBashCommand.js +1 -1
  289. package/dist/src/utils/processUserInput/processSlashCommand.js +1 -1
  290. package/dist/src/utils/processUserInput/processTextPrompt.js +1 -1
  291. package/dist/src/utils/processUserInput/processUserInput.js +1 -1
  292. package/dist/src/utils/profilerBase.js +1 -1
  293. package/dist/src/utils/promptCategory.js +1 -1
  294. package/dist/src/utils/promptEditor.js +1 -1
  295. package/dist/src/utils/promptShellExecution.js +1 -1
  296. package/dist/src/utils/proxy.js +1 -1
  297. package/dist/src/utils/queryHelpers.js +1 -1
  298. package/dist/src/utils/queryProfiler.js +1 -1
  299. package/dist/src/utils/queueProcessor.js +1 -1
  300. package/dist/src/utils/readFileInRange.js +1 -1
  301. package/dist/src/utils/releaseNotes.js +1 -1
  302. package/dist/src/utils/renderOptions.js +1 -1
  303. package/dist/src/utils/ripgrep.js +1 -1
  304. package/dist/src/utils/sandbox/sandbox-adapter.js +1 -1
  305. package/dist/src/utils/sdkEventQueue.js +1 -1
  306. package/dist/src/utils/secureStorage/index.js +1 -1
  307. package/dist/src/utils/secureStorage/macOsKeychainHelpers.js +1 -1
  308. package/dist/src/utils/secureStorage/macOsKeychainStorage.js +1 -1
  309. package/dist/src/utils/secureStorage/plainTextStorage.js +1 -1
  310. package/dist/src/utils/secureStorage/sqliteStorage.js +1 -1
  311. package/dist/src/utils/sessionEnvironment.js +1 -1
  312. package/dist/src/utils/sessionIngressAuth.js +1 -1
  313. package/dist/src/utils/sessionRestore.js +1 -1
  314. package/dist/src/utils/sessionStart.js +1 -1
  315. package/dist/src/utils/sessionTitle.js +1 -1
  316. package/dist/src/utils/settings/managedPath.js +1 -1
  317. package/dist/src/utils/settings/mdm/rawRead.js +1 -1
  318. package/dist/src/utils/settings/mdm/settings.js +1 -1
  319. package/dist/src/utils/settings/permissionValidation.js +1 -1
  320. package/dist/src/utils/settings/pluginOnlyPolicy.js +1 -1
  321. package/dist/src/utils/settings/schemaOutput.js +1 -1
  322. package/dist/src/utils/settings/settings.js +1 -1
  323. package/dist/src/utils/settings/types.js +1 -1
  324. package/dist/src/utils/settings/validateEditTool.js +1 -1
  325. package/dist/src/utils/settings/validation.js +1 -1
  326. package/dist/src/utils/shell/bashProvider.js +1 -1
  327. package/dist/src/utils/shell/powershellDetection.js +1 -1
  328. package/dist/src/utils/shell/powershellProvider.js +1 -1
  329. package/dist/src/utils/shell/readOnlyCommandValidation.js +1 -1
  330. package/dist/src/utils/shell/resolveDefaultShell.js +1 -1
  331. package/dist/src/utils/shell/shellToolUtils.js +1 -1
  332. package/dist/src/utils/shell/specPrefix.js +1 -1
  333. package/dist/src/utils/shellConfig.js +1 -1
  334. package/dist/src/utils/sideQuestion.js +1 -1
  335. package/dist/src/utils/skills/skillChangeDetector.js +1 -1
  336. package/dist/src/utils/slashCommandParsing.js +1 -1
  337. package/dist/src/utils/sliceAnsi.js +1 -1
  338. package/dist/src/utils/slowOperations.js +1 -1
  339. package/dist/src/utils/standaloneAgent.js +1 -1
  340. package/dist/src/utils/startupProfiler.js +1 -1
  341. package/dist/src/utils/staticRender.js +1 -1
  342. package/dist/src/utils/status.js +1 -1
  343. package/dist/src/utils/statusNoticeDefinitions.js +1 -1
  344. package/dist/src/utils/suggestions/commandSuggestions.js +1 -1
  345. package/dist/src/utils/suggestions/directoryCompletion.js +1 -1
  346. package/dist/src/utils/suggestions/shellHistoryCompletion.js +1 -1
  347. package/dist/src/utils/suggestions/skillUsageTracking.js +1 -1
  348. package/dist/src/utils/suggestions/slackChannelSuggestions.js +1 -1
  349. package/dist/src/utils/swarm/backends/detection.js +1 -1
  350. package/dist/src/utils/swarm/permissionSync.js +1 -1
  351. package/dist/src/utils/swarm/reconnection.js +1 -1
  352. package/dist/src/utils/swarm/spawnUtils.js +1 -91
  353. package/dist/src/utils/swarm/teammateInit.js +1 -1
  354. package/dist/src/utils/systemDirectories.js +1 -1
  355. package/dist/src/utils/systemPrompt.js +1 -1
  356. package/dist/src/utils/systemTheme.js +1 -1
  357. package/dist/src/utils/task/TaskOutput.js +1 -1
  358. package/dist/src/utils/task/diskOutput.js +1 -1
  359. package/dist/src/utils/tasks.js +1 -1
  360. package/dist/src/utils/teamDiscovery.js +1 -1
  361. package/dist/src/utils/teamMemoryOps.js +1 -1
  362. package/dist/src/utils/teammateMailbox.js +1 -1
  363. package/dist/src/utils/telemetry/betaSessionTracing.js +1 -1
  364. package/dist/src/utils/telemetry/bigqueryExporter.js +1 -1
  365. package/dist/src/utils/telemetry/events.js +1 -1
  366. package/dist/src/utils/telemetry/instrumentation.js +1 -1
  367. package/dist/src/utils/telemetry/logger.js +1 -1
  368. package/dist/src/utils/telemetry/perfettoTracing.js +1 -1
  369. package/dist/src/utils/telemetry/pluginTelemetry.js +1 -1
  370. package/dist/src/utils/telemetry/sessionTracing.js +1 -1
  371. package/dist/src/utils/telemetryAttributes.js +1 -1
  372. package/dist/src/utils/teleport/api.js +1 -1
  373. package/dist/src/utils/teleport/environments.js +1 -1
  374. package/dist/src/utils/teleport/gitBundle.js +1 -1
  375. package/dist/src/utils/teleport.js +1 -1
  376. package/dist/src/utils/tempfile.js +1 -1
  377. package/dist/src/utils/terminal.js +1 -1
  378. package/dist/src/utils/terminalPanel.js +1 -1
  379. package/dist/src/utils/textHighlighting.js +1 -1
  380. package/dist/src/utils/theme.js +1 -1
  381. package/dist/src/utils/themes/bootstrap.js +1 -1
  382. package/dist/src/utils/themes/loader.js +1 -1
  383. package/dist/src/utils/thinking.js +1 -1
  384. package/dist/src/utils/tmuxSocket.js +1 -1
  385. package/dist/src/utils/tokens.js +1 -1
  386. package/dist/src/utils/toolPool.js +1 -1
  387. package/dist/src/utils/toolResultStorage.js +1 -1
  388. package/dist/src/utils/transcriptSearch.js +1 -1
  389. package/dist/src/utils/truncate.js +1 -1
  390. package/dist/src/utils/ultraplan/keyword.js +1 -1
  391. package/dist/src/utils/unaryLogging.js +1 -1
  392. package/dist/src/utils/undercover.js +1 -1
  393. package/dist/src/utils/user.js +1 -1
  394. package/dist/src/utils/userPromptKeywords.js +1 -1
  395. package/dist/src/utils/which.js +1 -1
  396. package/dist/src/utils/windowsPaths.js +1 -1
  397. package/dist/src/utils/worktree.js +1 -1
  398. package/dist/src/utils/zodToJsonSchema.js +1 -1
  399. package/dist/src/vim/operators.js +1 -1
  400. package/dist/src/vim/textObjects.js +1 -1
  401. package/dist/src/vim/transitions.js +1 -1
  402. package/dist/src/voice/voiceModeEnabled.js +1 -1
  403. package/dist/src/webapp/auth.js +1 -1
  404. package/dist/src/webapp/tunnel.js +1 -1
  405. package/dist/src/whatsapp/bridge.js +1 -1
  406. package/dist/src/whatsapp/mirror.js +1 -1
  407. package/dist/webapp/main-MTQLKGXD.js +1 -1
  408. package/package.json +1 -1
@@ -1 +1 @@
1
- import{SandboxManager as o,SandboxRuntimeConfigSchema as t,SandboxViolationStore as n}from"@anthropic-ai/sandbox-runtime";import{rmSync as e,statSync as s}from"fs";import{readFile as a}from"fs/promises";import{memoize as r}from"lodash-es";import{join as i,resolve as l,sep as d}from"path";import{getAdditionalDirectoriesForClaudeMd as c,getCwdState as u,getOriginalCwd as g}from"../../bootstrap/state.js";import{logForDebugging as m}from"../debug.js";import{expandPath as b}from"../path.js";import{getPlatform as f}from"../platform.js";import{settingsChangeDetector as x}from"../settings/changeDetector.js";import{SETTING_SOURCES as S}from"../settings/constants.js";import{getManagedSettingsDropInDir as p}from"../settings/managedPath.js";import{getInitialSettings as h,getSettings_DEPRECATED as w,getSettingsFilePathForSource as y,getSettingsForSource as P,getSettingsRootPathForSource as C,updateSettingsForSource as k}from"../settings/settings.js";import{BASH_TOOL_NAME as F}from"src/tools/BashTool/toolName.js";import{FILE_EDIT_TOOL_NAME as E}from"src/tools/FileEditTool/constants.js";import{FILE_READ_TOOL_NAME as v}from"src/tools/FileReadTool/prompt.js";import{WEB_FETCH_TOOL_NAME as R}from"src/tools/WebFetchTool/prompt.js";import{errorMessage as A}from"../errors.js";import{getClaudeTempDir as N}from"../permissions/filesystem.js";import{ripgrepCommand as W}from"../ripgrep.js";function permissionRuleValueFromString(o){const t=o.match(/^([^(]+)\(([^)]+)\)$/);if(!t)return{toolName:o};const n=t[1],e=t[2];return n&&e?{toolName:n,ruleContent:e}:{toolName:o}}export function resolvePathPatternForSandbox(o,t){if(o.startsWith("//"))return o.slice(1);if(o.startsWith("/")&&!o.startsWith("//")){const n=C(t);return l(n,o.slice(1))}return o}export function resolveSandboxFilesystemPath(o,t){return o.startsWith("//")?o.slice(1):b(o,C(t))}export function shouldAllowManagedSandboxDomainsOnly(){return!0===P("policySettings")?.sandbox?.network?.allowManagedDomainsOnly}function shouldAllowManagedReadPathsOnly(){return!0===P("policySettings")?.sandbox?.filesystem?.allowManagedReadPathsOnly}export function convertToSandboxRuntimeConfig(o){const t=o.permissions||{},n=[],e=[];if(shouldAllowManagedSandboxDomainsOnly()){const o=P("policySettings");for(const t of o?.sandbox?.network?.allowedDomains||[])n.push(t);for(const t of o?.permissions?.allow||[]){const o=permissionRuleValueFromString(t);o.toolName===R&&o.ruleContent?.startsWith("domain:")&&n.push(o.ruleContent.substring(7))}}else{for(const t of o.sandbox?.network?.allowedDomains||[])n.push(t);for(const o of t.allow||[]){const t=permissionRuleValueFromString(o);t.toolName===R&&t.ruleContent?.startsWith("domain:")&&n.push(t.ruleContent.substring(7))}}for(const o of t.deny||[]){const t=permissionRuleValueFromString(o);t.toolName===R&&t.ruleContent?.startsWith("domain:")&&e.push(t.ruleContent.substring(7))}const a=[".",N()],r=[],i=[],d=[],m=S.map(o=>y(o)).filter(o=>void 0!==o);r.push(...m),r.push(p());const b=u(),f=g();b!==f&&(r.push(l(b,".claude","settings.json")),r.push(l(b,".claude","settings.local.json"))),r.push(l(f,".claude","skills")),r.push(l(f,".context","skills")),b!==f&&(r.push(l(b,".claude","skills")),r.push(l(b,".context","skills"))),j.length=0;const x=["HEAD","objects","refs","hooks","config"];for(const o of b===f?[f]:[f,b])for(const t of x){const n=l(o,t);try{s(n),r.push(n)}catch{j.push(n)}}D&&D!==b&&a.push(D);const h=new Set([...o.permissions?.additionalDirectories||[],...c()]);a.push(...h);for(const o of S){const t=P(o);if(t?.permissions){for(const n of t.permissions.allow||[]){const t=permissionRuleValueFromString(n);t.toolName===E&&t.ruleContent&&a.push(resolvePathPatternForSandbox(t.ruleContent,o))}for(const n of t.permissions.deny||[]){const t=permissionRuleValueFromString(n);t.toolName===E&&t.ruleContent&&r.push(resolvePathPatternForSandbox(t.ruleContent,o)),t.toolName===v&&t.ruleContent&&i.push(resolvePathPatternForSandbox(t.ruleContent,o))}}const n=t?.sandbox?.filesystem;if(n){for(const t of n.allowWrite||[])a.push(resolveSandboxFilesystemPath(t,o));for(const t of n.denyWrite||[])r.push(resolveSandboxFilesystemPath(t,o));for(const t of n.denyRead||[])i.push(resolveSandboxFilesystemPath(t,o));if(!shouldAllowManagedReadPathsOnly()||"policySettings"===o)for(const t of n.allowRead||[])d.push(resolveSandboxFilesystemPath(t,o))}}const{rgPath:w,rgArgs:C,argv0:k}=W(),F=o.sandbox?.ripgrep??{command:w,args:C,argv0:k};return{network:{allowedDomains:n,deniedDomains:e,allowUnixSockets:o.sandbox?.network?.allowUnixSockets,allowAllUnixSockets:o.sandbox?.network?.allowAllUnixSockets,allowLocalBinding:o.sandbox?.network?.allowLocalBinding,httpProxyPort:o.sandbox?.network?.httpProxyPort,socksProxyPort:o.sandbox?.network?.socksProxyPort},filesystem:{denyRead:i,allowRead:d,allowWrite:a,denyWrite:r},ignoreViolations:o.sandbox?.ignoreViolations,enableWeakerNestedSandbox:o.sandbox?.enableWeakerNestedSandbox,enableWeakerNetworkIsolation:o.sandbox?.enableWeakerNetworkIsolation,ripgrep:F}}let I,L,D;const j=[],O=r(()=>{const{rgPath:t,rgArgs:n}=W();return o.checkDependencies({command:t,args:n})});function getSandboxEnabledSetting(){try{const o=w();return o?.sandbox?.enabled??!1}catch(o){return m(`Failed to get settings for sandbox check: ${o}`),!1}}const T=r(()=>o.isSupportedPlatform());function isPlatformInEnabledList(){try{const o=h(),t=o?.sandbox?.enabledPlatforms;if(void 0===t)return!0;if(0===t.length)return!1;const n=f();return t.includes(n)}catch(o){return m(`Failed to check enabledPlatforms: ${o}`),!0}}function isSandboxingEnabled(){return!!T()&&!(O().errors.length>0)&&!!isPlatformInEnabledList()&&getSandboxEnabledSetting()}export function addToExcludedCommands(o,t){const n=P("localSettings"),e=n?.sandbox?.excludedCommands||[];let s=o;if(t){const o=t.filter(o=>"addRules"===o.type&&o.rules.some(o=>o.toolName===F));if(o.length>0&&"addRules"===o[0].type){const t=o[0].rules.find(o=>o.toolName===F);t?.ruleContent&&(s=function(o){const t=o.match(/^(.+):\*$/);return t?.[1]??null}(t.ruleContent)||t.ruleContent)}}return e.includes(s)||k("localSettings",{sandbox:{...n?.sandbox,excludedCommands:[...e,s]}}),s}export const SandboxManager={initialize:async function(t){if(I)return I;if(!isSandboxingEnabled())return;const n=t?async o=>shouldAllowManagedSandboxDomainsOnly()?(m(`[sandbox] Blocked network request to ${o.host} (allowManagedDomainsOnly)`),!1):t(o):void 0;return I=(async()=>{try{void 0===D&&(D=await async function(o){const t=i(o,".git");try{const n=(await a(t,{encoding:"utf8"})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;const e=l(o,n[1].trim()),s=`${d}.git${d}worktrees${d}`,r=e.lastIndexOf(s);return r>0?e.substring(0,r):null}catch{return null}}(u()));const t=convertToSandboxRuntimeConfig(w());await o.initialize(t,n),L=x.subscribe(()=>{const t=convertToSandboxRuntimeConfig(w());o.updateConfig(t),m("Sandbox configuration updated from settings change")})}catch(o){I=void 0,m(`Failed to initialize sandbox: ${A(o)}`)}})(),I},isSandboxingEnabled,isSandboxEnabledInSettings:getSandboxEnabledSetting,isPlatformInEnabledList,getSandboxUnavailableReason:function(){if(!getSandboxEnabledSetting())return;if(!T()){const o=f();return"wsl"===o?"sandbox.enabled is set but WSL1 is not supported (requires WSL2)":`sandbox.enabled is set but ${o} is not supported (requires macOS, Linux, or WSL2)`}if(!isPlatformInEnabledList())return`sandbox.enabled is set but ${f()} is not in sandbox.enabledPlatforms`;const o=O();if(o.errors.length>0){const t="macos"===f()?"run /sandbox or /doctor for details":"install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details";return`sandbox.enabled is set but dependencies are missing: ${o.errors.join(", ")} · ${t}`}},isAutoAllowBashIfSandboxedEnabled:function(){const o=w();return o?.sandbox?.autoAllowBashIfSandboxed??!0},areUnsandboxedCommandsAllowed:function(){const o=w();return o?.sandbox?.allowUnsandboxedCommands??!0},isSandboxRequired:function(){const o=w();return getSandboxEnabledSetting()&&(o?.sandbox?.failIfUnavailable??!1)},areSandboxSettingsLockedByPolicy:function(){const o=["flagSettings","policySettings"];for(const t of o){const o=P(t);if(void 0!==o?.sandbox?.enabled||void 0!==o?.sandbox?.autoAllowBashIfSandboxed||void 0!==o?.sandbox?.allowUnsandboxedCommands)return!0}return!1},setSandboxSettings:async function(o){const t=P("localSettings");k("localSettings",{sandbox:{...t?.sandbox,...void 0!==o.enabled&&{enabled:o.enabled},...void 0!==o.autoAllowBashIfSandboxed&&{autoAllowBashIfSandboxed:o.autoAllowBashIfSandboxed},...void 0!==o.allowUnsandboxedCommands&&{allowUnsandboxedCommands:o.allowUnsandboxedCommands}}})},getExcludedCommands:function(){const o=w();return o?.sandbox?.excludedCommands??[]},wrapWithSandbox:async function(t,n,e,s){if(isSandboxingEnabled()){if(!I)throw new Error("Sandbox failed to initialize. ");await I}return o.wrapWithSandbox(t,n,e,s)},refreshConfig:function(){if(!isSandboxingEnabled())return;const t=convertToSandboxRuntimeConfig(w());o.updateConfig(t)},reset:async function(){return L?.(),L=void 0,D=void 0,j.length=0,O.cache.clear?.(),T.cache.clear?.(),I=void 0,o.reset()},checkDependencies:O,getFsReadConfig:o.getFsReadConfig,getFsWriteConfig:o.getFsWriteConfig,getNetworkRestrictionConfig:o.getNetworkRestrictionConfig,getIgnoreViolations:o.getIgnoreViolations,getLinuxGlobPatternWarnings:function(){const o=f();if("linux"!==o&&"wsl"!==o)return[];try{const o=w();if(!o?.sandbox?.enabled)return[];const t=o?.permissions||{},n=[],hasGlobs=o=>{const t=o.replace(/\/\*\*$/,"");return/[*?[\]]/.test(t)};for(const o of[...t.allow||[],...t.deny||[]]){const t=permissionRuleValueFromString(o);(t.toolName===E||t.toolName===v)&&t.ruleContent&&hasGlobs(t.ruleContent)&&n.push(o)}return n}catch(o){return m(`Failed to get Linux glob pattern warnings: ${o}`),[]}},isSupportedPlatform:T,getAllowUnixSockets:o.getAllowUnixSockets,getAllowLocalBinding:o.getAllowLocalBinding,getEnableWeakerNestedSandbox:o.getEnableWeakerNestedSandbox,getProxyPort:o.getProxyPort,getSocksProxyPort:o.getSocksProxyPort,getLinuxHttpSocketPath:o.getLinuxHttpSocketPath,getLinuxSocksSocketPath:o.getLinuxSocksSocketPath,waitForNetworkInitialization:o.waitForNetworkInitialization,getSandboxViolationStore:o.getSandboxViolationStore,annotateStderrWithSandboxFailures:o.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{o.cleanupAfterCommand(),function(){for(const o of j)try{e(o,{recursive:!0}),m(`[Sandbox] scrubbed planted bare-repo file: ${o}`)}catch{}}()}};export{n as SandboxViolationStore,t as SandboxRuntimeConfigSchema};
1
+ import{SandboxManager as o,SandboxRuntimeConfigSchema as n,SandboxViolationStore as t}from"@anthropic-ai/sandbox-runtime";import{rmSync as e,statSync as s}from"fs";import{readFile as a}from"fs/promises";import{memoize as r}from"lodash-es";import{join as i,resolve as l,sep as d}from"path";import{getAdditionalDirectoriesForClaudeMd as c,getCwdState as u,getOriginalCwd as b}from"../../bootstrap/state.js";import{logForDebugging as f}from"../debug.js";import{expandPath as m}from"../path.js";import{getPlatform as g}from"../platform.js";import{settingsChangeDetector as x}from"../settings/changeDetector.js";import{SETTING_SOURCES as p}from"../settings/constants.js";import{getManagedSettingsDropInDir as S}from"../settings/managedPath.js";import{getInitialSettings as h,getSettings_DEPRECATED as w,getSettingsFilePathForSource as y,getSettingsForSource as P,getSettingsRootPathForSource as k,updateSettingsForSource as C}from"../settings/settings.js";import{BASH_TOOL_NAME as v}from"../../tools/BashTool/toolName.js";import{FILE_EDIT_TOOL_NAME as F}from"../../tools/FileEditTool/constants.js";import{FILE_READ_TOOL_NAME as W}from"../../tools/FileReadTool/prompt.js";import{WEB_FETCH_TOOL_NAME as R}from"../../tools/WebFetchTool/prompt.js";import{errorMessage as E}from"../errors.js";import{getClaudeTempDir as A}from"../permissions/filesystem.js";import{ripgrepCommand as N}from"../ripgrep.js";function permissionRuleValueFromString(o){const n=o.match(/^([^(]+)\(([^)]+)\)$/);if(!n)return{toolName:o};const t=n[1],e=n[2];return t&&e?{toolName:t,ruleContent:e}:{toolName:o}}export function resolvePathPatternForSandbox(o,n){if(o.startsWith("//"))return o.slice(1);if(o.startsWith("/")&&!o.startsWith("//")){const t=k(n);return l(t,o.slice(1))}return o}export function resolveSandboxFilesystemPath(o,n){return o.startsWith("//")?o.slice(1):m(o,k(n))}export function shouldAllowManagedSandboxDomainsOnly(){return!0===P("policySettings")?.sandbox?.network?.allowManagedDomainsOnly}function shouldAllowManagedReadPathsOnly(){return!0===P("policySettings")?.sandbox?.filesystem?.allowManagedReadPathsOnly}export function convertToSandboxRuntimeConfig(o){const n=o.permissions||{},t=[],e=[];if(shouldAllowManagedSandboxDomainsOnly()){const o=P("policySettings");for(const n of o?.sandbox?.network?.allowedDomains||[])t.push(n);for(const n of o?.permissions?.allow||[]){const o=permissionRuleValueFromString(n);o.toolName===R&&o.ruleContent?.startsWith("domain:")&&t.push(o.ruleContent.substring(7))}}else{for(const n of o.sandbox?.network?.allowedDomains||[])t.push(n);for(const o of n.allow||[]){const n=permissionRuleValueFromString(o);n.toolName===R&&n.ruleContent?.startsWith("domain:")&&t.push(n.ruleContent.substring(7))}}for(const o of n.deny||[]){const n=permissionRuleValueFromString(o);n.toolName===R&&n.ruleContent?.startsWith("domain:")&&e.push(n.ruleContent.substring(7))}const a=[".",A()],r=[],i=[],d=[],f=p.map(o=>y(o)).filter(o=>void 0!==o);r.push(...f),r.push(S());const m=u(),g=b();m!==g&&(r.push(l(m,".claude","settings.json")),r.push(l(m,".claude","settings.local.json"))),r.push(l(g,".claude","skills")),r.push(l(g,".context","skills")),m!==g&&(r.push(l(m,".claude","skills")),r.push(l(m,".context","skills"))),$.length=0;const x=["HEAD","objects","refs","hooks","config"];for(const o of m===g?[g]:[g,m])for(const n of x){const t=l(o,n);try{s(t),r.push(t)}catch{$.push(t)}}j&&j!==m&&a.push(j);const h=new Set([...o.permissions?.additionalDirectories||[],...c()]);a.push(...h);for(const o of p){const n=P(o);if(n?.permissions){for(const t of n.permissions.allow||[]){const n=permissionRuleValueFromString(t);n.toolName===F&&n.ruleContent&&a.push(resolvePathPatternForSandbox(n.ruleContent,o))}for(const t of n.permissions.deny||[]){const n=permissionRuleValueFromString(t);n.toolName===F&&n.ruleContent&&r.push(resolvePathPatternForSandbox(n.ruleContent,o)),n.toolName===W&&n.ruleContent&&i.push(resolvePathPatternForSandbox(n.ruleContent,o))}}const t=n?.sandbox?.filesystem;if(t){for(const n of t.allowWrite||[])a.push(resolveSandboxFilesystemPath(n,o));for(const n of t.denyWrite||[])r.push(resolveSandboxFilesystemPath(n,o));for(const n of t.denyRead||[])i.push(resolveSandboxFilesystemPath(n,o));if(!shouldAllowManagedReadPathsOnly()||"policySettings"===o)for(const n of t.allowRead||[])d.push(resolveSandboxFilesystemPath(n,o))}}const{rgPath:w,rgArgs:k,argv0:C}=N(),v=o.sandbox?.ripgrep??{command:w,args:k,argv0:C};return{network:{allowedDomains:t,deniedDomains:e,allowUnixSockets:o.sandbox?.network?.allowUnixSockets,allowAllUnixSockets:o.sandbox?.network?.allowAllUnixSockets,allowLocalBinding:o.sandbox?.network?.allowLocalBinding,httpProxyPort:o.sandbox?.network?.httpProxyPort,socksProxyPort:o.sandbox?.network?.socksProxyPort},filesystem:{denyRead:i,allowRead:d,allowWrite:a,denyWrite:r},ignoreViolations:o.sandbox?.ignoreViolations,enableWeakerNestedSandbox:o.sandbox?.enableWeakerNestedSandbox,enableWeakerNetworkIsolation:o.sandbox?.enableWeakerNetworkIsolation,ripgrep:v}}let I,L,j;const $=[];const D=r(()=>{const{rgPath:n,rgArgs:t}=N();return o.checkDependencies({command:n,args:t})});function getSandboxEnabledSetting(){try{const o=w();return o?.sandbox?.enabled??!1}catch(o){return f(`Failed to get settings for sandbox check: ${o}`),!1}}const U=r(()=>o.isSupportedPlatform());function isPlatformInEnabledList(){try{const o=h(),n=o?.sandbox?.enabledPlatforms;if(void 0===n)return!0;if(0===n.length)return!1;const t=g();return n.includes(t)}catch(o){return f(`Failed to check enabledPlatforms: ${o}`),!0}}function isSandboxingEnabled(){return!!U()&&(!(D().errors.length>0)&&(!!isPlatformInEnabledList()&&getSandboxEnabledSetting()))}export function addToExcludedCommands(o,n){const t=P("localSettings"),e=t?.sandbox?.excludedCommands||[];let s=o;if(n){const o=n.filter(o=>"addRules"===o.type&&o.rules.some(o=>o.toolName===v));if(o.length>0&&"addRules"===o[0].type){const n=o[0].rules.find(o=>o.toolName===v);if(n?.ruleContent){s=function(o){const n=o.match(/^(.+):\*$/);return n?.[1]??null}(n.ruleContent)||n.ruleContent}}}return e.includes(s)||C("localSettings",{sandbox:{...t?.sandbox,excludedCommands:[...e,s]}}),s}export const SandboxManager={initialize:async function(n){if(I)return I;if(!isSandboxingEnabled())return;const t=n?async o=>shouldAllowManagedSandboxDomainsOnly()?(f(`[sandbox] Blocked network request to ${o.host} (allowManagedDomainsOnly)`),!1):n(o):void 0;return I=(async()=>{try{void 0===j&&(j=await async function(o){const n=i(o,".git");try{const t=(await a(n,{encoding:"utf8"})).match(/^gitdir:\s*(.+)$/m);if(!t?.[1])return null;const e=l(o,t[1].trim()),s=`${d}.git${d}worktrees${d}`,r=e.lastIndexOf(s);return r>0?e.substring(0,r):null}catch{return null}}(u()));const n=convertToSandboxRuntimeConfig(w());await o.initialize(n,t),L=x.subscribe(()=>{const n=convertToSandboxRuntimeConfig(w());o.updateConfig(n),f("Sandbox configuration updated from settings change")})}catch(o){I=void 0,f(`Failed to initialize sandbox: ${E(o)}`)}})(),I},isSandboxingEnabled,isSandboxEnabledInSettings:getSandboxEnabledSetting,isPlatformInEnabledList,getSandboxUnavailableReason:function(){if(!getSandboxEnabledSetting())return;if(!U()){const o=g();return"wsl"===o?"sandbox.enabled is set but WSL1 is not supported (requires WSL2)":`sandbox.enabled is set but ${o} is not supported (requires macOS, Linux, or WSL2)`}if(!isPlatformInEnabledList())return`sandbox.enabled is set but ${g()} is not in sandbox.enabledPlatforms`;const o=D();if(o.errors.length>0){const n="macos"===g()?"run /sandbox or /doctor for details":"install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details";return`sandbox.enabled is set but dependencies are missing: ${o.errors.join(", ")} · ${n}`}},isAutoAllowBashIfSandboxedEnabled:function(){const o=w();return o?.sandbox?.autoAllowBashIfSandboxed??!0},areUnsandboxedCommandsAllowed:function(){const o=w();return o?.sandbox?.allowUnsandboxedCommands??!0},isSandboxRequired:function(){const o=w();return getSandboxEnabledSetting()&&(o?.sandbox?.failIfUnavailable??!1)},areSandboxSettingsLockedByPolicy:function(){const o=["flagSettings","policySettings"];for(const n of o){const o=P(n);if(void 0!==o?.sandbox?.enabled||void 0!==o?.sandbox?.autoAllowBashIfSandboxed||void 0!==o?.sandbox?.allowUnsandboxedCommands)return!0}return!1},setSandboxSettings:async function(o){const n=P("localSettings");C("localSettings",{sandbox:{...n?.sandbox,...void 0!==o.enabled&&{enabled:o.enabled},...void 0!==o.autoAllowBashIfSandboxed&&{autoAllowBashIfSandboxed:o.autoAllowBashIfSandboxed},...void 0!==o.allowUnsandboxedCommands&&{allowUnsandboxedCommands:o.allowUnsandboxedCommands}}})},getExcludedCommands:function(){const o=w();return o?.sandbox?.excludedCommands??[]},wrapWithSandbox:async function(n,t,e,s){if(isSandboxingEnabled()){if(!I)throw new Error("Sandbox failed to initialize. ");await I}return o.wrapWithSandbox(n,t,e,s)},refreshConfig:function(){if(!isSandboxingEnabled())return;const n=convertToSandboxRuntimeConfig(w());o.updateConfig(n)},reset:async function(){return L?.(),L=void 0,j=void 0,$.length=0,D.cache.clear?.(),U.cache.clear?.(),I=void 0,o.reset()},checkDependencies:D,getFsReadConfig:o.getFsReadConfig,getFsWriteConfig:o.getFsWriteConfig,getNetworkRestrictionConfig:o.getNetworkRestrictionConfig,getIgnoreViolations:o.getIgnoreViolations,getLinuxGlobPatternWarnings:function(){const o=g();if("linux"!==o&&"wsl"!==o)return[];try{const o=w();if(!o?.sandbox?.enabled)return[];const n=o?.permissions||{},t=[],hasGlobs=o=>{const n=o.replace(/\/\*\*$/,"");return/[*?[\]]/.test(n)};for(const o of[...n.allow||[],...n.deny||[]]){const n=permissionRuleValueFromString(o);(n.toolName===F||n.toolName===W)&&n.ruleContent&&hasGlobs(n.ruleContent)&&t.push(o)}return t}catch(o){return f(`Failed to get Linux glob pattern warnings: ${o}`),[]}},isSupportedPlatform:U,getAllowUnixSockets:o.getAllowUnixSockets,getAllowLocalBinding:o.getAllowLocalBinding,getEnableWeakerNestedSandbox:o.getEnableWeakerNestedSandbox,getProxyPort:o.getProxyPort,getSocksProxyPort:o.getSocksProxyPort,getLinuxHttpSocketPath:o.getLinuxHttpSocketPath,getLinuxSocksSocketPath:o.getLinuxSocksSocketPath,waitForNetworkInitialization:o.waitForNetworkInitialization,getSandboxViolationStore:o.getSandboxViolationStore,annotateStderrWithSandboxFailures:o.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{o.cleanupAfterCommand(),function(){for(const o of $)try{e(o,{recursive:!0}),f(`[Sandbox] scrubbed planted bare-repo file: ${o}`)}catch{}}()}};export{t as SandboxViolationStore,n as SandboxRuntimeConfigSchema};
@@ -1 +1 @@
1
- import{randomUUID as t}from"crypto";import{getIsNonInteractiveSession as e,getSessionId as s}from"../bootstrap/state.js";import{recordSdkEvent as o}from"../core/tasks/sdkAdapter.js";const n=[];export function enqueueSdkEvent(t){o(t),e()&&(n.length>=1e3&&n.shift(),n.push(t))}export function drainSdkEvents(){return 0===n.length?[]:n.splice(0).map(e=>({...e,uuid:t(),session_id:s()}))}export function emitTaskTerminatedSdk(t,e,s){enqueueSdkEvent({type:"system",subtype:"task_notification",task_id:t,tool_use_id:s?.toolUseId,status:e,output_file:s?.outputFile??"",summary:s?.summary??"",usage:s?.usage})}
1
+ import{randomUUID as t}from"crypto";import{getIsNonInteractiveSession as e,getSessionId as s}from"../bootstrap/state.js";import{recordSdkEvent as o}from"../core/tasks/sdkAdapter.js";const u=[];export function enqueueSdkEvent(t){o(t),e()&&(u.length>=1e3&&u.shift(),u.push(t))}export function drainSdkEvents(){if(0===u.length)return[];return u.splice(0).map(e=>({...e,uuid:t(),session_id:s()}))}export function emitTaskTerminatedSdk(t,e,s){enqueueSdkEvent({type:"system",subtype:"task_notification",task_id:t,tool_use_id:s?.toolUseId,status:e,output_file:s?.outputFile??"",summary:s?.summary??"",usage:s?.usage})}
@@ -1 +1 @@
1
- import{createFallbackStorage as a}from"./fallbackStorage.js";import{macOsKeychainStorage as r}from"./macOsKeychainStorage.js";import{plainTextStorage as e}from"./plainTextStorage.js";import{sqliteStorage as t}from"./sqliteStorage.js";export function getSecureStorage(){return"darwin"===process.platform?a(r,e):t}
1
+ import{createFallbackStorage as r}from"./fallbackStorage.js";import{macOsKeychainStorage as o}from"./macOsKeychainStorage.js";import{plainTextStorage as t}from"./plainTextStorage.js";import{sqliteStorage as e}from"./sqliteStorage.js";export function getSecureStorage(){return"darwin"===process.platform?r(o,t):e}
@@ -1 +1 @@
1
- import{createHash as e}from"crypto";import{userInfo as t}from"os";import{getOauthConfig as a}from"src/constants/oauth.js";import{getClaudeConfigHomeDir as c}from"../envUtils.js";export const CREDENTIALS_SERVICE_SUFFIX="-credentials";export function getMacOsKeychainStorageServiceName(t=""){const n=c(),r=process.env.CLAUDE_CONFIG_DIR?`-${e("sha256").update(n).digest("hex").substring(0,8)}`:"";return`Context Code${a().OAUTH_FILE_SUFFIX}${t}${r}`}export function getUsername(){try{return process.env.USER||t().username}catch{return"claude-code-user"}}export const KEYCHAIN_CACHE_TTL_MS=3e4;export const keychainCacheState={cache:{data:null,cachedAt:0},generation:0,readInFlight:null};export function clearKeychainCache(){keychainCacheState.cache={data:null,cachedAt:0},keychainCacheState.generation++,keychainCacheState.readInFlight=null}export function primeKeychainCacheFromPrefetch(e){if(0!==keychainCacheState.cache.cachedAt)return;let t=null;if(e)try{t=JSON.parse(e)}catch{return}keychainCacheState.cache={data:t,cachedAt:Date.now()}}
1
+ import{createHash as e}from"crypto";import{userInfo as t}from"os";import{getOauthConfig as a}from"../../constants/oauth.js";import{getClaudeConfigHomeDir as c}from"../envUtils.js";export const CREDENTIALS_SERVICE_SUFFIX="-credentials";export function getMacOsKeychainStorageServiceName(t=""){const n=c(),r=!process.env.CLAUDE_CONFIG_DIR?"":`-${e("sha256").update(n).digest("hex").substring(0,8)}`;return`Context Code${a().OAUTH_FILE_SUFFIX}${t}${r}`}export function getUsername(){try{return process.env.USER||t().username}catch{return"claude-code-user"}}export const KEYCHAIN_CACHE_TTL_MS=3e4;export const keychainCacheState={cache:{data:null,cachedAt:0},generation:0,readInFlight:null};export function clearKeychainCache(){keychainCacheState.cache={data:null,cachedAt:0},keychainCacheState.generation++,keychainCacheState.readInFlight=null}export function primeKeychainCacheFromPrefetch(e){if(0!==keychainCacheState.cache.cachedAt)return;let t=null;if(e)try{t=JSON.parse(e)}catch{return}keychainCacheState.cache={data:t,cachedAt:Date.now()}}
@@ -1 +1 @@
1
- import{execaSync as e}from"execa";import{logForDebugging as a}from"../debug.js";import{execFileNoThrow as t}from"../execFileNoThrow.js";import{execSyncWithDefaults_DEPRECATED as r}from"../execFileNoThrowPortable.js";import{jsonParse as c,jsonStringify as n}from"../slowOperations.js";import{CREDENTIALS_SERVICE_SUFFIX as s,clearKeychainCache as i,getMacOsKeychainStorageServiceName as o,getUsername as d,KEYCHAIN_CACHE_TTL_MS as u,keychainCacheState as h}from"./macOsKeychainHelpers.js";export const macOsKeychainStorage={name:"keychain",read(){const e=h.cache;if(Date.now()-e.cachedAt<u)return e.data;try{const e=o(s),a=d(),t=r(`security find-generic-password -a "${a}" -w -s "${e}"`);if(t){const e=c(t);return h.cache={data:e,cachedAt:Date.now()},e}}catch(e){}return null!==e.data?(a("[keychain] read failed; serving stale cache",{level:"warn"}),h.cache={data:e.data,cachedAt:Date.now()},e.data):(h.cache={data:null,cachedAt:Date.now()},null)},async readAsync(){const e=h.cache;if(Date.now()-e.cachedAt<u)return e.data;if(h.readInFlight)return h.readInFlight;const r=h.generation,n=async function(){try{const e=o(s),a=d(),{stdout:r,code:n}=await t("security",["find-generic-password","-a",a,"-w","-s",e],{useCwd:!1,preserveOutputOnError:!1});if(0===n&&r)return c(r.trim())}catch(e){}return null}().then(t=>{if(r===h.generation){null===t&&null!==e.data&&a("[keychain] readAsync failed; serving stale cache",{level:"warn"});const r=t??e.data;return h.cache={data:r,cachedAt:Date.now()},h.readInFlight=null,r}return t});return h.readInFlight=n,n},update(t){i();try{const r=o(s),c=d(),i=n(t),u=Buffer.from(i,"utf-8").toString("hex"),l=`add-generic-password -U -a "${c}" -s "${r}" -X "${u}"\n`;let p;return l.length<=4032?p=e("security",["-i"],{input:l,stdio:["pipe","pipe","pipe"],reject:!1}):(a(`Keychain payload (${i.length}B JSON) exceeds security -i stdin limit; using argv`,{level:"warn"}),p=e("security",["add-generic-password","-U","-a",c,"-s",r,"-X",u],{stdio:["ignore","pipe","pipe"],reject:!1})),0!==p.exitCode?{success:!1}:(h.cache={data:t,cachedAt:Date.now()},{success:!0})}catch(e){return{success:!1}}},delete(){i();try{const e=o(s),a=d();return r(`security delete-generic-password -a "${a}" -s "${e}"`),!0}catch(e){return!1}}};let l;export function isMacOsKeychainLocked(){if(void 0!==l)return l;if("darwin"!==process.platform)return l=!1,!1;try{const a=e("security",["show-keychain-info"],{reject:!1,stdio:["ignore","pipe","pipe"]});l=36===a.exitCode}catch{l=!1}return l}
1
+ import{execaSync as e}from"execa";import{logForDebugging as t}from"../debug.js";import{execFileNoThrow as r}from"../execFileNoThrow.js";import{execSyncWithDefaults_DEPRECATED as a}from"../execFileNoThrowPortable.js";import{jsonParse as c,jsonStringify as n}from"../slowOperations.js";import{CREDENTIALS_SERVICE_SUFFIX as i,clearKeychainCache as s,getMacOsKeychainStorageServiceName as o,getUsername as d,KEYCHAIN_CACHE_TTL_MS as u,keychainCacheState as l}from"./macOsKeychainHelpers.js";export const macOsKeychainStorage={name:"keychain",read(){const e=l.cache;if(Date.now()-e.cachedAt<u)return e.data;try{const e=o(i),t=d(),r=a(`security find-generic-password -a "${t}" -w -s "${e}"`);if(r){const e=c(r);return l.cache={data:e,cachedAt:Date.now()},e}}catch(e){}return null!==e.data?(t("[keychain] read failed; serving stale cache",{level:"warn"}),l.cache={data:e.data,cachedAt:Date.now()},e.data):(l.cache={data:null,cachedAt:Date.now()},null)},async readAsync(){const e=l.cache;if(Date.now()-e.cachedAt<u)return e.data;if(l.readInFlight)return l.readInFlight;const a=l.generation,n=async function(){try{const e=o(i),t=d(),{stdout:a,code:n}=await r("security",["find-generic-password","-a",t,"-w","-s",e],{useCwd:!1,preserveOutputOnError:!1});if(0===n&&a)return c(a.trim())}catch(e){}return null}().then(r=>{if(a===l.generation){null===r&&null!==e.data&&t("[keychain] readAsync failed; serving stale cache",{level:"warn"});const a=r??e.data;return l.cache={data:a,cachedAt:Date.now()},l.readInFlight=null,a}return r});return l.readInFlight=n,n},update(r){s();try{const a=o(i),c=d(),s=n(r),u=Buffer.from(s,"utf-8").toString("hex"),h=`add-generic-password -U -a "${c}" -s "${a}" -X "${u}"\n`;let p;return h.length<=4032?p=e("security",["-i"],{input:h,stdio:["pipe","pipe","pipe"],reject:!1}):(t(`Keychain payload (${s.length}B JSON) exceeds security -i stdin limit; using argv`,{level:"warn"}),p=e("security",["add-generic-password","-U","-a",c,"-s",a,"-X",u],{stdio:["ignore","pipe","pipe"],reject:!1})),0!==p.exitCode?{success:!1}:(l.cache={data:r,cachedAt:Date.now()},{success:!0})}catch(e){return{success:!1}}},delete(){s();try{const e=o(i),t=d();return a(`security delete-generic-password -a "${t}" -s "${e}"`),!0}catch(e){return!1}}};let h;export function isMacOsKeychainLocked(){if(void 0!==h)return h;if("darwin"!==process.platform)return h=!1,!1;try{const t=e("security",["show-keychain-info"],{reject:!1,stdio:["ignore","pipe","pipe"]});h=36===t.exitCode}catch{h=!1}return h}
@@ -1 +1 @@
1
- import{chmodSync as t}from"fs";import{join as r}from"path";import{getClaudeConfigHomeDir as e}from"../envUtils.js";import{getErrnoCode as n}from"../errors.js";import{getFsImplementation as a}from"../fsOperations.js";import{jsonParse as o,jsonStringify as s,writeFileSync_DEPRECATED as i}from"../slowOperations.js";function getStoragePath(){const t=e();return{storageDir:t,storagePath:r(t,".credentials.json")}}export const plainTextStorage={name:"plaintext",read(){const{storagePath:t}=getStoragePath();try{const r=a().readFileSync(t,{encoding:"utf8"});return o(r)}catch{return null}},async readAsync(){const{storagePath:t}=getStoragePath();try{const r=await a().readFile(t,{encoding:"utf8"});return o(r)}catch{return null}},update(r){try{const{storageDir:e,storagePath:o}=getStoragePath();try{a().mkdirSync(e)}catch(t){if("EEXIST"!==n(t))throw t}return i(o,s(r),{encoding:"utf8",flush:!1}),t(o,384),{success:!0,warning:"Warning: Storing credentials in plaintext."}}catch{return{success:!1}}},delete(){const{storagePath:t}=getStoragePath();try{return a().unlinkSync(t),!0}catch(t){return"ENOENT"===n(t)}}};
1
+ import{chmodSync as t}from"fs";import{join as r}from"path";import{getClaudeConfigHomeDir as e}from"../envUtils.js";import{getErrnoCode as n}from"../errors.js";import{getFsImplementation as a}from"../fsOperations.js";import{jsonParse as o,jsonStringify as s,writeFileSync_DEPRECATED as c}from"../slowOperations.js";function getStoragePath(){const t=e();return{storageDir:t,storagePath:r(t,".credentials.json")}}export const plainTextStorage={name:"plaintext",read(){const{storagePath:t}=getStoragePath();try{const r=a().readFileSync(t,{encoding:"utf8"});return o(r)}catch{return null}},async readAsync(){const{storagePath:t}=getStoragePath();try{const r=await a().readFile(t,{encoding:"utf8"});return o(r)}catch{return null}},update(r){try{const{storageDir:e,storagePath:o}=getStoragePath();try{a().mkdirSync(e)}catch(t){if("EEXIST"!==n(t))throw t}return c(o,s(r),{encoding:"utf8",flush:!1}),t(o,384),{success:!0,warning:"Warning: Storing credentials in plaintext."}}catch{return{success:!1}}},delete(){const{storagePath:t}=getStoragePath();try{return a().unlinkSync(t),!0}catch(t){return"ENOENT"===n(t)}}};
@@ -1 +1 @@
1
- import{chmodSync as e}from"fs";import{createCipheriv as t,createDecipheriv as r,randomBytes as n}from"crypto";import{createRequire as a}from"module";import{join as o}from"path";import{getClaudeConfigHomeDir as s}from"../envUtils.js";import{getErrnoCode as c}from"../errors.js";import{getFsImplementation as i}from"../fsOperations.js";import{jsonParse as u,jsonStringify as l,writeFileSync_DEPRECATED as f}from"../slowOperations.js";import{plainTextStorage as g}from"./plainTextStorage.js";const y=a(import.meta.url),h="enc:v1:";function getDatabasePath(){return o(s(),"provider-state.sqlite3")}function getKeyPath(){return o(s(),"secure-storage.key")}function getLegacyCredentialsPath(){return o(s(),".credentials.json")}let p=null,m=!1,d=null;function getOrCreateEncryptionKey(){if(d)return d;const t=i(),r=getKeyPath();try{const e=t.readFileSync(r,{encoding:"utf8"}).trim();if(e)return d=Buffer.from(e,"hex"),d}catch{}const a=n(32);return f(r,a.toString("hex"),{encoding:"utf8",flush:!1}),e(r,384),d=a,a}function savePayload(e,r){e.prepare("\n INSERT INTO secure_storage (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n ").run("main_storage",function(e){const r=getOrCreateEncryptionKey(),a=n(12),o=t("aes-256-gcm",r,a),s=Buffer.concat([o.update(e,"utf8"),o.final()]),c=o.getAuthTag();return`${h}${a.toString("hex")}:${c.toString("hex")}:${s.toString("hex")}`}(r))}function getDb(){if(p)return p;const e=getDatabasePath();try{try{i().mkdirSync(s(),{mode:448})}catch(e){if("EEXIST"!==c(e))throw e}const t=y("node:sqlite");return p=new t.DatabaseSync(e),p.exec("\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS secure_storage (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n "),p}catch(e){return console.error("Error al inicializar SQLite para SecureStorage:",e),null}}export const sqliteStorage={name:"sqlite",read(){const e=getDb();if(!e)return null;try{const t=e.prepare("SELECT value FROM secure_storage WHERE key = ?").get("main_storage");if(t){const n=String(t.value),a=function(e){if(!e.startsWith(h))return e;const t=e.slice(7),[n,a,o]=t.split(":");if(!n||!a||!o)throw new Error("Payload cifrado invalido.");const s=getOrCreateEncryptionKey(),c=r("aes-256-gcm",s,Buffer.from(n,"hex"));return c.setAuthTag(Buffer.from(a,"hex")),Buffer.concat([c.update(Buffer.from(o,"hex")),c.final()]).toString("utf8")}(n);return n.startsWith(h)||savePayload(e,a),hasLegacyCredentialsFile()&&g.delete(),u(a)}return function(e){if(m)return null;m=!0;const t=g.read();return t&&0!==Object.keys(t).length?(savePayload(e,l(t)),g.delete(),t):null}(e)}catch{return null}},async readAsync(){return this.read()},update(e){const t=getDb();if(!t)return{success:!1};try{return savePayload(t,l(e)),{success:!0}}catch(e){return console.error("Error al actualizar SQLite:",e),{success:!1}}},delete(){const e=getDb();if(!e)return!1;try{return e.prepare("DELETE FROM secure_storage WHERE key = ?").run("main_storage"),!0}catch{return!1}}};export function getSecureStorageDbPath(){return getDatabasePath()}export function getSecureStorageKeyPath(){return getKeyPath()}export function getLegacyCredentialsFilePath(){return getLegacyCredentialsPath()}export function hasLegacyCredentialsFile(){try{return i().existsSync(getLegacyCredentialsPath())}catch{return!1}}export function isSecureStorageEncrypted(){const e=function(){const e=getDb();if(!e)return null;try{const t=e.prepare("SELECT value FROM secure_storage WHERE key = ?").get("main_storage");return"string"==typeof t?.value?t.value:null}catch{return null}}();return!!e&&e.startsWith(h)}
1
+ import{chmodSync as e}from"fs";import{createCipheriv as t,createDecipheriv as r,randomBytes as n}from"crypto";import{createRequire as a}from"module";import{join as o}from"path";import{getClaudeConfigHomeDir as u}from"../envUtils.js";import{getErrnoCode as c}from"../errors.js";import{getFsImplementation as s}from"../fsOperations.js";import{jsonParse as i,jsonStringify as l,writeFileSync_DEPRECATED as f}from"../slowOperations.js";import{plainTextStorage as g}from"./plainTextStorage.js";const y=a(import.meta.url),h="enc:v1:";function getDatabasePath(){return o(u(),"provider-state.sqlite3")}function getKeyPath(){return o(u(),"secure-storage.key")}function getLegacyCredentialsPath(){return o(u(),".credentials.json")}let p=null,d=!1,m=null;function getOrCreateEncryptionKey(){if(m)return m;const t=s(),r=getKeyPath();try{const e=t.readFileSync(r,{encoding:"utf8"}).trim();if(e)return m=Buffer.from(e,"hex"),m}catch{}const a=n(32);return f(r,a.toString("hex"),{encoding:"utf8",flush:!1}),e(r,384),m=a,a}function savePayload(e,r){e.prepare("\n INSERT INTO secure_storage (key, value)\n VALUES (?, ?)\n ON CONFLICT(key) DO UPDATE SET value = excluded.value\n ").run("main_storage",function(e){const r=getOrCreateEncryptionKey(),a=n(12),o=t("aes-256-gcm",r,a),u=Buffer.concat([o.update(e,"utf8"),o.final()]),c=o.getAuthTag();return`${h}${a.toString("hex")}:${c.toString("hex")}:${u.toString("hex")}`}(r))}function getDb(){if(p)return p;const e=getDatabasePath();try{try{s().mkdirSync(u(),{mode:448})}catch(e){if("EEXIST"!==c(e))throw e}const t=y("node:sqlite");return p=new t.DatabaseSync(e),p.exec("\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS secure_storage (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n "),p}catch(e){return console.error("Error al inicializar SQLite para SecureStorage:",e),null}}export const sqliteStorage={name:"sqlite",read(){const e=getDb();if(!e)return null;try{const t=e.prepare("SELECT value FROM secure_storage WHERE key = ?").get("main_storage");if(t){const n=String(t.value),a=function(e){if(!e.startsWith(h))return e;const t=e.slice(7),[n,a,o]=t.split(":");if(!n||!a||!o)throw new Error("Payload cifrado invalido.");const u=getOrCreateEncryptionKey(),c=r("aes-256-gcm",u,Buffer.from(n,"hex"));return c.setAuthTag(Buffer.from(a,"hex")),Buffer.concat([c.update(Buffer.from(o,"hex")),c.final()]).toString("utf8")}(n);return n.startsWith(h)||savePayload(e,a),hasLegacyCredentialsFile()&&g.delete(),i(a)}return function(e){if(d)return null;d=!0;const t=g.read();return t&&0!==Object.keys(t).length?(savePayload(e,l(t)),g.delete(),t):null}(e)}catch{return null}},async readAsync(){return this.read()},update(e){const t=getDb();if(!t)return{success:!1};try{return savePayload(t,l(e)),{success:!0}}catch(e){return console.error("Error al actualizar SQLite:",e),{success:!1}}},delete(){const e=getDb();if(!e)return!1;try{return e.prepare("DELETE FROM secure_storage WHERE key = ?").run("main_storage"),!0}catch{return!1}}};export function getSecureStorageDbPath(){return getDatabasePath()}export function getSecureStorageKeyPath(){return getKeyPath()}export function getLegacyCredentialsFilePath(){return getLegacyCredentialsPath()}export function hasLegacyCredentialsFile(){try{return s().existsSync(getLegacyCredentialsPath())}catch{return!1}}export function isSecureStorageEncrypted(){const e=function(){const e=getDb();if(!e)return null;try{const t=e.prepare("SELECT value FROM secure_storage WHERE key = ?").get("main_storage");return"string"==typeof t?.value?t.value:null}catch{return null}}();return!!e&&e.startsWith(h)}
@@ -1 +1 @@
1
- import{mkdir as t,readdir as e,readFile as o,writeFile as s}from"fs/promises";import{join as n}from"path";import{getSessionId as r}from"../bootstrap/state.js";import{logForDebugging as i}from"./debug.js";import{getClaudeConfigHomeDir as a}from"./envUtils.js";import{errorMessage as c,getErrnoCode as l}from"./errors.js";import{getPlatform as d}from"./platform.js";let h;export async function getSessionEnvDirPath(){const e=n(a(),"session-env",r());return await t(e,{recursive:!0}),e}export async function getHookEnvFilePath(t,e){const o=t.toLowerCase();return n(await getSessionEnvDirPath(),`${o}-hook-${e}.sh`)}export async function clearCwdEnvFiles(){try{const t=await getSessionEnvDirPath(),o=await e(t);await Promise.all(o.filter(t=>(t.startsWith("filechanged-hook-")||t.startsWith("cwdchanged-hook-"))&&m.test(t)).map(e=>s(n(t,e),"")))}catch(t){"ENOENT"!==l(t)&&i(`Failed to clear cwd env files: ${c(t)}`)}}export function invalidateSessionEnvCache(){i("Invalidating session environment cache"),h=void 0}export async function getSessionEnvironmentScript(){if("windows"===d())return i("Session environment not yet supported on Windows"),null;if(void 0!==h)return h;const t=[],s=process.env.CONTEXT_ENV_FILE??process.env.CLAUDE_ENV_FILE;if(s)try{const e=(await o(s,"utf8")).trim();e&&(t.push(e),i(`Session environment loaded from CLAUDE_ENV_FILE: ${s} (${e.length} chars)`))}catch(t){"ENOENT"!==l(t)&&i(`Failed to read CLAUDE_ENV_FILE: ${c(t)}`)}const r=await getSessionEnvDirPath();try{const s=(await e(r)).filter(t=>m.test(t)).sort(sortHookEnvFiles);for(const e of s){const s=n(r,e);try{const e=(await o(s,"utf8")).trim();e&&t.push(e)}catch(t){"ENOENT"!==l(t)&&i(`Failed to read hook file ${s}: ${c(t)}`)}}s.length>0&&i(`Session environment loaded from ${s.length} hook file(s)`)}catch(t){"ENOENT"!==l(t)&&i(`Failed to load session environment from hooks: ${c(t)}`)}return 0===t.length?(i("No session environment scripts found"),h=null,h):(h=t.join("\n"),i(`Session environment script ready (${h.length} chars total)`),h)}const f={setup:0,sessionstart:1,cwdchanged:2,filechanged:3},m=/^(setup|sessionstart|cwdchanged|filechanged)-hook-(\d+)\.sh$/;function sortHookEnvFiles(t,e){const o=t.match(m),s=e.match(m),n=o?.[1]||"",r=s?.[1]||"";return n!==r?(f[n]??99)-(f[r]??99):parseInt(o?.[2]||"0",10)-parseInt(s?.[2]||"0",10)}
1
+ import{mkdir as t,readdir as o,readFile as n,writeFile as e}from"fs/promises";import{join as s}from"path";import{getSessionId as i}from"../bootstrap/state.js";import{logForDebugging as r}from"./debug.js";import{getClaudeConfigHomeDir as a}from"./envUtils.js";import{errorMessage as c,getErrnoCode as h}from"./errors.js";import{getPlatform as l}from"./platform.js";let f;export async function getSessionEnvDirPath(){const o=s(a(),"session-env",i());return await t(o,{recursive:!0}),o}export async function getHookEnvFilePath(t,o){const n=t.toLowerCase();return s(await getSessionEnvDirPath(),`${n}-hook-${o}.sh`)}export async function clearCwdEnvFiles(){try{const t=await getSessionEnvDirPath(),n=await o(t);await Promise.all(n.filter(t=>(t.startsWith("filechanged-hook-")||t.startsWith("cwdchanged-hook-"))&&m.test(t)).map(o=>e(s(t,o),"")))}catch(t){"ENOENT"!==h(t)&&r(`Failed to clear cwd env files: ${c(t)}`)}}export function invalidateSessionEnvCache(){r("Invalidating session environment cache"),f=void 0}export async function getSessionEnvironmentScript(){if("windows"===l())return r("Session environment not yet supported on Windows"),null;if(void 0!==f)return f;const t=[],e=process.env.CONTEXT_ENV_FILE??process.env.CLAUDE_ENV_FILE;if(e)try{const o=(await n(e,"utf8")).trim();o&&(t.push(o),r(`Session environment loaded from CLAUDE_ENV_FILE: ${e} (${o.length} chars)`))}catch(t){"ENOENT"!==h(t)&&r(`Failed to read CLAUDE_ENV_FILE: ${c(t)}`)}const i=await getSessionEnvDirPath();try{const e=(await o(i)).filter(t=>m.test(t)).sort(sortHookEnvFiles);for(const o of e){const e=s(i,o);try{const o=(await n(e,"utf8")).trim();o&&t.push(o)}catch(t){"ENOENT"!==h(t)&&r(`Failed to read hook file ${e}: ${c(t)}`)}}e.length>0&&r(`Session environment loaded from ${e.length} hook file(s)`)}catch(t){"ENOENT"!==h(t)&&r(`Failed to load session environment from hooks: ${c(t)}`)}return 0===t.length?(r("No session environment scripts found"),f=null,f):(f=t.join("\n"),r(`Session environment script ready (${f.length} chars total)`),f)}const d={setup:0,sessionstart:1,cwdchanged:2,filechanged:3},m=/^(setup|sessionstart|cwdchanged|filechanged)-hook-(\d+)\.sh$/;function sortHookEnvFiles(t,o){const n=t.match(m),e=o.match(m),s=n?.[1]||"",i=e?.[1]||"";if(s!==i)return(d[s]??99)-(d[i]??99);return parseInt(n?.[2]||"0",10)-parseInt(e?.[2]||"0",10)}
@@ -1 +1 @@
1
- import{getSessionIngressToken as e,setSessionIngressToken as s}from"../bootstrap/state.js";import{CCR_SESSION_INGRESS_TOKEN_PATH as r,maybePersistTokenForSubprocesses as o,readTokenFromWellKnownFile as n}from"./authFileDescriptor.js";import{logForDebugging as t}from"./debug.js";import{errorMessage as E}from"./errors.js";import{getFsImplementation as S}from"./fsOperations.js";export function getSessionIngressAuthToken(){return(process.env.CONTEXT_CODE_SESSION_ACCESS_TOKEN??process.env.CLAUDE_CODE_SESSION_ACCESS_TOKEN)||function(){const i=e();if(void 0!==i)return i;const _=process.env.CONTEXT_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR??process.env.CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR;if(!_){const e=process.env.CONTEXT_SESSION_INGRESS_TOKEN_FILE??process.env.CLAUDE_SESSION_INGRESS_TOKEN_FILE??r,o=n(e,"session ingress token");return s(o),o}const O=parseInt(_,10);if(Number.isNaN(O))return t(`CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR must be a valid file descriptor number, got: ${_}`,{level:"error"}),s(null),null;try{const e=S(),n="darwin"===process.platform||"freebsd"===process.platform?`/dev/fd/${O}`:`/proc/self/fd/${O}`,E=e.readFileSync(n,{encoding:"utf8"}).trim();return E?(t(`Successfully read token from file descriptor ${O}`),s(E),o(r,E,"session ingress token"),E):(t("File descriptor contained empty token",{level:"error"}),s(null),null)}catch(e){t(`Failed to read token from file descriptor ${O}: ${E(e)}`,{level:"error"});const o=process.env.CONTEXT_SESSION_INGRESS_TOKEN_FILE??process.env.CLAUDE_SESSION_INGRESS_TOKEN_FILE??r,S=n(o,"session ingress token");return s(S),S}}()}export function getSessionIngressAuthHeaders(){const e=getSessionIngressAuthToken();if(!e)return{};if(e.startsWith("sk-ant-sid")){const s={Cookie:`sessionKey=${e}`},r=process.env.CONTEXT_CODE_ORGANIZATION_UUID??process.env.CLAUDE_CODE_ORGANIZATION_UUID;return r&&(s["X-Organization-Uuid"]=r),s}return{Authorization:`Bearer ${e}`}}export function updateSessionIngressAuthToken(e){process.env.CONTEXT_CODE_SESSION_ACCESS_TOKEN=e,process.env.CLAUDE_CODE_SESSION_ACCESS_TOKEN=e}
1
+ import{getSessionIngressToken as e,setSessionIngressToken as s}from"../bootstrap/state.js";import{CCR_SESSION_INGRESS_TOKEN_PATH as r,maybePersistTokenForSubprocesses as o,readTokenFromWellKnownFile as n}from"./authFileDescriptor.js";import{logForDebugging as t}from"./debug.js";import{errorMessage as E}from"./errors.js";import{getFsImplementation as i}from"./fsOperations.js";export function getSessionIngressAuthToken(){const _=process.env.CONTEXT_CODE_SESSION_ACCESS_TOKEN??process.env.CLAUDE_CODE_SESSION_ACCESS_TOKEN;return _||function(){const _=e();if(void 0!==_)return _;const S=process.env.CONTEXT_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR??process.env.CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR;if(!S){const e=process.env.CONTEXT_SESSION_INGRESS_TOKEN_FILE??process.env.CLAUDE_SESSION_INGRESS_TOKEN_FILE??r,o=n(e,"session ingress token");return s(o),o}const O=parseInt(S,10);if(Number.isNaN(O))return t(`CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR must be a valid file descriptor number, got: ${S}`,{level:"error"}),s(null),null;try{const e=i(),n="darwin"===process.platform||"freebsd"===process.platform?`/dev/fd/${O}`:`/proc/self/fd/${O}`,E=e.readFileSync(n,{encoding:"utf8"}).trim();return E?(t(`Successfully read token from file descriptor ${O}`),s(E),o(r,E,"session ingress token"),E):(t("File descriptor contained empty token",{level:"error"}),s(null),null)}catch(e){t(`Failed to read token from file descriptor ${O}: ${E(e)}`,{level:"error"});const o=process.env.CONTEXT_SESSION_INGRESS_TOKEN_FILE??process.env.CLAUDE_SESSION_INGRESS_TOKEN_FILE??r,i=n(o,"session ingress token");return s(i),i}}()}export function getSessionIngressAuthHeaders(){const e=getSessionIngressAuthToken();if(!e)return{};if(e.startsWith("sk-ant-sid")){const s={Cookie:`sessionKey=${e}`},r=process.env.CONTEXT_CODE_ORGANIZATION_UUID??process.env.CLAUDE_CODE_ORGANIZATION_UUID;return r&&(s["X-Organization-Uuid"]=r),s}return{Authorization:`Bearer ${e}`}}export function updateSessionIngressAuthToken(e){process.env.CONTEXT_CODE_SESSION_ACCESS_TOKEN=e,process.env.CLAUDE_CODE_SESSION_ACCESS_TOKEN=e}
@@ -1 +1 @@
1
- import{createRequire as e}from"module";const t=e(import.meta.url);import{feature as o}from"bun:bundle";import{dirname as s}from"path";import{getMainLoopModelOverride as n,getSessionId as r,setMainLoopModelOverride as i,setMainThreadAgentType as a,setOriginalCwd as m,switchSession as c}from"../bootstrap/state.js";import{clearSystemPromptSections as l}from"../constants/systemPromptSections.js";import{restoreCostStateForSession as p}from"../cost-tracker.js";import{getActiveAgentsFromList as d,getAgentDefinitionsWithOverrides as g}from"../tools/AgentTool/loadAgentsDir.js";import{TODO_WRITE_TOOL_NAME as f}from"../tools/TodoWriteTool/constants.js";import{asSessionId as u}from"../types/ids.js";import{renameRecordingForSession as S}from"./asciicast.js";import{clearMemoryFileCaches as h}from"./claudemd.js";import{attributionRestoreStateFromLog as C,restoreAttributionStateFromSnapshots as A}from"./commitAttribution.js";import{updateSessionName as T}from"./concurrentSessions.js";import{getCwd as y}from"./cwd.js";import{logForDebugging as O}from"./debug.js";import{fileHistoryRestoreStateFromLog as v}from"./fileHistory.js";import{createSystemMessage as R}from"./messages.js";import{parseUserSpecifiedModel as b}from"./model/model.js";import{getPlansDirectory as j}from"./plans.js";import{setCwd as D}from"./Shell.js";import{adoptResumedSessionFile as M,recordContentReplacement as w,resetSessionFilePointer as F,restoreSessionMetadata as x,saveMode as k,saveWorktreeState as I}from"./sessionStorage.js";import{isTodoV2Enabled as N}from"./tasks.js";import{TodoListSchema as E}from"./todo/types.js";import{getCurrentWorktreeSession as L,restoreWorktreeSession as _}from"./worktree.js";export function restoreSessionStateFromLog(e,s){if(e.fileHistorySnapshots&&e.fileHistorySnapshots.length>0&&v(e.fileHistorySnapshots,e=>{s(t=>({...t,fileHistory:e}))}),o("COMMIT_ATTRIBUTION")&&e.attributionSnapshots&&e.attributionSnapshots.length>0&&C(e.attributionSnapshots,e=>{s(t=>({...t,attribution:e}))}),o("CONTEXT_COLLAPSE")&&t("../services/contextCollapse/persist.js").restoreFromEntries(e.contextCollapseCommits??[],e.contextCollapseSnapshot),!N()&&e.messages&&e.messages.length>0){const t=function(e){for(let t=e.length-1;t>=0;t--){const o=e[t];if("assistant"!==o?.type)continue;const s=o.message.content.find(e=>"tool_use"===e.type&&e.name===f);if(!s||"tool_use"!==s.type)continue;const n=s.input;if(null===n||"object"!=typeof n)return[];const r=E().safeParse(n.todos);return r.success?r.data:[]}return[]}(e.messages);if(t.length>0){const e=r();s(o=>({...o,todos:{...o.todos,[e]:t}}))}}}export function computeRestoredAttributionState(e){if(o("COMMIT_ATTRIBUTION")&&e.attributionSnapshots&&e.attributionSnapshots.length>0)return A(e.attributionSnapshots)}export function computeStandaloneAgentContext(e,t){if(e||t)return{name:e??"",color:"default"===t?void 0:t}}export function restoreAgentFromSession(e,t,o){if(t)return{agentDefinition:t,agentType:void 0};if(!e)return a(void 0),{agentDefinition:void 0,agentType:void 0};const s=o.activeAgents.find(t=>t.agentType===e);return s?(a(s.agentType),!n()&&s.model&&"inherit"!==s.model&&i(b(s.model)),{agentDefinition:s,agentType:s.agentType}):(O(`Resumed session had agent "${e}" but it is no longer available. Using default behavior.`),a(void 0),{agentDefinition:void 0,agentType:void 0})}export async function refreshAgentDefinitionsForModeSwitch(e,t,s,n){if(!o("COORDINATOR_MODE")||!e)return n;g.cache.clear?.();const r=await g(t),i=[...r.allAgents,...s];return{...r,allAgents:i,activeAgents:d(i)}}export function restoreWorktreeForResume(e){const t=L();if(t)I(t);else if(e){try{process.chdir(e.worktreePath)}catch{return void I(null)}D(e.worktreePath),m(y()),_(e),h(),l(),j.cache.clear?.()}}export function exitRestoredWorktree(){const e=L();if(e){_(null),h(),l(),j.cache.clear?.();try{process.chdir(e.originalCwd)}catch{return}D(e.originalCwd),m(y())}}export async function processResumedConversation(e,n,r){let i;if(o("COORDINATOR_MODE")&&(i=r.modeApi?.matchSessionMode(e.mode),i&&e.messages.push(R(i,"warning"))),n.forkSession)e.contentReplacements?.length&&await w(e.contentReplacements);else{const t=n.sessionIdOverride??e.sessionId;t&&(c(u(t),n.transcriptPath?s(n.transcriptPath):null),await S(),await F(),p(t))}x(n.forkSession?{...e,worktreeSession:void 0}:e),n.forkSession||(restoreWorktreeForResume(e.worktreeSession),M()),o("CONTEXT_COLLAPSE")&&t("../services/contextCollapse/persist.js").restoreFromEntries(e.contextCollapseCommits??[],e.contextCollapseSnapshot);const{agentDefinition:a,agentType:m}=restoreAgentFromSession(e.agentSetting,r.mainThreadAgentDefinition,r.agentDefinitions);o("COORDINATOR_MODE")&&k(r.modeApi?.isCoordinatorMode()?"coordinator":"normal");const l=n.includeAttribution?computeRestoredAttributionState(e):void 0,d=computeStandaloneAgentContext(e.agentName,e.agentColor);T(e.agentName);const g=await refreshAgentDefinitionsForModeSwitch(!!i,r.currentCwd,r.cliAgents,r.agentDefinitions);return{messages:e.messages,fileHistorySnapshots:e.fileHistorySnapshots,contentReplacements:e.contentReplacements,agentName:e.agentName,agentColor:"default"===e.agentColor?void 0:e.agentColor,restoredAgentDef:a,initialState:{...r.initialState,...m&&{agent:m},...l&&{attribution:l},...d&&{standaloneAgentContext:d},agentDefinitions:g}}}
1
+ import{feature as t}from"../recovery/bunBundleShim.js";import{createRequire as e}from"module";const o=e(import.meta.url);import{dirname as n}from"path";import{getMainLoopModelOverride as s,getSessionId as i,setMainLoopModelOverride as r,setMainThreadAgentType as a,setOriginalCwd as m,switchSession as c}from"../bootstrap/state.js";import{clearSystemPromptSections as l}from"../constants/systemPromptSections.js";import{restoreCostStateForSession as p}from"../cost-tracker.js";import{getActiveAgentsFromList as f,getAgentDefinitionsWithOverrides as g}from"../tools/AgentTool/loadAgentsDir.js";import{TODO_WRITE_TOOL_NAME as u}from"../tools/TodoWriteTool/constants.js";import{asSessionId as d}from"../types/ids.js";import{renameRecordingForSession as h}from"./asciicast.js";import{clearMemoryFileCaches as S}from"./claudemd.js";import{attributionRestoreStateFromLog as A,restoreAttributionStateFromSnapshots as C}from"./commitAttribution.js";import{updateSessionName as y}from"./concurrentSessions.js";import{getCwd as T}from"./cwd.js";import{logForDebugging as j}from"./debug.js";import{fileHistoryRestoreStateFromLog as v}from"./fileHistory.js";import{createSystemMessage as O}from"./messages.js";import{parseUserSpecifiedModel as b}from"./model/model.js";import{getPlansDirectory as D}from"./plans.js";import{setCwd as R}from"./Shell.js";import{adoptResumedSessionFile as x,recordContentReplacement as w,resetSessionFilePointer as k,restoreSessionMetadata as I,saveMode as M,saveWorktreeState as N}from"./sessionStorage.js";import{isTodoV2Enabled as E}from"./tasks.js";import{TodoListSchema as F}from"./todo/types.js";import{getCurrentWorktreeSession as _,restoreWorktreeSession as P}from"./worktree.js";export function restoreSessionStateFromLog(e,n){if(e.fileHistorySnapshots&&e.fileHistorySnapshots.length>0&&v(e.fileHistorySnapshots,t=>{n(e=>({...e,fileHistory:t}))}),t("COMMIT_ATTRIBUTION")&&e.attributionSnapshots&&e.attributionSnapshots.length>0&&A(e.attributionSnapshots,t=>{n(e=>({...e,attribution:t}))}),t("CONTEXT_COLLAPSE")&&o("../services/contextCollapse/persist.js").restoreFromEntries(e.contextCollapseCommits??[],e.contextCollapseSnapshot),!E()&&e.messages&&e.messages.length>0){const t=function(t){for(let e=t.length-1;e>=0;e--){const o=t[e];if("assistant"!==o?.type)continue;const n=o.message.content.find(t=>"tool_use"===t.type&&t.name===u);if(!n||"tool_use"!==n.type)continue;const s=n.input;if(null===s||"object"!=typeof s)return[];const i=F().safeParse(s.todos);return i.success?i.data:[]}return[]}(e.messages);if(t.length>0){const e=i();n(o=>({...o,todos:{...o.todos,[e]:t}}))}}}export function computeRestoredAttributionState(e){if(t("COMMIT_ATTRIBUTION")&&e.attributionSnapshots&&e.attributionSnapshots.length>0)return C(e.attributionSnapshots)}export function computeStandaloneAgentContext(t,e){if(t||e)return{name:t??"",color:"default"===e?void 0:e}}export function restoreAgentFromSession(t,e,o){if(e)return{agentDefinition:e,agentType:void 0};if(!t)return a(void 0),{agentDefinition:void 0,agentType:void 0};const n=o.activeAgents.find(e=>e.agentType===t);return n?(a(n.agentType),!s()&&n.model&&"inherit"!==n.model&&r(b(n.model)),{agentDefinition:n,agentType:n.agentType}):(j(`Resumed session had agent "${t}" but it is no longer available. Using default behavior.`),a(void 0),{agentDefinition:void 0,agentType:void 0})}export async function refreshAgentDefinitionsForModeSwitch(e,o,n,s){if(!t("COORDINATOR_MODE")||!e)return s;g.cache.clear?.();const i=await g(o),r=[...i.allAgents,...n];return{...i,allAgents:r,activeAgents:f(r)}}export function restoreWorktreeForResume(t){const e=_();if(e)N(e);else if(t){try{process.chdir(t.worktreePath)}catch{return void N(null)}R(t.worktreePath),m(T()),P(t),S(),l(),D.cache.clear?.()}}export function exitRestoredWorktree(){const t=_();if(t){P(null),S(),l(),D.cache.clear?.();try{process.chdir(t.originalCwd)}catch{return}R(t.originalCwd),m(T())}}export async function processResumedConversation(e,s,i){let r;if(t("COORDINATOR_MODE")&&(r=i.modeApi?.matchSessionMode(e.mode),r&&e.messages.push(O(r,"warning"))),s.forkSession)e.contentReplacements?.length&&await w(e.contentReplacements);else{const t=s.sessionIdOverride??e.sessionId;t&&(c(d(t),s.transcriptPath?n(s.transcriptPath):null),await h(),await k(),p(t))}I(s.forkSession?{...e,worktreeSession:void 0}:e),s.forkSession||(restoreWorktreeForResume(e.worktreeSession),x()),t("CONTEXT_COLLAPSE")&&o("../services/contextCollapse/persist.js").restoreFromEntries(e.contextCollapseCommits??[],e.contextCollapseSnapshot);const{agentDefinition:a,agentType:m}=restoreAgentFromSession(e.agentSetting,i.mainThreadAgentDefinition,i.agentDefinitions);t("COORDINATOR_MODE")&&M(i.modeApi?.isCoordinatorMode()?"coordinator":"normal");const l=s.includeAttribution?computeRestoredAttributionState(e):void 0,f=computeStandaloneAgentContext(e.agentName,e.agentColor);y(e.agentName);const g=await refreshAgentDefinitionsForModeSwitch(!!r,i.currentCwd,i.cliAgents,i.agentDefinitions);return{messages:e.messages,fileHistorySnapshots:e.fileHistorySnapshots,contentReplacements:e.contentReplacements,agentName:e.agentName,agentColor:"default"===e.agentColor?void 0:e.agentColor,restoredAgentDef:a,initialState:{...i.initialState,...m&&{agent:m},...l&&{attribution:l},...f&&{standaloneAgentContext:f},agentDefinitions:g}}}
@@ -1 +1 @@
1
- import{getMainThreadAgentType as o}from"../bootstrap/state.js";import{createAttachmentMessage as e}from"./attachments.js";import{logForDebugging as s}from"./debug.js";import{withDiagnosticsTiming as t}from"./diagLogs.js";import{isBareMode as n}from"./envUtils.js";import{updateWatchPaths as i}from"./hooks/fileChangedWatcher.js";import{shouldAllowManagedHooksOnly as a}from"./hooks/hooksConfigSnapshot.js";import{executeSessionStartHooks as r,executeSetupHooks as l}from"./hooks.js";import{logError as c}from"./log.js";import{loadPluginHooks as u}from"./plugins/loadPluginHooks.js";let g;export function takeInitialUserMessage(){const o=g;return g=void 0,o}export async function processSessionStartHooks(l,{sessionId:d,agentType:p,model:h,forceSyncExecution:m}={}){if(n())return[];const k=[],f=[],S=[];if(a())s("Skipping plugin hooks - allowManagedHooksOnly is enabled");else try{await t("load_plugin_hooks",()=>u())}catch(o){const e=o instanceof Error?new Error(`Failed to load plugin hooks during ${l}: ${o.message}`):new Error(`Failed to load plugin hooks during ${l}: ${String(o)}`);o instanceof Error&&o.stack&&(e.stack=o.stack),c(e);const t=o instanceof Error?o.message:String(o);let n="";n=t.includes("Failed to clone")||t.includes("network")||t.includes("ETIMEDOUT")||t.includes("ENOTFOUND")?"This appears to be a network issue. Check your internet connection and try again.":t.includes("Permission denied")||t.includes("EACCES")||t.includes("EPERM")?"This appears to be a permissions issue. Check file permissions on ~/.context/plugins/":t.includes("Invalid")||t.includes("parse")||t.includes("JSON")||t.includes("schema")?"This appears to be a configuration issue. Check your plugin settings in .claude/settings.json":"Please fix the plugin configuration or remove problematic plugins from your settings.",s(`Warning: Failed to load plugin hooks. SessionStart hooks from plugins will not execute. Error: ${t}. ${n}`,{level:"warn"})}const E=p??o();for await(const o of r(l,d,E,h,void 0,void 0,m))o.message&&k.push(o.message),o.additionalContexts&&o.additionalContexts.length>0&&f.push(...o.additionalContexts),o.initialUserMessage&&(g=o.initialUserMessage),o.watchPaths&&o.watchPaths.length>0&&S.push(...o.watchPaths);if(S.length>0&&i(S),f.length>0){const o=e({type:"hook_additional_context",content:f,hookName:"SessionStart",toolUseID:"SessionStart",hookEvent:"SessionStart"});k.push(o)}return k}export async function processSetupHooks(o,{forceSyncExecution:t}={}){if(n())return[];const i=[],r=[];if(a())s("Skipping plugin hooks - allowManagedHooksOnly is enabled");else try{await u()}catch(o){const e=o instanceof Error?o.message:String(o);s(`Warning: Failed to load plugin hooks. Setup hooks from plugins will not execute. Error: ${e}`,{level:"warn"})}for await(const e of l(o,void 0,void 0,t))e.message&&i.push(e.message),e.additionalContexts&&e.additionalContexts.length>0&&r.push(...e.additionalContexts);if(r.length>0){const o=e({type:"hook_additional_context",content:r,hookName:"Setup",toolUseID:"Setup",hookEvent:"Setup"});i.push(o)}return i}
1
+ import{getMainThreadAgentType as o}from"../bootstrap/state.js";import{createAttachmentMessage as e}from"./attachments.js";import{logForDebugging as s}from"./debug.js";import{withDiagnosticsTiming as t}from"./diagLogs.js";import{isBareMode as n}from"./envUtils.js";import{updateWatchPaths as i}from"./hooks/fileChangedWatcher.js";import{shouldAllowManagedHooksOnly as a}from"./hooks/hooksConfigSnapshot.js";import{executeSessionStartHooks as r,executeSetupHooks as l}from"./hooks.js";import{logError as c}from"./log.js";import{loadPluginHooks as u}from"./plugins/loadPluginHooks.js";let p;export function takeInitialUserMessage(){const o=p;return p=void 0,o}export async function processSessionStartHooks(l,{sessionId:d,agentType:g,model:h,forceSyncExecution:m}={}){if(n())return[];const f=[],k=[],S=[];if(a())s("Skipping plugin hooks - allowManagedHooksOnly is enabled");else try{await t("load_plugin_hooks",()=>u())}catch(o){const e=o instanceof Error?new Error(`Failed to load plugin hooks during ${l}: ${o.message}`):new Error(`Failed to load plugin hooks during ${l}: ${String(o)}`);o instanceof Error&&o.stack&&(e.stack=o.stack),c(e);const t=o instanceof Error?o.message:String(o);let n="";n=t.includes("Failed to clone")||t.includes("network")||t.includes("ETIMEDOUT")||t.includes("ENOTFOUND")?"This appears to be a network issue. Check your internet connection and try again.":t.includes("Permission denied")||t.includes("EACCES")||t.includes("EPERM")?"This appears to be a permissions issue. Check file permissions on ~/.context/plugins/":t.includes("Invalid")||t.includes("parse")||t.includes("JSON")||t.includes("schema")?"This appears to be a configuration issue. Check your plugin settings in .claude/settings.json":"Please fix the plugin configuration or remove problematic plugins from your settings.",s(`Warning: Failed to load plugin hooks. SessionStart hooks from plugins will not execute. Error: ${t}. ${n}`,{level:"warn"})}const E=g??o();for await(const o of r(l,d,E,h,void 0,void 0,m))o.message&&f.push(o.message),o.additionalContexts&&o.additionalContexts.length>0&&k.push(...o.additionalContexts),o.initialUserMessage&&(p=o.initialUserMessage),o.watchPaths&&o.watchPaths.length>0&&S.push(...o.watchPaths);if(S.length>0&&i(S),k.length>0){const o=e({type:"hook_additional_context",content:k,hookName:"SessionStart",toolUseID:"SessionStart",hookEvent:"SessionStart"});f.push(o)}return f}export async function processSetupHooks(o,{forceSyncExecution:t}={}){if(n())return[];const i=[],r=[];if(a())s("Skipping plugin hooks - allowManagedHooksOnly is enabled");else try{await u()}catch(o){const e=o instanceof Error?o.message:String(o);s(`Warning: Failed to load plugin hooks. Setup hooks from plugins will not execute. Error: ${e}`,{level:"warn"})}for await(const e of l(o,void 0,void 0,t))e.message&&i.push(e.message),e.additionalContexts&&e.additionalContexts.length>0&&r.push(...e.additionalContexts);if(r.length>0){const o=e({type:"hook_additional_context",content:r,hookName:"Setup",toolUseID:"Setup",hookEvent:"Setup"});i.push(o)}return i}
@@ -1 +1 @@
1
- import{z as e}from"zod/v4";import{getIsNonInteractiveSession as t}from"../bootstrap/state.js";import{logEvent as s}from"../services/analytics/index.js";import{queryHaiku as n}from"../services/api/claude.js";import{logForDebugging as o}from"./debug.js";import{safeParseJSON as i}from"./json.js";import{lazySchema as r}from"./lazySchema.js";import{extractTextContent as a}from"./messages.js";import{asSystemPrompt as l}from"./systemPromptType.js";export function extractConversationText(e){const t=[];for(const s of e){if("user"!==s.type&&"assistant"!==s.type)continue;if("isMeta"in s&&s.isMeta)continue;if("origin"in s&&s.origin&&"human"!==s.origin.kind)continue;const e=s.message.content;if("string"==typeof e)t.push(e);else if(Array.isArray(e))for(const s of e)"type"in s&&"text"===s.type&&"text"in s&&t.push(s.text)}const s=t.join("\n");return s.length>1e3?s.slice(-1e3):s}const c=r(()=>e.object({title:e.string()}));export async function generateSessionTitle(e,r){const u=e.trim();if(!u)return null;try{const e=await n({systemPrompt:l(['Generate a concise, sentence-case title (3-7 words) that captures the main topic or goal of this coding session. The title should be clear enough that the user recognizes the session in a list. Use sentence case: capitalize only the first word and proper nouns.\n\nReturn JSON with a single "title" field.\n\nGood examples:\n{"title": "Fix login button on mobile"}\n{"title": "Add OAuth authentication"}\n{"title": "Debug failing CI tests"}\n{"title": "Refactor API client error handling"}\n\nBad (too vague): {"title": "Code changes"}\nBad (too long): {"title": "Investigate and fix the issue where the login button does not respond on mobile devices"}\nBad (wrong case): {"title": "Fix Login Button On Mobile"}']),userPrompt:u,outputFormat:{type:"json_schema",schema:{type:"object",properties:{title:{type:"string"}},required:["title"],additionalProperties:!1}},signal:r,options:{querySource:"generate_session_title",agents:[],isNonInteractiveSession:t(),hasAppendSystemPrompt:!1,mcpTools:[]}}),o=a(e.message.content),p=c().safeParse(i(o)),m=p.success&&p.data.title.trim()||null;return s("tengu_session_title_generated",{success:null!==m}),m}catch(e){return o(`generateSessionTitle failed: ${e}`,{level:"error"}),s("tengu_session_title_generated",{success:!1}),null}}
1
+ import{z as e}from"zod/v4";import{getIsNonInteractiveSession as t}from"../bootstrap/state.js";import{logEvent as n}from"../services/analytics/index.js";import{queryHaiku as s}from"../services/api/claude.js";import{logForDebugging as i}from"./debug.js";import{safeParseJSON as o}from"./json.js";import{lazySchema as r}from"./lazySchema.js";import{extractTextContent as a}from"./messages.js";import{asSystemPrompt as l}from"./systemPromptType.js";export function extractConversationText(e){const t=[];for(const n of e){if("user"!==n.type&&"assistant"!==n.type)continue;if("isMeta"in n&&n.isMeta)continue;if("origin"in n&&n.origin&&"human"!==n.origin.kind)continue;const e=n.message.content;if("string"==typeof e)t.push(e);else if(Array.isArray(e))for(const n of e)"type"in n&&"text"===n.type&&"text"in n&&t.push(n.text)}const n=t.join("\n");return n.length>1e3?n.slice(-1e3):n}const c=r(()=>e.object({title:e.string()}));export async function generateSessionTitle(e,r){const u=e.trim();if(!u)return null;try{const e=await s({systemPrompt:l(['Generate a concise, sentence-case title (3-7 words) that captures the main topic or goal of this coding session. The title should be clear enough that the user recognizes the session in a list. Use sentence case: capitalize only the first word and proper nouns.\n\nReturn JSON with a single "title" field.\n\nGood examples:\n{"title": "Fix login button on mobile"}\n{"title": "Add OAuth authentication"}\n{"title": "Debug failing CI tests"}\n{"title": "Refactor API client error handling"}\n\nBad (too vague): {"title": "Code changes"}\nBad (too long): {"title": "Investigate and fix the issue where the login button does not respond on mobile devices"}\nBad (wrong case): {"title": "Fix Login Button On Mobile"}']),userPrompt:u,outputFormat:{type:"json_schema",schema:{type:"object",properties:{title:{type:"string"}},required:["title"],additionalProperties:!1}},signal:r,options:{querySource:"generate_session_title",agents:[],isNonInteractiveSession:t(),hasAppendSystemPrompt:!1,mcpTools:[]}}),i=a(e.message.content),p=c().safeParse(o(i)),m=p.success&&p.data.title.trim()||null;return n("tengu_session_title_generated",{success:null!==m}),m}catch(e){return i(`generateSessionTitle failed: ${e}`,{level:"error"}),n("tengu_session_title_generated",{success:!1}),null}}
@@ -1 +1 @@
1
- import e from"lodash-es/memoize.js";import{join as t}from"path";import{getPlatform as o}from"../platform.js";export const getManagedFilePath=e(function(){if("ant"===process.env.USER_TYPE){const e=process.env.CONTEXT_CODE_MANAGED_SETTINGS_PATH??process.env.CLAUDE_CODE_MANAGED_SETTINGS_PATH;if(e)return e}switch(o()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}});export const getManagedSettingsDropInDir=e(function(){return t(getManagedFilePath(),"managed-settings.d")});
1
+ import e from"lodash-es/memoize.js";import{join as t}from"path";import{getPlatform as r}from"../platform.js";export const getManagedFilePath=e(function(){if("ant"===process.env.USER_TYPE){const e=process.env.CONTEXT_CODE_MANAGED_SETTINGS_PATH??process.env.CLAUDE_CODE_MANAGED_SETTINGS_PATH;if(e)return e}switch(r()){case"macos":return"/Library/Application Support/ClaudeCode";case"windows":return"C:\\Program Files\\ClaudeCode";default:return"/etc/claude-code"}});export const getManagedSettingsDropInDir=e(function(){return t(getManagedFilePath(),"managed-settings.d")});
@@ -1 +1 @@
1
- import{execFile as t}from"child_process";import{existsSync as e}from"fs";import{getMacOSPlistPaths as o,MDM_SUBPROCESS_TIMEOUT_MS as s,PLUTIL_ARGS_PREFIX as l,PLUTIL_PATH as r,WINDOWS_REGISTRY_KEY_PATH_HKCU as u,WINDOWS_REGISTRY_KEY_PATH_HKLM as a,WINDOWS_REGISTRY_VALUE_NAME as i}from"./constants.js";let n=null;function execFilePromise(e,o){return new Promise(l=>{t(e,o,{encoding:"utf-8",timeout:s},(t,e)=>{l({stdout:e??"",code:t?1:0})})})}export function fireRawRead(){return(async()=>{if("darwin"===process.platform){const t=o(),s=(await Promise.all(t.map(async({path:t,label:o})=>{if(!e(t))return{stdout:"",label:o,ok:!1};const{stdout:s,code:u}=await execFilePromise(r,[...l,t]);return{stdout:s,label:o,ok:0===u&&!!s}}))).find(t=>t.ok);return{plistStdouts:s?[{stdout:s.stdout,label:s.label}]:[],hklmStdout:null,hkcuStdout:null}}if("win32"===process.platform){const[t,e]=await Promise.all([execFilePromise("reg",["query",a,"/v",i]),execFilePromise("reg",["query",u,"/v",i])]);return{plistStdouts:null,hklmStdout:0===t.code?t.stdout:null,hkcuStdout:0===e.code?e.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}export function startMdmRawRead(){n||(n=fireRawRead())}export function getMdmRawReadPromise(){return n}
1
+ import{execFile as t}from"child_process";import{existsSync as e}from"fs";import{getMacOSPlistPaths as o,MDM_SUBPROCESS_TIMEOUT_MS as l,PLUTIL_ARGS_PREFIX as r,PLUTIL_PATH as u,WINDOWS_REGISTRY_KEY_PATH_HKCU as n,WINDOWS_REGISTRY_KEY_PATH_HKLM as s,WINDOWS_REGISTRY_VALUE_NAME as i}from"./constants.js";let d=null;function execFilePromise(e,o){return new Promise(r=>{t(e,o,{encoding:"utf-8",timeout:l},(t,e)=>{r({stdout:e??"",code:t?1:0})})})}export function fireRawRead(){return(async()=>{if("darwin"===process.platform){const t=o(),l=(await Promise.all(t.map(async({path:t,label:o})=>{if(!e(t))return{stdout:"",label:o,ok:!1};const{stdout:l,code:n}=await execFilePromise(u,[...r,t]);return{stdout:l,label:o,ok:0===n&&!!l}}))).find(t=>t.ok);return{plistStdouts:l?[{stdout:l.stdout,label:l.label}]:[],hklmStdout:null,hkcuStdout:null}}if("win32"===process.platform){const[t,e]=await Promise.all([execFilePromise("reg",["query",s,"/v",i]),execFilePromise("reg",["query",n,"/v",i])]);return{plistStdouts:null,hklmStdout:0===t.code?t.stdout:null,hkcuStdout:0===e.code?e.stdout:null}}return{plistStdouts:null,hklmStdout:null,hkcuStdout:null}})()}export function startMdmRawRead(){d||(d=fireRawRead())}export function getMdmRawReadPromise(){return d}
@@ -1 +1 @@
1
- import{join as t}from"path";import{logForDebugging as e}from"../../debug.js";import{logForDiagnosticsNoPII as s}from"../../diagLogs.js";import{readFileSync as n}from"../../fileRead.js";import{getFsImplementation as r}from"../../fsOperations.js";import{safeParseJSON as o}from"../../json.js";import{profileCheckpoint as i}from"../../startupProfiler.js";import{getManagedFilePath as a,getManagedSettingsDropInDir as u}from"../managedPath.js";import{SettingsSchema as c}from"../types.js";import{filterInvalidPermissionRules as m,formatZodError as d}from"../validation.js";import{WINDOWS_REGISTRY_KEY_PATH_HKCU as g,WINDOWS_REGISTRY_KEY_PATH_HKLM as f,WINDOWS_REGISTRY_VALUE_NAME as l}from"./constants.js";import{fireRawRead as p,getMdmRawReadPromise as S}from"./rawRead.js";const h=Object.freeze({settings:{},errors:[]});let R=null,j=null,y=null;export function startMdmSettingsLoad(){y||(y=(async()=>{i("mdm_load_start");const t=Date.now(),n=S()??p(),{mdm:r,hkcu:o}=consumeRawReadResult(await n);R=r,j=o,i("mdm_load_end");const a=Date.now()-t;if(e(`MDM settings load completed in ${a}ms`),Object.keys(r.settings).length>0){e(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{s("info","mdm_settings_loaded",{duration_ms:a,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})())}export async function ensureMdmSettingsLoaded(){y||startMdmSettingsLoad(),await y}export function getMdmSettings(){return R??h}export function getHkcuSettings(){return j??h}export function clearMdmSettingsCache(){R=null,j=null,y=null}export function setMdmSettingsCache(t,e){R=t,j=e}export async function refreshMdmSettings(){return consumeRawReadResult(await p())}export function parseCommandOutputAsSettings(t,e){const s=o(t,!1);if(!s||"object"!=typeof s)return{settings:{},errors:[]};const n=m(s,e),r=c().safeParse(s);if(!r.success){const t=d(r.error,e);return{settings:{},errors:[...n,...t]}}return{settings:r.data,errors:n}}export function parseRegQueryStdout(t,e="Settings"){const s=t.split(/\r?\n/),n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^\\s+${n}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(const t of s){const e=t.match(r);if(e&&e[1])return e[1].trimEnd()}return null}function consumeRawReadResult(e){if(e.plistStdouts&&e.plistStdouts.length>0){const{stdout:t,label:s}=e.plistStdouts[0],n=parseCommandOutputAsSettings(t,s);if(Object.keys(n.settings).length>0)return{mdm:n,hkcu:h}}if(e.hklmStdout){const t=parseRegQueryStdout(e.hklmStdout);if(t){const e=parseCommandOutputAsSettings(t,`Registry: ${f}\\${l}`);if(Object.keys(e.settings).length>0)return{mdm:e,hkcu:h}}}if(function(){try{const e=t(a(),"managed-settings.json"),s=n(e),r=o(s,!1);if(r&&"object"==typeof r&&Object.keys(r).length>0)return!0}catch{}try{const e=u(),s=r().readdirSync(e);for(const r of s)if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith("."))try{const s=n(t(e,r.name)),i=o(s,!1);if(i&&"object"==typeof i&&Object.keys(i).length>0)return!0}catch{}}catch{}return!1}())return{mdm:h,hkcu:h};if(e.hkcuStdout){const t=parseRegQueryStdout(e.hkcuStdout);if(t){const e=parseCommandOutputAsSettings(t,`Registry: ${g}\\${l}`);return{mdm:h,hkcu:e}}}return{mdm:h,hkcu:h}}
1
+ import{join as t}from"path";import{logForDebugging as e}from"../../debug.js";import{logForDiagnosticsNoPII as s}from"../../diagLogs.js";import{readFileSync as n}from"../../fileRead.js";import{getFsImplementation as r}from"../../fsOperations.js";import{safeParseJSON as o}from"../../json.js";import{profileCheckpoint as i}from"../../startupProfiler.js";import{getManagedFilePath as u,getManagedSettingsDropInDir as c}from"../managedPath.js";import{SettingsSchema as a}from"../types.js";import{filterInvalidPermissionRules as m,formatZodError as d}from"../validation.js";import{WINDOWS_REGISTRY_KEY_PATH_HKCU as f,WINDOWS_REGISTRY_KEY_PATH_HKLM as g,WINDOWS_REGISTRY_VALUE_NAME as l}from"./constants.js";import{fireRawRead as p,getMdmRawReadPromise as h}from"./rawRead.js";const j=Object.freeze({settings:{},errors:[]});let y=null,S=null,k=null;export function startMdmSettingsLoad(){k||(k=(async()=>{i("mdm_load_start");const t=Date.now(),n=h()??p(),{mdm:r,hkcu:o}=consumeRawReadResult(await n);y=r,S=o,i("mdm_load_end");const u=Date.now()-t;if(e(`MDM settings load completed in ${u}ms`),Object.keys(r.settings).length>0){e(`MDM settings found: ${Object.keys(r.settings).join(", ")}`);try{s("info","mdm_settings_loaded",{duration_ms:u,key_count:Object.keys(r.settings).length,error_count:r.errors.length})}catch{}}})())}export async function ensureMdmSettingsLoaded(){k||startMdmSettingsLoad(),await k}export function getMdmSettings(){return y??j}export function getHkcuSettings(){return S??j}export function clearMdmSettingsCache(){y=null,S=null,k=null}export function setMdmSettingsCache(t,e){y=t,S=e}export async function refreshMdmSettings(){return consumeRawReadResult(await p())}export function parseCommandOutputAsSettings(t,e){const s=o(t,!1);if(!s||"object"!=typeof s)return{settings:{},errors:[]};const n=m(s,e),r=a().safeParse(s);if(!r.success){const t=d(r.error,e);return{settings:{},errors:[...n,...t]}}return{settings:r.data,errors:n}}export function parseRegQueryStdout(t,e="Settings"){const s=t.split(/\r?\n/),n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^\\s+${n}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(const t of s){const e=t.match(r);if(e&&e[1])return e[1].trimEnd()}return null}function consumeRawReadResult(e){if(e.plistStdouts&&e.plistStdouts.length>0){const{stdout:t,label:s}=e.plistStdouts[0],n=parseCommandOutputAsSettings(t,s);if(Object.keys(n.settings).length>0)return{mdm:n,hkcu:j}}if(e.hklmStdout){const t=parseRegQueryStdout(e.hklmStdout);if(t){const e=parseCommandOutputAsSettings(t,`Registry: ${g}\\${l}`);if(Object.keys(e.settings).length>0)return{mdm:e,hkcu:j}}}if(function(){try{const e=t(u(),"managed-settings.json"),s=n(e),r=o(s,!1);if(r&&"object"==typeof r&&Object.keys(r).length>0)return!0}catch{}try{const e=c(),s=r().readdirSync(e);for(const r of s)if((r.isFile()||r.isSymbolicLink())&&r.name.endsWith(".json")&&!r.name.startsWith("."))try{const s=n(t(e,r.name)),i=o(s,!1);if(i&&"object"==typeof i&&Object.keys(i).length>0)return!0}catch{}}catch{}return!1}())return{mdm:j,hkcu:j};if(e.hkcuStdout){const t=parseRegQueryStdout(e.hkcuStdout);if(t){const e=parseCommandOutputAsSettings(t,`Registry: ${f}\\${l}`);return{mdm:j,hkcu:e}}}return{mdm:j,hkcu:j}}
@@ -1 +1 @@
1
- import{z as e}from"zod/v4";import{mcpInfoFromString as t}from"../../services/mcp/mcpStringUtils.js";import{lazySchema as r}from"../lazySchema.js";import{permissionRuleValueFromString as s}from"../permissions/permissionRuleParser.js";import{capitalize as o}from"../stringUtils.js";import{getCustomValidation as a,isBashPrefixTool as i,isFilePatternTool as n}from"./toolValidationConfig.js";function isEscaped(e,t){let r=0,s=t-1;for(;s>=0&&"\\"===e[s];)r++,s--;return r%2!=0}function countUnescapedChar(e,t){let r=0;for(let s=0;s<e.length;s++)e[s]!==t||isEscaped(e,s)||r++;return r}export function validatePermissionRule(e){if(!e||""===e.trim())return{valid:!1,error:"Permission rule cannot be empty"};if(countUnescapedChar(e,"(")!==countUnescapedChar(e,")"))return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(function(e){for(let t=0;t<e.length-1;t++)if("("===e[t]&&")"===e[t+1]&&!isEscaped(e,t))return!0;return!1}(e)){const t=e.substring(0,e.indexOf("("));return t?{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${t}" without parentheses`,examples:[`${t}`,`${t}(some-pattern)`]}:{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"}}const r=s(e),l=t(r.toolName);if(l)return void 0!==r.ruleContent||countUnescapedChar(e,"(")>0?{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${r.toolName}" without parentheses, or use "mcp__${l.serverName}__*" for all tools`,examples:[`mcp__${l.serverName}`,`mcp__${l.serverName}__*`,l.toolName&&"*"!==l.toolName?`mcp__${l.serverName}__${l.toolName}`:void 0].filter(Boolean)}:{valid:!0};if(!r.toolName||0===r.toolName.length)return{valid:!1,error:"Tool name cannot be empty"};if(r.toolName[0]!==r.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${o(String(r.toolName))}"`};const m=a(r.toolName);if(m&&void 0!==r.ruleContent){const e=m(r.ruleContent);if(!e.valid)return e}if(i(r.toolName)&&void 0!==r.ruleContent){const e=r.ruleContent;if(e.includes(":*")&&!e.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(":*"===e)return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm:*)","Bash(git:*)"]}}if(n(r.toolName)&&void 0!==r.ruleContent){const e=r.ruleContent;if(e.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${r.toolName}(*.ts) - matches .ts files`,`${r.toolName}(src/**) - matches all files in src`,`${r.toolName}(**/*.test.ts) - matches test files`]};if(e.includes("*")&&!e.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/)&&!e.includes("**"))return{valid:!1,error:"Wildcard placement might be incorrect",suggestion:"Wildcards are typically used at path boundaries",examples:[`${r.toolName}(*.js) - all .js files`,`${r.toolName}(src/*) - all files directly in src`,`${r.toolName}(src/**) - all files recursively in src`]}}return{valid:!0}}export const PermissionRuleSchema=r(()=>e.string().superRefine((t,r)=>{const s=validatePermissionRule(t);if(!s.valid){let o=s.error;s.suggestion&&(o+=`. ${s.suggestion}`),s.examples&&s.examples.length>0&&(o+=`. Examples: ${s.examples.join(", ")}`),r.addIssue({code:e.ZodIssueCode.custom,message:o,params:{received:t}})}}));
1
+ import{z as e}from"zod/v4";import{mcpInfoFromString as t}from"../../services/mcp/mcpStringUtils.js";import{lazySchema as r}from"../lazySchema.js";import{permissionRuleValueFromString as s}from"../permissions/permissionRuleParser.js";import{capitalize as o}from"../stringUtils.js";import{getCustomValidation as n,isBashPrefixTool as i,isFilePatternTool as a}from"./toolValidationConfig.js";function isEscaped(e,t){let r=0,s=t-1;for(;s>=0&&"\\"===e[s];)r++,s--;return r%2!=0}function countUnescapedChar(e,t){let r=0;for(let s=0;s<e.length;s++)e[s]!==t||isEscaped(e,s)||r++;return r}export function validatePermissionRule(e){if(!e||""===e.trim())return{valid:!1,error:"Permission rule cannot be empty"};if(countUnescapedChar(e,"(")!==countUnescapedChar(e,")"))return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(function(e){for(let t=0;t<e.length-1;t++)if("("===e[t]&&")"===e[t+1]&&!isEscaped(e,t))return!0;return!1}(e)){const t=e.substring(0,e.indexOf("("));return t?{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${t}" without parentheses`,examples:[`${t}`,`${t}(some-pattern)`]}:{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"}}const r=s(e),l=t(r.toolName);if(l)return void 0!==r.ruleContent||countUnescapedChar(e,"(")>0?{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${r.toolName}" without parentheses, or use "mcp__${l.serverName}__*" for all tools`,examples:[`mcp__${l.serverName}`,`mcp__${l.serverName}__*`,l.toolName&&"*"!==l.toolName?`mcp__${l.serverName}__${l.toolName}`:void 0].filter(Boolean)}:{valid:!0};if(!r.toolName||0===r.toolName.length)return{valid:!1,error:"Tool name cannot be empty"};if(r.toolName[0]!==r.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${o(String(r.toolName))}"`};const m=n(r.toolName);if(m&&void 0!==r.ruleContent){const e=m(r.ruleContent);if(!e.valid)return e}if(i(r.toolName)&&void 0!==r.ruleContent){const e=r.ruleContent;if(e.includes(":*")&&!e.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(":*"===e)return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm:*)","Bash(git:*)"]}}if(a(r.toolName)&&void 0!==r.ruleContent){const e=r.ruleContent;if(e.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${r.toolName}(*.ts) - matches .ts files`,`${r.toolName}(src/**) - matches all files in src`,`${r.toolName}(**/*.test.ts) - matches test files`]};if(e.includes("*")&&!e.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/)&&!e.includes("**"))return{valid:!1,error:"Wildcard placement might be incorrect",suggestion:"Wildcards are typically used at path boundaries",examples:[`${r.toolName}(*.js) - all .js files`,`${r.toolName}(src/*) - all files directly in src`,`${r.toolName}(src/**) - all files recursively in src`]}}return{valid:!0}}export const PermissionRuleSchema=r(()=>e.string().superRefine((t,r)=>{const s=validatePermissionRule(t);if(!s.valid){let o=s.error;s.suggestion&&(o+=`. ${s.suggestion}`),s.examples&&s.examples.length>0&&(o+=`. Examples: ${s.examples.join(", ")}`),r.addIssue({code:e.ZodIssueCode.custom,message:o,params:{received:t}})}}));
@@ -1 +1 @@
1
- import{getSettingsForSource as t}from"./settings.js";export function isRestrictedToPluginOnly(i){const n=t("policySettings")?.strictPluginOnlyCustomization;return!0===n||!!Array.isArray(n)&&n.includes(i)}const i=new Set(["plugin","policySettings","built-in","builtin","bundled"]);export function isSourceAdminTrusted(t){return void 0!==t&&i.has(t)}
1
+ import{getSettingsForSource as i}from"./settings.js";export function isRestrictedToPluginOnly(t){const n=i("policySettings")?.strictPluginOnlyCustomization;return!0===n||!!Array.isArray(n)&&n.includes(t)}const t=new Set(["plugin","policySettings","built-in","builtin","bundled"]);export function isSourceAdminTrusted(i){return void 0!==i&&t.has(i)}
@@ -1 +1 @@
1
- import{toJSONSchema as t}from"zod/v4";import{jsonStringify as e}from"../slowOperations.js";import{SettingsSchema as n}from"./types.js";export function generateSettingsJSONSchema(){const o=t(n(),{unrepresentable:"any"});return e(o,null,2)}
1
+ import{toJSONSchema as e}from"zod/v4";import{jsonStringify as r}from"../slowOperations.js";import{SettingsSchema as t}from"./types.js";export function generateSettingsJSONSchema(){const o=e(t(),{unrepresentable:"any"});return r(o,null,2)}
@@ -1 +1 @@
1
- import{feature as t}from"bun:bundle";import e from"lodash-es/mergeWith.js";import{dirname as s,join as n,resolve as o}from"path";import{z as r}from"zod/v4";import{getFlagSettingsInline as i,getFlagSettingsPath as a,getOriginalCwd as g,getUseCoworkPlugins as c}from"../../bootstrap/state.js";import{getRemoteManagedSettingsSyncFromCache as l}from"../../services/remoteManagedSettings/syncCacheState.js";import{uniq as u}from"../array.js";import{logForDebugging as S}from"../debug.js";import{logForDiagnosticsNoPII as f}from"../diagLogs.js";import{getClaudeConfigHomeDir as d,isEnvTruthy as p}from"../envUtils.js";import{getErrnoCode as m,isENOENT as h}from"../errors.js";import{writeFileSyncAndFlush_DEPRECATED as F}from"../file.js";import{readFileSync as P}from"../fileRead.js";import{getFsImplementation as y,safeResolvePath as j}from"../fsOperations.js";import{addFileGlobRuleToGitignore as k}from"../git/gitignore.js";import{safeParseJSON as C}from"../json.js";import{logError as b}from"../log.js";import{getPlatform as M}from"../platform.js";import{clone as E,jsonStringify as R}from"../slowOperations.js";import{profileCheckpoint as x}from"../startupProfiler.js";import{getEnabledSettingSources as v}from"./constants.js";import{markInternalWrite as O}from"./internalWrites.js";import{getManagedFilePath as A,getManagedSettingsDropInDir as I}from"./managedPath.js";import{getHkcuSettings as w,getMdmSettings as D}from"./mdm/settings.js";import{getCachedParsedFile as _,getCachedSettingsForSource as T,getPluginSettingsBase as N,getSessionSettingsCache as U,resetSettingsCache as $,setCachedParsedFile as W,setCachedSettingsForSource as z,setSessionSettingsCache as L}from"./settingsCache.js";import{SettingsSchema as B}from"./types.js";import{filterInvalidPermissionRules as G,formatZodError as K}from"./validation.js";function getManagedSettingsFilePath(){return n(A(),"managed-settings.json")}export function loadManagedFileSettings(){const t=[];let s={},o=!1;const{settings:r,errors:i}=parseSettingsFile(getManagedSettingsFilePath());t.push(...i),r&&Object.keys(r).length>0&&(s=e(s,r,settingsMergeCustomizer),o=!0);const a=I();try{const r=y().readdirSync(a).filter(t=>(t.isFile()||t.isSymbolicLink())&&t.name.endsWith(".json")&&!t.name.startsWith(".")).map(t=>t.name).sort();for(const i of r){const{settings:r,errors:g}=parseSettingsFile(n(a,i));t.push(...g),r&&Object.keys(r).length>0&&(s=e(s,r,settingsMergeCustomizer),o=!0)}}catch(t){const e=m(t);"ENOENT"!==e&&"ENOTDIR"!==e&&b(t)}return{settings:o?s:null,errors:t}}export function getManagedFileSettingsPresence(){const{settings:t}=parseSettingsFile(getManagedSettingsFilePath()),e=!!t&&Object.keys(t).length>0;let s=!1;const n=I();try{s=y().readdirSync(n).some(t=>(t.isFile()||t.isSymbolicLink())&&t.name.endsWith(".json")&&!t.name.startsWith("."))}catch{}return{hasBase:e,hasDropIns:s}}function handleFileSystemError(t,e){"object"==typeof t&&t&&"code"in t&&"ENOENT"===t.code?S(`Broken symlink or missing file encountered for settings.json at path: ${e}`):b(t)}export function parseSettingsFile(t){const e=_(t);if(e)return{settings:e.settings?E(e.settings):null,errors:e.errors};const s=function(t){try{const{resolvedPath:e}=j(y(),t),s=P(e);if(""===s.trim())return{settings:{},errors:[]};const n=C(s,!1),o=G(n,t),r=B().safeParse(n);if(!r.success){const e=K(r.error,t);return{settings:null,errors:[...o,...e]}}return{settings:r.data,errors:o}}catch(e){return handleFileSystemError(e,t),{settings:null,errors:[]}}}(t);return W(t,s),{settings:s.settings?E(s.settings):null,errors:s.errors}}export function getSettingsRootPathForSource(t){switch(t){case"userSettings":return o(d());case"policySettings":case"projectSettings":case"localSettings":return o(g());case"flagSettings":{const t=a();return t?s(o(t)):o(g())}}}export function getSettingsFilePathForSource(t){switch(t){case"userSettings":return n(getSettingsRootPathForSource(t),c()||p(process.env.CONTEXT_CODE_USE_COWORK_PLUGINS)||p(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS)?"cowork_settings.json":"settings.json");case"projectSettings":case"localSettings":{const e=getSettingsRootPathForSource(t),s=n(e,getPreferredRelativeSettingsFilePathForSource(t)),o=n(e,getRelativeSettingsFilePathForSource(t)),r=y();return r.existsSync(s)?s:r.existsSync(o)?o:s}case"policySettings":return getManagedSettingsFilePath();case"flagSettings":return a()}}export function getRelativeSettingsFilePathForSource(t){switch(t){case"projectSettings":return n(".claude","settings.json");case"localSettings":return n(".claude","settings.local.json")}}export function getPreferredRelativeSettingsFilePathForSource(t){switch(t){case"projectSettings":return n(".context","settings.json");case"localSettings":return n(".context","settings.local.json")}}export function getProjectRelativeSettingsPathForDisplay(t){const e=getPreferredRelativeSettingsFilePathForSource(t),s=getRelativeSettingsFilePathForSource(t),o=getSettingsRootPathForSource(t),r=y();return r.existsSync(n(o,e))?e:r.existsSync(n(o,s))?s:e}export function getSettingsForSource(t){const e=T(t);if(void 0!==e)return e;const s=getSettingsForSourceUncached(t);return z(t,s),s}function getSettingsForSourceUncached(t){if("policySettings"===t){const t=l();if(t&&Object.keys(t).length>0)return t;const e=D();if(Object.keys(e.settings).length>0)return e.settings;const{settings:s}=loadManagedFileSettings();if(s)return s;const n=w();return Object.keys(n.settings).length>0?n.settings:null}const s=getSettingsFilePathForSource(t),{settings:n}=s?parseSettingsFile(s):{settings:null};if("flagSettings"===t){const t=i();if(t){const s=B().safeParse(t);if(s.success)return e(n||{},s.data,settingsMergeCustomizer)}}return n}export function getPolicySettingsOrigin(){const t=l();if(t&&Object.keys(t).length>0)return"remote";const e=D();if(Object.keys(e.settings).length>0)return"macos"===M()?"plist":"hklm";const{settings:s}=loadManagedFileSettings();if(s)return"file";const n=w();return Object.keys(n.settings).length>0?"hkcu":null}export function updateSettingsForSource(t,n){if("policySettings"===t||"flagSettings"===t)return{error:null};const o=getSettingsFilePathForSource(t);if(!o)return{error:null};try{y().mkdirSync(s(o));let r=getSettingsForSourceUncached(t);if(!r){let e=null;try{e=P(o)}catch(t){if(!h(t))throw t}if(null!==e){const t=C(e);if(null===t)return{error:new Error(`Invalid JSON syntax in settings file at ${o}`)};t&&"object"==typeof t&&(r=t,S(`Using raw settings from ${o} due to validation failure`))}}const i=e(r||{},n,(t,e,s,n)=>{if(void 0!==e||!n||"string"!=typeof s)return Array.isArray(e)?e:void 0;delete n[s]});O(o),F(o,R(i,null,2)+"\n"),$(),"localSettings"===t&&(k(getRelativeSettingsFilePathForSource("localSettings"),g()),k(getPreferredRelativeSettingsFilePathForSource("localSettings"),g()))}catch(t){const e=new Error(`Failed to read raw settings from ${o}: ${t}`);return b(e),{error:e}}return{error:null}}export function settingsMergeCustomizer(t,e){if(Array.isArray(t)&&Array.isArray(e))return s=t,n=e,u([...s,...n]);var s,n}export function getManagedSettingsKeysForLogging(e){const s=B().strip().parse(e),n=["permissions","sandbox","hooks"],o=[],r={permissions:new Set(["allow","deny","ask","defaultMode","disableBypassPermissionsMode",...t("TRANSCRIPT_CLASSIFIER")?["disableAutoMode"]:[],"additionalDirectories"]),sandbox:new Set(["enabled","failIfUnavailable","allowUnsandboxedCommands","network","filesystem","ignoreViolations","excludedCommands","autoAllowBashIfSandboxed","enableWeakerNestedSandbox","enableWeakerNetworkIsolation","ripgrep"]),hooks:new Set(["PreToolUse","PostToolUse","Notification","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","PreCompact","PostCompact","TeammateIdle","TaskCreated","TaskCompleted"])};for(const t of Object.keys(s))if(n.includes(t)&&s[t]&&"object"==typeof s[t]){const e=s[t],n=r[t];if(n)for(const s of Object.keys(e))n.has(s)&&o.push(`${t}.${s}`)}else o.push(t);return o.sort()}let H=!1;export function getInitialSettings(){const{settings:t}=getSettingsWithErrors();return t||{}}export const getSettings_DEPRECATED=getInitialSettings;export function getSettingsWithSources(){$();const t=[];for(const e of v()){const s=getSettingsForSource(e);s&&Object.keys(s).length>0&&t.push({source:e,settings:s})}return{effective:getInitialSettings(),sources:t}}export function getSettingsWithErrors(){const t=U();if(null!==t)return t;const s=function(){if(H)return{settings:{},errors:[]};const t=Date.now();x("loadSettingsFromDisk_start"),f("info","settings_load_started"),H=!0;try{const s=N();let n={};s&&(n=e(n,s,settingsMergeCustomizer));const r=[],a=new Set,g=new Set;for(const t of v()){if("policySettings"===t){let t=null;const s=[],o=l();if(o&&Object.keys(o).length>0){const e=B().safeParse(o);e.success?t=e.data:s.push(...K(e.error,"remote managed settings"))}if(!t){const e=D();Object.keys(e.settings).length>0&&(t=e.settings),s.push(...e.errors)}if(!t){const{settings:e,errors:n}=loadManagedFileSettings();e&&(t=e),s.push(...n)}if(!t){const e=w();Object.keys(e.settings).length>0&&(t=e.settings),s.push(...e.errors)}t&&(n=e(n,t,settingsMergeCustomizer));for(const t of s){const e=`${t.file}:${t.path}:${t.message}`;a.has(e)||(a.add(e),r.push(t))}continue}const s=getSettingsFilePathForSource(t);if(s){const t=o(s);if(!g.has(t)){g.add(t);const{settings:o,errors:i}=parseSettingsFile(s);for(const t of i){const e=`${t.file}:${t.path}:${t.message}`;a.has(e)||(a.add(e),r.push(t))}o&&(n=e(n,o,settingsMergeCustomizer))}}if("flagSettings"===t){const t=i();if(t){const s=B().safeParse(t);s.success&&(n=e(n,s.data,settingsMergeCustomizer))}}}return f("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:g.size,error_count:r.length}),{settings:n,errors:r}}finally{H=!1}}();return x("loadSettingsFromDisk_end"),L(s),s}export function hasSkipDangerousModePermissionPrompt(){return!!(getSettingsForSource("userSettings")?.skipDangerousModePermissionPrompt||getSettingsForSource("localSettings")?.skipDangerousModePermissionPrompt||getSettingsForSource("flagSettings")?.skipDangerousModePermissionPrompt||getSettingsForSource("policySettings")?.skipDangerousModePermissionPrompt)}export function hasAutoModeOptIn(){if(t("TRANSCRIPT_CLASSIFIER")){const t=getSettingsForSource("userSettings")?.skipAutoPermissionPrompt,e=getSettingsForSource("localSettings")?.skipAutoPermissionPrompt,s=getSettingsForSource("flagSettings")?.skipAutoPermissionPrompt,n=getSettingsForSource("policySettings")?.skipAutoPermissionPrompt,o=!!(t||e||s||n);return S(`[auto-mode] hasAutoModeOptIn=${o} skipAutoPermissionPrompt: user=${t} local=${e} flag=${s} policy=${n}`),o}return!1}export function getUseAutoModeDuringPlan(){return!t("TRANSCRIPT_CLASSIFIER")||!1!==getSettingsForSource("policySettings")?.useAutoModeDuringPlan&&!1!==getSettingsForSource("flagSettings")?.useAutoModeDuringPlan&&!1!==getSettingsForSource("userSettings")?.useAutoModeDuringPlan&&!1!==getSettingsForSource("localSettings")?.useAutoModeDuringPlan}export function getAutoModeConfig(){if(t("TRANSCRIPT_CLASSIFIER")){const t=r.object({allow:r.array(r.string()).optional(),soft_deny:r.array(r.string()).optional(),deny:r.array(r.string()).optional(),environment:r.array(r.string()).optional()}),e=[],s=[],n=[];for(const o of["userSettings","localSettings","flagSettings","policySettings"]){const r=getSettingsForSource(o);if(!r)continue;const i=t.safeParse(r.autoMode);i.success&&(i.data.allow&&e.push(...i.data.allow),i.data.soft_deny&&s.push(...i.data.soft_deny),"ant"===process.env.USER_TYPE&&i.data.deny&&s.push(...i.data.deny),i.data.environment&&n.push(...i.data.environment))}if(e.length>0||s.length>0||n.length>0)return{...e.length>0&&{allow:e},...s.length>0&&{soft_deny:s},...n.length>0&&{environment:n}}}}export function rawSettingsContainsKey(t){for(const e of v()){if("policySettings"===e)continue;const s=getSettingsFilePathForSource(e);if(s)try{const{resolvedPath:e}=j(y(),s),n=P(e);if(!n.trim())continue;const o=C(n,!1);if(o&&"object"==typeof o&&t in o)return!0}catch(t){handleFileSystemError(t,s)}}return!1}
1
+ import{feature as t}from"../../recovery/bunBundleShim.js";import e from"lodash-es/mergeWith.js";import{dirname as s,join as n,resolve as o}from"path";import{z as r}from"zod/v4";import{getFlagSettingsInline as i,getFlagSettingsPath as a,getOriginalCwd as g,getUseCoworkPlugins as c}from"../../bootstrap/state.js";import{getRemoteManagedSettingsSyncFromCache as l}from"../../services/remoteManagedSettings/syncCacheState.js";import{uniq as u}from"../array.js";import{logForDebugging as S}from"../debug.js";import{logForDiagnosticsNoPII as f}from"../diagLogs.js";import{getClaudeConfigHomeDir as p,isEnvTruthy as m}from"../envUtils.js";import{getErrnoCode as d,isENOENT as h}from"../errors.js";import{writeFileSyncAndFlush_DEPRECATED as y}from"../file.js";import{readFileSync as F}from"../fileRead.js";import{getFsImplementation as P,safeResolvePath as j}from"../fsOperations.js";import{addFileGlobRuleToGitignore as k}from"../git/gitignore.js";import{safeParseJSON as b}from"../json.js";import{logError as M}from"../log.js";import{getPlatform as x}from"../platform.js";import{clone as C,jsonStringify as v}from"../slowOperations.js";import{profileCheckpoint as A}from"../startupProfiler.js";import{getEnabledSettingSources as O}from"./constants.js";import{markInternalWrite as R}from"./internalWrites.js";import{getManagedFilePath as w,getManagedSettingsDropInDir as E}from"./managedPath.js";import{getHkcuSettings as _,getMdmSettings as I}from"./mdm/settings.js";import{getCachedParsedFile as D,getCachedSettingsForSource as T,getPluginSettingsBase as $,getSessionSettingsCache as U,resetSettingsCache as N,setCachedParsedFile as W,setCachedSettingsForSource as L,setSessionSettingsCache as z}from"./settingsCache.js";import{SettingsSchema as B}from"./types.js";import{filterInvalidPermissionRules as K,formatZodError as G}from"./validation.js";function getManagedSettingsFilePath(){return n(w(),"managed-settings.json")}export function loadManagedFileSettings(){const t=[];let s={},o=!1;const{settings:r,errors:i}=parseSettingsFile(getManagedSettingsFilePath());t.push(...i),r&&Object.keys(r).length>0&&(s=e(s,r,settingsMergeCustomizer),o=!0);const a=E();try{const r=P().readdirSync(a).filter(t=>(t.isFile()||t.isSymbolicLink())&&t.name.endsWith(".json")&&!t.name.startsWith(".")).map(t=>t.name).sort();for(const i of r){const{settings:r,errors:g}=parseSettingsFile(n(a,i));t.push(...g),r&&Object.keys(r).length>0&&(s=e(s,r,settingsMergeCustomizer),o=!0)}}catch(t){const e=d(t);"ENOENT"!==e&&"ENOTDIR"!==e&&M(t)}return{settings:o?s:null,errors:t}}export function getManagedFileSettingsPresence(){const{settings:t}=parseSettingsFile(getManagedSettingsFilePath()),e=!!t&&Object.keys(t).length>0;let s=!1;const n=E();try{s=P().readdirSync(n).some(t=>(t.isFile()||t.isSymbolicLink())&&t.name.endsWith(".json")&&!t.name.startsWith("."))}catch{}return{hasBase:e,hasDropIns:s}}function handleFileSystemError(t,e){"object"==typeof t&&t&&"code"in t&&"ENOENT"===t.code?S(`Broken symlink or missing file encountered for settings.json at path: ${e}`):M(t)}export function parseSettingsFile(t){const e=D(t);if(e)return{settings:e.settings?C(e.settings):null,errors:e.errors};const s=function(t){try{const{resolvedPath:e}=j(P(),t),s=F(e);if(""===s.trim())return{settings:{},errors:[]};const n=b(s,!1),o=K(n,t),r=B().safeParse(n);if(!r.success){const e=G(r.error,t);return{settings:null,errors:[...o,...e]}}return{settings:r.data,errors:o}}catch(e){return handleFileSystemError(e,t),{settings:null,errors:[]}}}(t);return W(t,s),{settings:s.settings?C(s.settings):null,errors:s.errors}}export function getSettingsRootPathForSource(t){switch(t){case"userSettings":return o(p());case"policySettings":case"projectSettings":case"localSettings":return o(g());case"flagSettings":{const t=a();return t?s(o(t)):o(g())}}}export function getSettingsFilePathForSource(t){switch(t){case"userSettings":return n(getSettingsRootPathForSource(t),c()||m(process.env.CONTEXT_CODE_USE_COWORK_PLUGINS)||m(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS)?"cowork_settings.json":"settings.json");case"projectSettings":case"localSettings":{const e=getSettingsRootPathForSource(t),s=n(e,getPreferredRelativeSettingsFilePathForSource(t)),o=n(e,getRelativeSettingsFilePathForSource(t)),r=P();return r.existsSync(s)?s:r.existsSync(o)?o:s}case"policySettings":return getManagedSettingsFilePath();case"flagSettings":return a()}}export function getRelativeSettingsFilePathForSource(t){switch(t){case"projectSettings":return n(".claude","settings.json");case"localSettings":return n(".claude","settings.local.json")}}export function getPreferredRelativeSettingsFilePathForSource(t){switch(t){case"projectSettings":return n(".context","settings.json");case"localSettings":return n(".context","settings.local.json")}}export function getProjectRelativeSettingsPathForDisplay(t){const e=getPreferredRelativeSettingsFilePathForSource(t),s=getRelativeSettingsFilePathForSource(t),o=getSettingsRootPathForSource(t),r=P();return r.existsSync(n(o,e))?e:r.existsSync(n(o,s))?s:e}export function getSettingsForSource(t){const e=T(t);if(void 0!==e)return e;const s=getSettingsForSourceUncached(t);return L(t,s),s}function getSettingsForSourceUncached(t){if("policySettings"===t){const t=l();if(t&&Object.keys(t).length>0)return t;const e=I();if(Object.keys(e.settings).length>0)return e.settings;const{settings:s}=loadManagedFileSettings();if(s)return s;const n=_();return Object.keys(n.settings).length>0?n.settings:null}const s=getSettingsFilePathForSource(t),{settings:n}=s?parseSettingsFile(s):{settings:null};if("flagSettings"===t){const t=i();if(t){const s=B().safeParse(t);if(s.success)return e(n||{},s.data,settingsMergeCustomizer)}}return n}export function getPolicySettingsOrigin(){const t=l();if(t&&Object.keys(t).length>0)return"remote";const e=I();if(Object.keys(e.settings).length>0)return"macos"===x()?"plist":"hklm";const{settings:s}=loadManagedFileSettings();if(s)return"file";const n=_();return Object.keys(n.settings).length>0?"hkcu":null}export function updateSettingsForSource(t,n){if("policySettings"===t||"flagSettings"===t)return{error:null};const o=getSettingsFilePathForSource(t);if(!o)return{error:null};try{P().mkdirSync(s(o));let r=getSettingsForSourceUncached(t);if(!r){let t=null;try{t=F(o)}catch(t){if(!h(t))throw t}if(null!==t){const e=b(t);if(null===e)return{error:new Error(`Invalid JSON syntax in settings file at ${o}`)};e&&"object"==typeof e&&(r=e,S(`Using raw settings from ${o} due to validation failure`))}}const i=e(r||{},n,(t,e,s,n)=>{if(void 0!==e||!n||"string"!=typeof s)return Array.isArray(e)?e:void 0;delete n[s]});R(o),y(o,v(i,null,2)+"\n"),N(),"localSettings"===t&&(k(getRelativeSettingsFilePathForSource("localSettings"),g()),k(getPreferredRelativeSettingsFilePathForSource("localSettings"),g()))}catch(t){const e=new Error(`Failed to read raw settings from ${o}: ${t}`);return M(e),{error:e}}return{error:null}}export function settingsMergeCustomizer(t,e){if(Array.isArray(t)&&Array.isArray(e))return s=t,n=e,u([...s,...n]);var s,n}export function getManagedSettingsKeysForLogging(e){const s=B().strip().parse(e),n=["permissions","sandbox","hooks"],o=[],r={permissions:new Set(["allow","deny","ask","defaultMode","disableBypassPermissionsMode",...t("TRANSCRIPT_CLASSIFIER")?["disableAutoMode"]:[],"additionalDirectories"]),sandbox:new Set(["enabled","failIfUnavailable","allowUnsandboxedCommands","network","filesystem","ignoreViolations","excludedCommands","autoAllowBashIfSandboxed","enableWeakerNestedSandbox","enableWeakerNetworkIsolation","ripgrep"]),hooks:new Set(["PreToolUse","PostToolUse","Notification","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","PreCompact","PostCompact","TeammateIdle","TaskCreated","TaskCompleted"])};for(const t of Object.keys(s))if(n.includes(t)&&s[t]&&"object"==typeof s[t]){const e=s[t],n=r[t];if(n)for(const s of Object.keys(e))n.has(s)&&o.push(`${t}.${s}`)}else o.push(t);return o.sort()}let J=!1;export function getInitialSettings(){const{settings:t}=getSettingsWithErrors();return t||{}}export const getSettings_DEPRECATED=getInitialSettings;export function getSettingsWithSources(){N();const t=[];for(const e of O()){const s=getSettingsForSource(e);s&&Object.keys(s).length>0&&t.push({source:e,settings:s})}return{effective:getInitialSettings(),sources:t}}export function getSettingsWithErrors(){const t=U();if(null!==t)return t;const s=function(){if(J)return{settings:{},errors:[]};const t=Date.now();A("loadSettingsFromDisk_start"),f("info","settings_load_started"),J=!0;try{const s=$();let n={};s&&(n=e(n,s,settingsMergeCustomizer));const r=[],a=new Set,g=new Set;for(const t of O()){if("policySettings"===t){let t=null;const s=[],o=l();if(o&&Object.keys(o).length>0){const e=B().safeParse(o);e.success?t=e.data:s.push(...G(e.error,"remote managed settings"))}if(!t){const e=I();Object.keys(e.settings).length>0&&(t=e.settings),s.push(...e.errors)}if(!t){const{settings:e,errors:n}=loadManagedFileSettings();e&&(t=e),s.push(...n)}if(!t){const e=_();Object.keys(e.settings).length>0&&(t=e.settings),s.push(...e.errors)}t&&(n=e(n,t,settingsMergeCustomizer));for(const t of s){const e=`${t.file}:${t.path}:${t.message}`;a.has(e)||(a.add(e),r.push(t))}continue}const s=getSettingsFilePathForSource(t);if(s){const t=o(s);if(!g.has(t)){g.add(t);const{settings:o,errors:i}=parseSettingsFile(s);for(const t of i){const e=`${t.file}:${t.path}:${t.message}`;a.has(e)||(a.add(e),r.push(t))}o&&(n=e(n,o,settingsMergeCustomizer))}}if("flagSettings"===t){const t=i();if(t){const s=B().safeParse(t);s.success&&(n=e(n,s.data,settingsMergeCustomizer))}}}return f("info","settings_load_completed",{duration_ms:Date.now()-t,source_count:g.size,error_count:r.length}),{settings:n,errors:r}}finally{J=!1}}();return A("loadSettingsFromDisk_end"),z(s),s}export function hasSkipDangerousModePermissionPrompt(){return!!(getSettingsForSource("userSettings")?.skipDangerousModePermissionPrompt||getSettingsForSource("localSettings")?.skipDangerousModePermissionPrompt||getSettingsForSource("flagSettings")?.skipDangerousModePermissionPrompt||getSettingsForSource("policySettings")?.skipDangerousModePermissionPrompt)}export function hasAutoModeOptIn(){if(t("TRANSCRIPT_CLASSIFIER")){const t=getSettingsForSource("userSettings")?.skipAutoPermissionPrompt,e=getSettingsForSource("localSettings")?.skipAutoPermissionPrompt,s=getSettingsForSource("flagSettings")?.skipAutoPermissionPrompt,n=getSettingsForSource("policySettings")?.skipAutoPermissionPrompt,o=!!(t||e||s||n);return S(`[auto-mode] hasAutoModeOptIn=${o} skipAutoPermissionPrompt: user=${t} local=${e} flag=${s} policy=${n}`),o}return!1}export function getUseAutoModeDuringPlan(){return!t("TRANSCRIPT_CLASSIFIER")||!1!==getSettingsForSource("policySettings")?.useAutoModeDuringPlan&&!1!==getSettingsForSource("flagSettings")?.useAutoModeDuringPlan&&!1!==getSettingsForSource("userSettings")?.useAutoModeDuringPlan&&!1!==getSettingsForSource("localSettings")?.useAutoModeDuringPlan}export function getAutoModeConfig(){if(t("TRANSCRIPT_CLASSIFIER")){const t=r.object({allow:r.array(r.string()).optional(),soft_deny:r.array(r.string()).optional(),deny:r.array(r.string()).optional(),environment:r.array(r.string()).optional()}),e=[],s=[],n=[];for(const o of["userSettings","localSettings","flagSettings","policySettings"]){const r=getSettingsForSource(o);if(!r)continue;const i=t.safeParse(r.autoMode);i.success&&(i.data.allow&&e.push(...i.data.allow),i.data.soft_deny&&s.push(...i.data.soft_deny),"ant"===process.env.USER_TYPE&&i.data.deny&&s.push(...i.data.deny),i.data.environment&&n.push(...i.data.environment))}if(e.length>0||s.length>0||n.length>0)return{...e.length>0&&{allow:e},...s.length>0&&{soft_deny:s},...n.length>0&&{environment:n}}}}export function rawSettingsContainsKey(t){for(const e of O()){if("policySettings"===e)continue;const s=getSettingsFilePathForSource(e);if(s)try{const{resolvedPath:e}=j(P(),s),n=F(e);if(!n.trim())continue;const o=b(n,!1);if(o&&"object"==typeof o&&t in o)return!0}catch(t){handleFileSystemError(t,s)}}return!1}
@@ -1 +1 @@
1
- import{feature as e}from"bun:bundle";import{z as o}from"zod/v4";import{SandboxSettingsSchema as t}from"../../entrypoints/sandboxTypes.js";import{isEnvTruthy as s}from"../envUtils.js";import{lazySchema as r}from"../lazySchema.js";import{EXTERNAL_PERMISSION_MODES as i,PERMISSION_MODES as a}from"../permissions/PermissionMode.js";import{MarketplaceSourceSchema as n}from"../plugins/schemas.js";import{CLAUDE_CODE_SETTINGS_SCHEMA_URL as l}from"./constants.js";import{PermissionRuleSchema as c}from"./permissionValidation.js";export{HookCommandSchema,HookMatcherSchema,HooksSchema}from"../../schemas/hooks.js";import{HooksSchema as d}from"../../schemas/hooks.js";import{count as p}from"../array.js";export const EnvironmentVariablesSchema=r(()=>o.record(o.string(),o.coerce.string()));export const PermissionsSchema=r(()=>o.object({allow:o.array(c()).optional().describe("List of permission rules for allowed operations"),deny:o.array(c()).optional().describe("List of permission rules for denied operations"),ask:o.array(c()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:o.enum(e("TRANSCRIPT_CLASSIFIER")?a:i).optional().describe("Default permission mode when Context Code needs access"),disableBypassPermissionsMode:o.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...e("TRANSCRIPT_CLASSIFIER")?{disableAutoMode:o.enum(["disable"]).optional().describe("Disable auto mode")}:{},additionalDirectories:o.array(o.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough());export const ExtraKnownMarketplaceSchema=r(()=>o.object({source:n().describe("Where to fetch the marketplace from"),installLocation:o.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:o.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")}));export const AllowedMcpServerEntrySchema=r(()=>o.object({serverName:o.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:o.array(o.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:o.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(e=>1===p([void 0!==e.serverName,void 0!==e.serverCommand,void 0!==e.serverUrl],Boolean),{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'}));export const DeniedMcpServerEntrySchema=r(()=>o.object({serverName:o.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:o.array(o.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:o.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(e=>1===p([void 0!==e.serverName,void 0!==e.serverCommand,void 0!==e.serverUrl],Boolean),{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'}));export const CUSTOMIZATION_SURFACES=["skills","agents","hooks","mcp"];export const SettingsSchema=r(()=>o.object({$schema:o.literal(l).optional().describe("JSON Schema reference for Context Code settings"),apiKeyHelper:o.string().optional().describe("Path to a script that outputs authentication values"),awsCredentialExport:o.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:o.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:o.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),...s(process.env.CONTEXT_CODE_ENABLE_XAA)||s(process.env.CLAUDE_CODE_ENABLE_XAA)?{xaaIdp:o.object({issuer:o.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:o.string().describe("Context Code's client_id registered at the IdP"),callbackPort:o.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")}:{},fileSuggestion:o.object({type:o.literal("command"),command:o.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:o.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),cleanupPeriodDays:o.number().nonnegative().int().optional().describe("Number of days to retain chat transcripts (default: 30). Setting to 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."),env:EnvironmentVariablesSchema().optional().describe("Environment variables to set for Context Code sessions"),attribution:o.object({commit:o.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:o.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Context Code attribution if not set."),includeCoAuthoredBy:o.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Context's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:o.boolean().optional().describe("Include built-in commit and PR workflow instructions in Context's system prompt (default: true)"),permissions:PermissionsSchema().optional().describe("Tool usage permissions configuration"),model:o.string().optional().describe("Override the default model used by Context Code"),availableModels:o.array(o.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),modelOverrides:o.record(o.string(),o.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:o.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:o.array(o.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:o.array(o.string()).optional().describe("List of rejected MCP servers from .mcp.json"),allowedMcpServers:o.array(AllowedMcpServerEntrySchema()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:o.array(DeniedMcpServerEntrySchema()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),hooks:d().optional().describe("Custom commands to run before/after tool executions"),worktree:o.object({symlinkDirectories:o.array(o.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:o.array(o.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). Dramatically faster in large monorepos — only the listed paths are written to disk.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:o.boolean().optional().describe("Disable all hooks and statusLine execution"),defaultShell:o.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:o.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:o.array(o.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:o.array(o.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:o.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:o.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),strictPluginOnlyCustomization:o.preprocess(e=>Array.isArray(e)?e.filter(e=>CUSTOMIZATION_SURFACES.includes(e)):e,o.union([o.boolean(),o.array(o.enum(CUSTOMIZATION_SURFACES))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.context/{surface}/, .context/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. Composes with strictKnownMarketplaces for end-to-end admin control — plugins gated by marketplace allowlist, everything else blocked here.'),statusLine:o.object({type:o.literal("command"),command:o.string(),padding:o.number().optional()}).optional().describe("Custom status line display configuration"),enabledPlugins:o.record(o.string(),o.union([o.array(o.string()),o.boolean(),o.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints.'),extraKnownMarketplaces:o.record(o.string(),ExtraKnownMarketplaceSchema()).check(e=>{for(const[o,t]of Object.entries(e.value))"settings"===t.source.source&&t.source.name!==o&&e.issues.push({code:"custom",input:t.source.name,path:[o,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${o}" but source.name "${t.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:o.array(n()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. Note: this is a policy gate only — it does NOT register marketplaces. To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:o.array(n()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),forceLoginMethod:o.enum(["claudeai","console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),forceLoginOrgUUID:o.string().optional().describe("Organization UUID to use for OAuth login"),otelHeadersHelper:o.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:o.string().optional().describe("Controls the output style for assistant responses"),language:o.string().optional().describe('Idioma preferido para las respuestas de Context y el dictado local (por ejemplo, "japanese", "spanish")'),skipWebFetchPreflight:o.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:t().optional(),feedbackSurveyRate:o.number().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:o.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:o.object({mode:o.enum(["append","replace"]),verbs:o.array(o.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:o.object({excludeDefault:o.boolean().optional(),tips:o.array(o.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:o.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:o.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:o.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:o.enum("ant"===process.env.USER_TYPE?["low","medium","high","max"]:["low","medium","high"]).optional().catch(void 0).describe("Persisted effort level for supported models."),advisorModel:o.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:o.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:o.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:o.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),showClearContextOnPlanAccept:o.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:o.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:o.array(o.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:o.record(o.string(),o.object({mcpServers:o.record(o.string(),o.record(o.string(),o.union([o.string(),o.number(),o.boolean(),o.array(o.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:o.record(o.string(),o.union([o.string(),o.number(),o.boolean(),o.array(o.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")})).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:o.object({defaultEnvironmentId:o.string().optional().describe("Default environment ID to use for remote sessions")}).optional().describe("Remote session configuration"),autoUpdatesChannel:o.enum(["latest","stable"]).optional().describe("Release channel for auto-updates (latest or stable)"),...e("LODESTONE")?{disableDeepLinkRegistration:o.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")}:{},minimumVersion:o.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),plansDirectory:o.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.context/plans/"),..."ant"===process.env.USER_TYPE?{classifierPermissionsEnabled:o.boolean().optional().describe("Enable AI-based classification for Bash(prompt:...) permission rules")}:{},...e("PROACTIVE")||e("KAIROS")?{minSleepDurationMs:o.number().nonnegative().int().optional().describe("Minimum duration in milliseconds that the Sleep tool must sleep for. Useful for throttling proactive tick frequency."),maxSleepDurationMs:o.number().int().min(-1).optional().describe("Maximum duration in milliseconds that the Sleep tool can sleep for. Set to -1 for indefinite sleep (waits for user input). Useful for limiting idle time in remote/managed environments.")}:{},...e("VOICE_MODE")?{voiceEnabled:o.boolean().optional().describe("Activar dictado local (mantener pulsado para hablar)")}:{},...e("KAIROS")?{assistant:o.boolean().optional().describe("Start Claude in assistant mode (custom system prompt, brief view, scheduled check-in skills)"),assistantName:o.string().optional().describe("Display name for the assistant, shown in the claude.ai session list")}:{},channelsEnabled:o.boolean().optional().describe("Teams/Enterprise opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). Default off. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:o.array(o.object({marketplace:o.string(),plugin:o.string()})).optional().describe("Teams/Enterprise allowlist of channel plugins. When set, replaces the default Anthropic allowlist — admins decide which plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),...e("KAIROS")||e("KAIROS_BRIEF")?{defaultView:o.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")}:{},prefersReducedMotion:o.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),autoMemoryEnabled:o.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:o.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .context/settings.json) for security. When unset, defaults to ~/.context/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:o.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:o.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),skipDangerousModePermissionPrompt:o.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),...e("TRANSCRIPT_CLASSIFIER")?{skipAutoPermissionPrompt:o.boolean().optional().describe("Whether the user has accepted the auto mode opt-in dialog"),useAutoModeDuringPlan:o.boolean().optional().describe("Whether plan mode uses auto mode semantics when auto mode is available (default: true)"),autoMode:o.object({allow:o.array(o.string()).optional().describe("Rules for the auto mode classifier allow section"),soft_deny:o.array(o.string()).optional().describe("Rules for the auto mode classifier deny section"),..."ant"===process.env.USER_TYPE?{deny:o.array(o.string()).optional()}:{},environment:o.array(o.string()).optional().describe("Entries for the auto mode classifier environment section")}).optional().describe("Auto mode classifier prompt customization")}:{},disableAutoMode:o.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:o.array(o.object({id:o.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:o.string().describe("Display name for the SSH connection"),sshHost:o.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:o.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:o.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:o.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMdExcludes:o.array(o.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:o.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").')}).passthrough());export function isMcpServerNameEntry(e){return"serverName"in e&&void 0!==e.serverName}export function isMcpServerCommandEntry(e){return"serverCommand"in e&&void 0!==e.serverCommand}export function isMcpServerUrlEntry(e){return"serverUrl"in e&&void 0!==e.serverUrl}
1
+ import{feature as e}from"../../recovery/bunBundleShim.js";import{z as o}from"zod/v4";import{SandboxSettingsSchema as t}from"../../entrypoints/sandboxTypes.js";import{isEnvTruthy as s}from"../envUtils.js";import{lazySchema as r}from"../lazySchema.js";import{EXTERNAL_PERMISSION_MODES as i,PERMISSION_MODES as a}from"../permissions/PermissionMode.js";import{MarketplaceSourceSchema as n}from"../plugins/schemas.js";import{CLAUDE_CODE_SETTINGS_SCHEMA_URL as l}from"./constants.js";import{PermissionRuleSchema as d}from"./permissionValidation.js";export{HookCommandSchema,HookMatcherSchema,HooksSchema}from"../../schemas/hooks.js";import{HooksSchema as c}from"../../schemas/hooks.js";import{count as p}from"../array.js";export const EnvironmentVariablesSchema=r(()=>o.record(o.string(),o.coerce.string()));export const PermissionsSchema=r(()=>o.object({allow:o.array(d()).optional().describe("List of permission rules for allowed operations"),deny:o.array(d()).optional().describe("List of permission rules for denied operations"),ask:o.array(d()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:o.enum(e("TRANSCRIPT_CLASSIFIER")?a:i).optional().describe("Default permission mode when Context Code needs access"),disableBypassPermissionsMode:o.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),...e("TRANSCRIPT_CLASSIFIER")?{disableAutoMode:o.enum(["disable"]).optional().describe("Disable auto mode")}:{},additionalDirectories:o.array(o.string()).optional().describe("Additional directories to include in the permission scope")}).passthrough());export const ExtraKnownMarketplaceSchema=r(()=>o.object({source:n().describe("Where to fetch the marketplace from"),installLocation:o.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:o.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")}));export const AllowedMcpServerEntrySchema=r(()=>o.object({serverName:o.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:o.array(o.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:o.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(e=>1===p([void 0!==e.serverName,void 0!==e.serverCommand,void 0!==e.serverUrl],Boolean),{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'}));export const DeniedMcpServerEntrySchema=r(()=>o.object({serverName:o.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:o.array(o.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:o.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(e=>1===p([void 0!==e.serverName,void 0!==e.serverCommand,void 0!==e.serverUrl],Boolean),{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'}));export const CUSTOMIZATION_SURFACES=["skills","agents","hooks","mcp"];export const SettingsSchema=r(()=>o.object({$schema:o.literal(l).optional().describe("JSON Schema reference for Context Code settings"),apiKeyHelper:o.string().optional().describe("Path to a script that outputs authentication values"),awsCredentialExport:o.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:o.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:o.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),...s(process.env.CONTEXT_CODE_ENABLE_XAA)||s(process.env.CLAUDE_CODE_ENABLE_XAA)?{xaaIdp:o.object({issuer:o.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:o.string().describe("Context Code's client_id registered at the IdP"),callbackPort:o.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")}:{},fileSuggestion:o.object({type:o.literal("command"),command:o.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:o.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),cleanupPeriodDays:o.number().nonnegative().int().optional().describe("Number of days to retain chat transcripts (default: 30). Setting to 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."),env:EnvironmentVariablesSchema().optional().describe("Environment variables to set for Context Code sessions"),attribution:o.object({commit:o.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:o.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Context Code attribution if not set."),includeCoAuthoredBy:o.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Context's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:o.boolean().optional().describe("Include built-in commit and PR workflow instructions in Context's system prompt (default: true)"),permissions:PermissionsSchema().optional().describe("Tool usage permissions configuration"),model:o.string().optional().describe("Override the default model used by Context Code"),availableModels:o.array(o.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),modelOverrides:o.record(o.string(),o.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:o.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:o.array(o.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:o.array(o.string()).optional().describe("List of rejected MCP servers from .mcp.json"),allowedMcpServers:o.array(AllowedMcpServerEntrySchema()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:o.array(DeniedMcpServerEntrySchema()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),hooks:c().optional().describe("Custom commands to run before/after tool executions"),worktree:o.object({symlinkDirectories:o.array(o.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:o.array(o.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). Dramatically faster in large monorepos — only the listed paths are written to disk.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:o.boolean().optional().describe("Disable all hooks and statusLine execution"),defaultShell:o.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:o.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:o.array(o.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:o.array(o.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:o.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:o.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),strictPluginOnlyCustomization:o.preprocess(e=>Array.isArray(e)?e.filter(e=>CUSTOMIZATION_SURFACES.includes(e)):e,o.union([o.boolean(),o.array(o.enum(CUSTOMIZATION_SURFACES))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.context/{surface}/, .context/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. Composes with strictKnownMarketplaces for end-to-end admin control — plugins gated by marketplace allowlist, everything else blocked here.'),statusLine:o.object({type:o.literal("command"),command:o.string(),padding:o.number().optional()}).optional().describe("Custom status line display configuration"),enabledPlugins:o.record(o.string(),o.union([o.array(o.string()),o.boolean(),o.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints.'),extraKnownMarketplaces:o.record(o.string(),ExtraKnownMarketplaceSchema()).check(e=>{for(const[o,t]of Object.entries(e.value))"settings"===t.source.source&&t.source.name!==o&&e.issues.push({code:"custom",input:t.source.name,path:[o,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${o}" but source.name "${t.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:o.array(n()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. Note: this is a policy gate only — it does NOT register marketplaces. To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:o.array(n()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),forceLoginMethod:o.enum(["claudeai","console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),forceLoginOrgUUID:o.string().optional().describe("Organization UUID to use for OAuth login"),otelHeadersHelper:o.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:o.string().optional().describe("Controls the output style for assistant responses"),language:o.string().optional().describe('Idioma preferido para las respuestas de Context y el dictado local (por ejemplo, "japanese", "spanish")'),skipWebFetchPreflight:o.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:t().optional(),feedbackSurveyRate:o.number().min(0).max(1).optional().describe("Probability (0–1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:o.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:o.object({mode:o.enum(["append","replace"]),verbs:o.array(o.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:o.object({excludeDefault:o.boolean().optional(),tips:o.array(o.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:o.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:o.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:o.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:o.enum("ant"===process.env.USER_TYPE?["low","medium","high","max"]:["low","medium","high"]).optional().catch(void 0).describe("Persisted effort level for supported models."),advisorModel:o.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:o.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:o.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),promptSuggestionEnabled:o.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),showClearContextOnPlanAccept:o.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:o.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),companyAnnouncements:o.array(o.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:o.record(o.string(),o.object({mcpServers:o.record(o.string(),o.record(o.string(),o.union([o.string(),o.number(),o.boolean(),o.array(o.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:o.record(o.string(),o.union([o.string(),o.number(),o.boolean(),o.array(o.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")})).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:o.object({defaultEnvironmentId:o.string().optional().describe("Default environment ID to use for remote sessions")}).optional().describe("Remote session configuration"),autoUpdatesChannel:o.enum(["latest","stable"]).optional().describe("Release channel for auto-updates (latest or stable)"),...e("LODESTONE")?{disableDeepLinkRegistration:o.enum(["disable"]).optional().describe("Prevent claude-cli:// protocol handler registration with the OS")}:{},minimumVersion:o.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),plansDirectory:o.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.context/plans/"),..."ant"===process.env.USER_TYPE?{classifierPermissionsEnabled:o.boolean().optional().describe("Enable AI-based classification for Bash(prompt:...) permission rules")}:{},...e("PROACTIVE")||e("KAIROS")?{minSleepDurationMs:o.number().nonnegative().int().optional().describe("Minimum duration in milliseconds that the Sleep tool must sleep for. Useful for throttling proactive tick frequency."),maxSleepDurationMs:o.number().int().min(-1).optional().describe("Maximum duration in milliseconds that the Sleep tool can sleep for. Set to -1 for indefinite sleep (waits for user input). Useful for limiting idle time in remote/managed environments.")}:{},...e("VOICE_MODE")?{voiceEnabled:o.boolean().optional().describe("Activar dictado local (mantener pulsado para hablar)")}:{},...e("KAIROS")?{assistant:o.boolean().optional().describe("Start Claude in assistant mode (custom system prompt, brief view, scheduled check-in skills)"),assistantName:o.string().optional().describe("Display name for the assistant, shown in the claude.ai session list")}:{},channelsEnabled:o.boolean().optional().describe("Teams/Enterprise opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). Default off. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:o.array(o.object({marketplace:o.string(),plugin:o.string()})).optional().describe("Teams/Enterprise allowlist of channel plugins. When set, replaces the default Anthropic allowlist — admins decide which plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),...e("KAIROS")||e("KAIROS_BRIEF")?{defaultView:o.enum(["chat","transcript"]).optional().describe("Default transcript view: chat (SendUserMessage checkpoints only) or transcript (full)")}:{},prefersReducedMotion:o.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),autoMemoryEnabled:o.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:o.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .context/settings.json) for security. When unset, defaults to ~/.context/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:o.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:o.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),skipDangerousModePermissionPrompt:o.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),...e("TRANSCRIPT_CLASSIFIER")?{skipAutoPermissionPrompt:o.boolean().optional().describe("Whether the user has accepted the auto mode opt-in dialog"),useAutoModeDuringPlan:o.boolean().optional().describe("Whether plan mode uses auto mode semantics when auto mode is available (default: true)"),autoMode:o.object({allow:o.array(o.string()).optional().describe("Rules for the auto mode classifier allow section"),soft_deny:o.array(o.string()).optional().describe("Rules for the auto mode classifier deny section"),..."ant"===process.env.USER_TYPE?{deny:o.array(o.string()).optional()}:{},environment:o.array(o.string()).optional().describe("Entries for the auto mode classifier environment section")}).optional().describe("Auto mode classifier prompt customization")}:{},disableAutoMode:o.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:o.array(o.object({id:o.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:o.string().describe("Display name for the SSH connection"),sshHost:o.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:o.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:o.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:o.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMdExcludes:o.array(o.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:o.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").')}).passthrough());export function isMcpServerNameEntry(e){return"serverName"in e&&void 0!==e.serverName}export function isMcpServerCommandEntry(e){return"serverCommand"in e&&void 0!==e.serverCommand}export function isMcpServerUrlEntry(e){return"serverUrl"in e&&void 0!==e.serverUrl}
@@ -1 +1 @@
1
- import{isClaudeSettingsPath as t}from"../permissions/filesystem.js";import{validateSettingsFileContent as e}from"./validation.js";export function validateInputForSettingsFileEdit(i,n,s){if(!t(i))return null;if(!e(n).isValid)return null;const l=s(),o=e(l);return o.isValid?null:{result:!1,message:`Context Code settings.json validation failed after edit:\n${o.error}\n\nFull schema:\n${o.fullSchema}\nIMPORTANT: Do not update the env unless explicitly instructed to do so.`,errorCode:10}}
1
+ import{isClaudeSettingsPath as e}from"../permissions/filesystem.js";import{validateSettingsFileContent as t}from"./validation.js";export function validateInputForSettingsFileEdit(i,n,l){if(!e(i))return null;if(!t(n).isValid)return null;const o=l(),r=t(o);return r.isValid?null:{result:!1,message:`Context Code settings.json validation failed after edit:\n${r.error}\n\nFull schema:\n${r.fullSchema}\nIMPORTANT: Do not update the env unless explicitly instructed to do so.`,errorCode:10}}
@@ -1 +1 @@
1
- import{jsonParse as e}from"../slowOperations.js";import{plural as s}from"../stringUtils.js";import{validatePermissionRule as i}from"./permissionValidation.js";import{generateSettingsJSONSchema as r}from"./schemaOutput.js";import{SettingsSchema as t}from"./types.js";import{getValidationTip as n}from"./validationTips.js";function isInvalidTypeIssue(e){return"invalid_type"===e.code}function isInvalidValueIssue(e){return"invalid_value"===e.code}function isTooSmallIssue(e){return"too_small"===e.code}function getReceivedType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function extractReceivedFromMessage(e){const s=e.match(/received (\w+)/);return s?s[1]:void 0}export function formatZodError(e,i){return e.issues.map(e=>{const r=e.path.map(String).join(".");let t,o,a,l,u,c=e.message;if(isInvalidValueIssue(e))o=e.values.map(e=>String(e)),a=o.join(" | "),l=void 0,u=void 0;else if(isInvalidTypeIssue(e)){a=e.expected;const s=extractReceivedFromMessage(e.message);l=s??getReceivedType(e.input),u=s??getReceivedType(e.input)}else isTooSmallIssue(e)?a=String(e.minimum):"custom"===e.code&&"params"in e&&(l=e.params.received,u=l);const d=n({path:r,code:e.code,expected:a,received:l,enumValues:o,message:e.message,value:l});if(isInvalidValueIssue(e))t=o?.map(e=>`"${e}"`).join(", "),c=`Invalid value. Expected one of: ${t}`;else if(isInvalidTypeIssue(e)){const s=extractReceivedFromMessage(e.message)??getReceivedType(e.input);c="object"===e.expected&&"null"===s&&""===r?"Invalid or malformed JSON":`Expected ${e.expected}, but received ${s}`}else if(function(e){return"unrecognized_keys"===e.code}(e)){const i=e.keys.join(", ");c=`Unrecognized ${s(e.keys.length,"field")}: ${i}`}else isTooSmallIssue(e)&&(c=`Number must be greater than or equal to ${e.minimum}`,t=String(e.minimum));return{file:i,path:r,message:c,expected:t,invalidValue:u,suggestion:d?.suggestion,docLink:d?.docLink}})}export function validateSettingsFileContent(s){try{const i=e(s),n=t().strict().safeParse(i);if(n.success)return{isValid:!0};return{isValid:!1,error:"Settings validation failed:\n"+formatZodError(n.error,"settings").map(e=>`- ${e.path}: ${e.message}`).join("\n"),fullSchema:r()}}catch(e){return{isValid:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown parsing error"}`,fullSchema:r()}}}export function filterInvalidPermissionRules(e,s){if(!e||"object"!=typeof e)return[];const r=e;if(!r.permissions||"object"!=typeof r.permissions)return[];const t=r.permissions,n=[];for(const e of["allow","deny","ask"]){const r=t[e];Array.isArray(r)&&(t[e]=r.filter(r=>{if("string"!=typeof r)return n.push({file:s,path:`permissions.${e}`,message:`Non-string value in ${e} array was removed`,invalidValue:r}),!1;const t=i(r);if(!t.valid){let i=`Invalid permission rule "${r}" was skipped`;return t.error&&(i+=`: ${t.error}`),t.suggestion&&(i+=`. ${t.suggestion}`),n.push({file:s,path:`permissions.${e}`,message:i,invalidValue:r}),!1}return!0}))}return n}
1
+ import{jsonParse as e}from"../slowOperations.js";import{plural as i}from"../stringUtils.js";import{validatePermissionRule as s}from"./permissionValidation.js";import{generateSettingsJSONSchema as r}from"./schemaOutput.js";import{SettingsSchema as n}from"./types.js";import{getValidationTip as t}from"./validationTips.js";function isInvalidTypeIssue(e){return"invalid_type"===e.code}function isInvalidValueIssue(e){return"invalid_value"===e.code}function isTooSmallIssue(e){return"too_small"===e.code}function getReceivedType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function extractReceivedFromMessage(e){const i=e.match(/received (\w+)/);return i?i[1]:void 0}export function formatZodError(e,s){return e.issues.map(e=>{const r=e.path.map(String).join(".");let n,o,a,l,u,c=e.message;if(isInvalidValueIssue(e))o=e.values.map(e=>String(e)),a=o.join(" | "),l=void 0,u=void 0;else if(isInvalidTypeIssue(e)){a=e.expected;const i=extractReceivedFromMessage(e.message);l=i??getReceivedType(e.input),u=i??getReceivedType(e.input)}else if(isTooSmallIssue(e))a=String(e.minimum);else if("custom"===e.code&&"params"in e){l=e.params.received,u=l}const d=t({path:r,code:e.code,expected:a,received:l,enumValues:o,message:e.message,value:l});if(isInvalidValueIssue(e))n=o?.map(e=>`"${e}"`).join(", "),c=`Invalid value. Expected one of: ${n}`;else if(isInvalidTypeIssue(e)){const i=extractReceivedFromMessage(e.message)??getReceivedType(e.input);c="object"===e.expected&&"null"===i&&""===r?"Invalid or malformed JSON":`Expected ${e.expected}, but received ${i}`}else if(function(e){return"unrecognized_keys"===e.code}(e)){const s=e.keys.join(", ");c=`Unrecognized ${i(e.keys.length,"field")}: ${s}`}else isTooSmallIssue(e)&&(c=`Number must be greater than or equal to ${e.minimum}`,n=String(e.minimum));return{file:s,path:r,message:c,expected:n,invalidValue:u,suggestion:d?.suggestion,docLink:d?.docLink}})}export function validateSettingsFileContent(i){try{const s=e(i),t=n().strict().safeParse(s);if(t.success)return{isValid:!0};const o=formatZodError(t.error,"settings");return{isValid:!1,error:"Settings validation failed:\n"+o.map(e=>`- ${e.path}: ${e.message}`).join("\n"),fullSchema:r()}}catch(e){return{isValid:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown parsing error"}`,fullSchema:r()}}}export function filterInvalidPermissionRules(e,i){if(!e||"object"!=typeof e)return[];const r=e;if(!r.permissions||"object"!=typeof r.permissions)return[];const n=r.permissions,t=[];for(const e of["allow","deny","ask"]){const r=n[e];Array.isArray(r)&&(n[e]=r.filter(r=>{if("string"!=typeof r)return t.push({file:i,path:`permissions.${e}`,message:`Non-string value in ${e} array was removed`,invalidValue:r}),!1;const n=s(r);if(!n.valid){let s=`Invalid permission rule "${r}" was skipped`;return n.error&&(s+=`: ${n.error}`),n.suggestion&&(s+=`. ${n.suggestion}`),t.push({file:i,path:`permissions.${e}`,message:s,invalidValue:r}),!1}return!0}))}return t}
@@ -1 +1 @@
1
- import{feature as s}from"bun:bundle";import{access as e}from"fs/promises";import{tmpdir as o}from"os";import{join as t}from"path";import{join as n}from"path/posix";import{rearrangePipeCommand as i}from"../bash/bashPipeCommand.js";import{createAndSaveSnapshot as r}from"../bash/ShellSnapshot.js";import{formatShellPrefixCommand as a}from"../bash/shellPrefix.js";import{quote as l}from"../bash/shellQuote.js";import{quoteShellCommand as d,rewriteWindowsNullRedirect as m,shouldAddStdinRedirect as c}from"../bash/shellQuoting.js";import{logForDebugging as p}from"../debug.js";import{getPlatform as u}from"../platform.js";import{getSessionEnvironmentScript as h}from"../sessionEnvironment.js";import{getSessionEnvVars as f}from"../sessionEnvVars.js";import{ensureSocketInitialized as E,getClaudeTmuxEnv as S,hasTmuxToolBeenUsed as w}from"../tmuxSocket.js";import{windowsPathToPosixPath as g}from"../windowsPaths.js";export async function createBashShellProvider(v,P){let b;const T=P?.skipSnapshot?Promise.resolve(void 0):r(v).catch(s=>{p(`Failed to create shell snapshot: ${s}`)});let _;return{type:"bash",shellPath:v,detached:!0,async buildExecCommand(r,f){let E=await T;if(E)try{await e(E)}catch{p(`Snapshot file missing, falling back to login shell: ${E}`),E=void 0}_=E,b=f.sandboxTmpDir;const S=o(),w="windows"===u()?g(S):S,P=f.useSandbox?n(f.sandboxTmpDir,`cwd-${f.id}`):n(w,`claude-${f.id}-cwd`),C=f.useSandbox?n(f.sandboxTmpDir,`cwd-${f.id}`):t(S,`claude-${f.id}-cwd`),D=m(r),x=c(D);let j=d(D,x);s("COMMIT_ATTRIBUTION")&&(r.includes("<<")||r.includes("\n"))&&(p(`Shell: Command before quoting (first 500 chars):\n${r.slice(0,500)}`),p(`Shell: Quoted command (first 500 chars):\n${j.slice(0,500)}`)),D.includes("|")&&x&&(j=i(D));const O=[];if(E){const s="windows"===u()?g(E):E;O.push(`source ${l([s])} 2>/dev/null || true`)}const L=await h();L&&O.push(L);const I=function(s){return process.env.CONTEXT_CODE_SHELL_PREFIX||process.env.CLAUDE_CODE_SHELL_PREFIX?"{ shopt -u extglob || setopt NO_EXTENDED_GLOB; } >/dev/null 2>&1 || true":s.includes("bash")?"shopt -u extglob 2>/dev/null || true":s.includes("zsh")?"setopt NO_EXTENDED_GLOB 2>/dev/null || true":null}(v);I&&O.push(I),O.push(`eval ${j}`),O.push(`pwd -P >| ${l([P])}`);let R=O.join(" && ");const $=process.env.CONTEXT_CODE_SHELL_PREFIX??process.env.CLAUDE_CODE_SHELL_PREFIX;return $&&(R=a($,R)),{commandString:R,cwdFilePath:C}},getSpawnArgs(s){const e=void 0!==_;return e&&p("Spawning shell without login (-l flag skipped)"),["-c",...e?[]:["-l"],s]},async getEnvironmentOverrides(s){const e=s.includes("tmux");"ant"===process.env.USER_TYPE&&(w()||e)&&await E();const o=S(),t={};if(o&&(t.TMUX=o),b){let s=b;"windows"===u()&&(s=g(s)),t.TMPDIR=s,t.CLAUDE_CODE_TMPDIR=s,t.TMPPREFIX=n(s,"zsh")}for(const[s,e]of f())t[s]=e;return t}}}
1
+ import{feature as s}from"../../recovery/bunBundleShim.js";import{access as o}from"fs/promises";import{tmpdir as e}from"os";import{join as t}from"path";import{join as n}from"path/posix";import{rearrangePipeCommand as r}from"../bash/bashPipeCommand.js";import{createAndSaveSnapshot as i}from"../bash/ShellSnapshot.js";import{formatShellPrefixCommand as l}from"../bash/shellPrefix.js";import{quote as a}from"../bash/shellQuote.js";import{quoteShellCommand as m,rewriteWindowsNullRedirect as c,shouldAddStdinRedirect as p}from"../bash/shellQuoting.js";import{logForDebugging as d}from"../debug.js";import{getPlatform as h}from"../platform.js";import{getSessionEnvironmentScript as u}from"../sessionEnvironment.js";import{getSessionEnvVars as f}from"../sessionEnvVars.js";import{ensureSocketInitialized as E,getClaudeTmuxEnv as w,hasTmuxToolBeenUsed as b}from"../tmuxSocket.js";import{windowsPathToPosixPath as v}from"../windowsPaths.js";export async function createBashShellProvider(_,S){let T;const D=S?.skipSnapshot?Promise.resolve(void 0):i(_).catch(s=>{d(`Failed to create shell snapshot: ${s}`)});let P;return{type:"bash",shellPath:_,detached:!0,async buildExecCommand(i,f){let E=await D;if(E)try{await o(E)}catch{d(`Snapshot file missing, falling back to login shell: ${E}`),E=void 0}P=E,T=f.sandboxTmpDir;const w=e(),b="windows"===h()?v(w):w,S=f.useSandbox?n(f.sandboxTmpDir,`cwd-${f.id}`):n(b,`claude-${f.id}-cwd`),g=f.useSandbox?n(f.sandboxTmpDir,`cwd-${f.id}`):t(w,`claude-${f.id}-cwd`),j=c(i),C=p(j);let O=m(j,C);s("COMMIT_ATTRIBUTION")&&(i.includes("<<")||i.includes("\n"))&&(d(`Shell: Command before quoting (first 500 chars):\n${i.slice(0,500)}`),d(`Shell: Quoted command (first 500 chars):\n${O.slice(0,500)}`)),j.includes("|")&&C&&(O=r(j));const x=[];if(E){const s="windows"===h()?v(E):E;x.push(`source ${a([s])} 2>/dev/null || true`)}const L=await u();L&&x.push(L);const $=function(s){return process.env.CONTEXT_CODE_SHELL_PREFIX||process.env.CLAUDE_CODE_SHELL_PREFIX?"{ shopt -u extglob || setopt NO_EXTENDED_GLOB; } >/dev/null 2>&1 || true":s.includes("bash")?"shopt -u extglob 2>/dev/null || true":s.includes("zsh")?"setopt NO_EXTENDED_GLOB 2>/dev/null || true":null}(_);$&&x.push($),x.push(`eval ${O}`),x.push(`pwd -P >| ${a([S])}`);let I=x.join(" && ");const X=process.env.CONTEXT_CODE_SHELL_PREFIX??process.env.CLAUDE_CODE_SHELL_PREFIX;return X&&(I=l(X,I)),{commandString:I,cwdFilePath:g}},getSpawnArgs(s){const o=void 0!==P;return o&&d("Spawning shell without login (-l flag skipped)"),["-c",...o?[]:["-l"],s]},async getEnvironmentOverrides(s){const o=s.includes("tmux");"ant"===process.env.USER_TYPE&&(b()||o)&&await E();const e=w(),t={};if(e&&(t.TMUX=e),T){let s=T;"windows"===h()&&(s=v(s)),t.TMPDIR=s,t.CLAUDE_CODE_TMPDIR=s,t.TMPPREFIX=n(s,"zsh")}for(const[s,o]of f())t[s]=o;return t}}}
@@ -1 +1 @@
1
- import{realpath as t,stat as e}from"fs/promises";import{getPlatform as r}from"../platform.js";import{which as a}from"../which.js";async function probePath(t){try{return(await e(t)).isFile()?t:null}catch{return null}}export async function findPowerShell(){const e=await a("pwsh");if(e){if("linux"===r()){const r=await t(e).catch(()=>e);if(e.startsWith("/snap/")||r.startsWith("/snap/")){const e=await probePath("/opt/microsoft/powershell/7/pwsh")??await probePath("/usr/bin/pwsh");if(e){const r=await t(e).catch(()=>e);if(!e.startsWith("/snap/")&&!r.startsWith("/snap/"))return e}}}return e}return await a("powershell")||null}let o=null;export function getCachedPowerShellPath(){return o||(o=findPowerShell()),o}export async function getPowerShellEdition(){const t=await getCachedPowerShellPath();return t?"pwsh"===t.split(/[/\\]/).pop().toLowerCase().replace(/\.exe$/,"")?"core":"desktop":null}export function resetPowerShellCache(){o=null}
1
+ import{realpath as t,stat as e}from"fs/promises";import{getPlatform as r}from"../platform.js";import{which as o}from"../which.js";async function probePath(t){try{return(await e(t)).isFile()?t:null}catch{return null}}export async function findPowerShell(){const e=await o("pwsh");if(e){if("linux"===r()){const r=await t(e).catch(()=>e);if(e.startsWith("/snap/")||r.startsWith("/snap/")){const e=await probePath("/opt/microsoft/powershell/7/pwsh")??await probePath("/usr/bin/pwsh");if(e){const r=await t(e).catch(()=>e);if(!e.startsWith("/snap/")&&!r.startsWith("/snap/"))return e}}}return e}const n=await o("powershell");return n||null}let n=null;export function getCachedPowerShellPath(){return n||(n=findPowerShell()),n}export async function getPowerShellEdition(){const t=await getCachedPowerShellPath();if(!t)return null;return"pwsh"===t.split(/[/\\]/).pop().toLowerCase().replace(/\.exe$/,"")?"core":"desktop"}export function resetPowerShellCache(){n=null}