@iaforged/context-code 2.1.7 → 2.2.4

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 (411) hide show
  1. package/dist/src/Task.js +1 -1
  2. package/dist/src/commands/login/login.js +1 -1
  3. package/dist/src/components/ConsoleOAuthFlow.js +1 -1
  4. package/dist/src/constants/oauth.js +1 -1
  5. package/dist/src/context/mailbox.js +1 -1
  6. package/dist/src/context/voice.js +1 -1
  7. package/dist/src/hooks/useTerminalSize.js +1 -1
  8. package/dist/src/ink/Ansi.js +1 -1
  9. package/dist/src/ink/clearTerminal.js +1 -1
  10. package/dist/src/ink/colorize.js +1 -1
  11. package/dist/src/ink/components/App.js +1 -1
  12. package/dist/src/ink/components/Button.js +1 -1
  13. package/dist/src/ink/components/ClockContext.js +1 -1
  14. package/dist/src/ink/components/CursorDeclarationContext.js +1 -1
  15. package/dist/src/ink/components/Link.js +1 -1
  16. package/dist/src/ink/components/StdinContext.js +1 -1
  17. package/dist/src/ink/components/TerminalFocusContext.js +1 -1
  18. package/dist/src/ink/dom.js +1 -1
  19. package/dist/src/ink/events/keyboard-event.js +1 -1
  20. package/dist/src/ink/hit-test.js +1 -1
  21. package/dist/src/ink/hooks/use-animation-frame.js +1 -1
  22. package/dist/src/ink/hooks/use-app.js +1 -1
  23. package/dist/src/ink/hooks/use-input.js +1 -1
  24. package/dist/src/ink/hooks/use-interval.js +1 -1
  25. package/dist/src/ink/hooks/use-selection.js +1 -1
  26. package/dist/src/ink/hooks/use-tab-status.js +1 -1
  27. package/dist/src/ink/hooks/use-terminal-focus.js +1 -1
  28. package/dist/src/ink/hooks/use-terminal-title.js +1 -1
  29. package/dist/src/ink/hooks/use-terminal-viewport.js +1 -1
  30. package/dist/src/ink/ink.js +1 -1
  31. package/dist/src/ink/layout/yoga.js +1 -1
  32. package/dist/src/ink/line-width-cache.js +1 -1
  33. package/dist/src/ink/log-update.js +1 -1
  34. package/dist/src/ink/measure-text.js +1 -1
  35. package/dist/src/ink/output.js +1 -1
  36. package/dist/src/ink/parse-keypress.js +1 -1
  37. package/dist/src/ink/reconciler.js +1 -1
  38. package/dist/src/ink/render-border.js +1 -1
  39. package/dist/src/ink/render-node-to-output.js +1 -1
  40. package/dist/src/ink/render-to-screen.js +1 -1
  41. package/dist/src/ink/renderer.js +1 -1
  42. package/dist/src/ink/root.js +1 -1
  43. package/dist/src/ink/screen.js +1 -1
  44. package/dist/src/ink/searchHighlight.js +1 -1
  45. package/dist/src/ink/selection.js +1 -1
  46. package/dist/src/ink/squash-text-nodes.js +1 -1
  47. package/dist/src/ink/stringWidth.js +1 -1
  48. package/dist/src/ink/tabstops.js +1 -1
  49. package/dist/src/ink/terminal.js +1 -1
  50. package/dist/src/ink/termio/osc.js +1 -1
  51. package/dist/src/ink/termio/parser.js +1 -1
  52. package/dist/src/ink/termio/tokenize.js +1 -1
  53. package/dist/src/ink/useTerminalNotification.js +1 -1
  54. package/dist/src/ink/warn.js +1 -1
  55. package/dist/src/ink/widest-line.js +1 -1
  56. package/dist/src/ink/wrap-text.js +1 -1
  57. package/dist/src/ink/wrapAnsi.js +1 -1
  58. package/dist/src/native-ts/yoga-layout/index.js +1 -1
  59. package/dist/src/schemas/hooks.js +1 -1
  60. package/dist/src/services/SessionMemory/sessionMemoryUtils.js +1 -1
  61. package/dist/src/services/api/client.js +1 -1
  62. package/dist/src/services/api/dumpPrompts.js +1 -1
  63. package/dist/src/services/api/errorUtils.js +1 -1
  64. package/dist/src/services/api/promptCacheBreakDetection.js +1 -1
  65. package/dist/src/services/api/withRetry.js +1 -1
  66. package/dist/src/services/autoDream/consolidationLock.js +1 -1
  67. package/dist/src/services/mcp/elicitationHandler.js +1 -1
  68. package/dist/src/services/mcp/mcpStringUtils.js +1 -1
  69. package/dist/src/services/mcp/oauthPort.js +1 -1
  70. package/dist/src/services/mcp/vscodeSdkMcp.js +1 -1
  71. package/dist/src/services/oauth/client.js +1 -1
  72. package/dist/src/services/oauth/getOauthProfile.js +1 -1
  73. package/dist/src/services/objetivo/types.js +1 -1
  74. package/dist/src/services/rateLimitMocking.js +1 -1
  75. package/dist/src/services/remoteManagedSettings/syncCacheState.js +1 -1
  76. package/dist/src/skills/bundledSkills.js +1 -1
  77. package/dist/src/tasks/DreamTask/DreamTask.js +1 -1
  78. package/dist/src/tools/AgentTool/agentMemory.js +1 -1
  79. package/dist/src/tools/AgentTool/forkSubagent.js +1 -1
  80. package/dist/src/tools/BashTool/BashToolResultMessage.js +1 -1
  81. package/dist/src/tools/BashTool/UI.js +1 -1
  82. package/dist/src/tools/BashTool/sedEditParser.js +1 -1
  83. package/dist/src/tools/BashTool/utils.js +1 -1
  84. package/dist/src/tools/FileReadTool/imageProcessor.js +1 -1
  85. package/dist/src/tools/FileReadTool/prompt.js +1 -1
  86. package/dist/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +1 -1
  87. package/dist/src/tools/ListMcpResourcesTool/UI.js +1 -1
  88. package/dist/src/tools/MCPTool/MCPTool.js +1 -1
  89. package/dist/src/tools/MCPTool/UI.js +1 -1
  90. package/dist/src/tools/McpAuthTool/McpAuthTool.js +1 -1
  91. package/dist/src/tools/NotebookEditTool/prompt.js +1 -1
  92. package/dist/src/tools/PowerShellTool/PowerShellTool.js +1 -1
  93. package/dist/src/tools/PowerShellTool/UI.js +1 -1
  94. package/dist/src/tools/PowerShellTool/gitSafety.js +1 -1
  95. package/dist/src/tools/PowerShellTool/modeValidation.js +1 -1
  96. package/dist/src/tools/PowerShellTool/pathValidation.js +1 -1
  97. package/dist/src/tools/PowerShellTool/powershellPermissions.js +1 -1
  98. package/dist/src/tools/PowerShellTool/powershellSecurity.js +1 -1
  99. package/dist/src/tools/PowerShellTool/prompt.js +1 -1
  100. package/dist/src/tools/PowerShellTool/readOnlyValidation.js +1 -1
  101. package/dist/src/tools/REPLTool/constants.js +1 -1
  102. package/dist/src/tools/REPLTool/primitiveTools.js +1 -1
  103. package/dist/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +1 -1
  104. package/dist/src/tools/ReadMcpResourceTool/UI.js +1 -1
  105. package/dist/src/tools/ScheduleCronTool/prompt.js +1 -1
  106. package/dist/src/tools/SkillTool/prompt.js +1 -1
  107. package/dist/src/tools/TodoWriteTool/TodoWriteTool.js +1 -1
  108. package/dist/src/tools/ToolSearchTool/prompt.js +1 -1
  109. package/dist/src/tools/WebSearchTool/prompt.js +1 -1
  110. package/dist/src/tools/shared/gitOperationTracking.js +1 -1
  111. package/dist/src/types/permissions.js +1 -1
  112. package/dist/src/utils/Cursor.js +1 -1
  113. package/dist/src/utils/QueryGuard.js +1 -1
  114. package/dist/src/utils/Shell.js +1 -1
  115. package/dist/src/utils/ShellCommand.js +1 -1
  116. package/dist/src/utils/activityManager.js +1 -1
  117. package/dist/src/utils/advisor.js +1 -1
  118. package/dist/src/utils/appleTerminalBackup.js +1 -1
  119. package/dist/src/utils/argumentSubstitution.js +1 -1
  120. package/dist/src/utils/authFileDescriptor.js +1 -1
  121. package/dist/src/utils/autoUpdater.js +1 -1
  122. package/dist/src/utils/background/remote/preconditions.js +1 -1
  123. package/dist/src/utils/background/remote/remoteSession.js +1 -1
  124. package/dist/src/utils/bash/ShellSnapshot.js +1 -1
  125. package/dist/src/utils/bash/ast.js +1 -1
  126. package/dist/src/utils/bash/bashParser.js +1 -1
  127. package/dist/src/utils/bash/bashPipeCommand.js +1 -1
  128. package/dist/src/utils/bash/parser.js +1 -1
  129. package/dist/src/utils/bash/shellQuote.js +1 -1
  130. package/dist/src/utils/bash/shellQuoting.js +1 -1
  131. package/dist/src/utils/billing.js +1 -1
  132. package/dist/src/utils/caCerts.js +1 -1
  133. package/dist/src/utils/claudeInChrome/common.js +1 -1
  134. package/dist/src/utils/claudeInChrome/setupPortable.js +1 -1
  135. package/dist/src/utils/claudemd.js +1 -1
  136. package/dist/src/utils/collapseBackgroundBashNotifications.js +1 -1
  137. package/dist/src/utils/collapseReadSearch.js +1 -1
  138. package/dist/src/utils/completionCache.js +1 -1
  139. package/dist/src/utils/computerUse/common.js +1 -1
  140. package/dist/src/utils/concurrentSessions.js +1 -1
  141. package/dist/src/utils/context.js +1 -1
  142. package/dist/src/utils/cron.js +1 -1
  143. package/dist/src/utils/cronTasks.js +1 -1
  144. package/dist/src/utils/cwd.js +1 -1
  145. package/dist/src/utils/debug.js +1 -1
  146. package/dist/src/utils/debugFilter.js +1 -1
  147. package/dist/src/utils/detectRepository.js +1 -1
  148. package/dist/src/utils/diagLogs.js +1 -1
  149. package/dist/src/utils/diff.js +1 -1
  150. package/dist/src/utils/directMemberMessage.js +1 -1
  151. package/dist/src/utils/doctorDiagnostic.js +1 -1
  152. package/dist/src/utils/dxt/helpers.js +1 -1
  153. package/dist/src/utils/dxt/zip.js +1 -1
  154. package/dist/src/utils/earlyInput.js +1 -1
  155. package/dist/src/utils/editor.js +1 -1
  156. package/dist/src/utils/effort.js +1 -1
  157. package/dist/src/utils/embeddedTools.js +1 -1
  158. package/dist/src/utils/envDynamic.js +1 -1
  159. package/dist/src/utils/envUtils.js +1 -1
  160. package/dist/src/utils/execFileNoThrowPortable.js +1 -1
  161. package/dist/src/utils/execSyncWrapper.js +1 -1
  162. package/dist/src/utils/exportRenderer.js +1 -1
  163. package/dist/src/utils/extraUsage.js +1 -1
  164. package/dist/src/utils/fastMode.js +1 -1
  165. package/dist/src/utils/fileOperationAnalytics.js +1 -1
  166. package/dist/src/utils/fileRead.js +1 -1
  167. package/dist/src/utils/findExecutable.js +1 -1
  168. package/dist/src/utils/format.js +1 -1
  169. package/dist/src/utils/frontmatterParser.js +1 -1
  170. package/dist/src/utils/fsOperations.js +1 -1
  171. package/dist/src/utils/fullscreen.js +1 -1
  172. package/dist/src/utils/genericProcessUtils.js +1 -1
  173. package/dist/src/utils/getWorktreePaths.js +1 -1
  174. package/dist/src/utils/git/gitConfigParser.js +1 -1
  175. package/dist/src/utils/git/gitFilesystem.js +1 -1
  176. package/dist/src/utils/git/gitignore.js +1 -1
  177. package/dist/src/utils/gitDiff.js +1 -1
  178. package/dist/src/utils/gitSettings.js +1 -1
  179. package/dist/src/utils/glob.js +1 -1
  180. package/dist/src/utils/gracefulShutdown.js +1 -1
  181. package/dist/src/utils/groupToolUses.js +1 -1
  182. package/dist/src/utils/handlePromptSubmit.js +1 -1
  183. package/dist/src/utils/hash.js +1 -1
  184. package/dist/src/utils/hooks/fileChangedWatcher.js +1 -1
  185. package/dist/src/utils/hooks/hooksSettings.js +1 -1
  186. package/dist/src/utils/hooks/registerSkillHooks.js +1 -1
  187. package/dist/src/utils/hooks/sessionHooks.js +1 -1
  188. package/dist/src/utils/http.js +1 -1
  189. package/dist/src/utils/hyperlink.js +1 -1
  190. package/dist/src/utils/ide.js +1 -1
  191. package/dist/src/utils/idePathConversion.js +1 -1
  192. package/dist/src/utils/imagePaste.js +1 -1
  193. package/dist/src/utils/imageResizer.js +1 -1
  194. package/dist/src/utils/imageStore.js +1 -1
  195. package/dist/src/utils/inProcessTeammateHelpers.js +1 -1
  196. package/dist/src/utils/ink.js +1 -1
  197. package/dist/src/utils/jetbrains.js +1 -1
  198. package/dist/src/utils/json.js +1 -1
  199. package/dist/src/utils/listSessionsImpl.js +1 -1
  200. package/dist/src/utils/localInstaller.js +1 -1
  201. package/dist/src/utils/lockfile.js +1 -1
  202. package/dist/src/utils/logoV2Utils.js +1 -1
  203. package/dist/src/utils/markdown.js +1 -1
  204. package/dist/src/utils/mcp/dateTimeParser.js +1 -1
  205. package/dist/src/utils/mcpOutputStorage.js +1 -1
  206. package/dist/src/utils/mcpValidation.js +1 -1
  207. package/dist/src/utils/memoize.js +1 -1
  208. package/dist/src/utils/memory/types.js +1 -1
  209. package/dist/src/utils/memoryFileDetection.js +1 -1
  210. package/dist/src/utils/messageQueueManager.js +1 -1
  211. package/dist/src/utils/messages/mappers.js +1 -1
  212. package/dist/src/utils/messages/systemInit.js +1 -1
  213. package/dist/src/utils/model/antModels.js +1 -1
  214. package/dist/src/utils/model/check1mAccess.js +1 -1
  215. package/dist/src/utils/model/contextWindowUpgradeCheck.js +1 -1
  216. package/dist/src/utils/model/model.js +1 -1
  217. package/dist/src/utils/model/modelAllowlist.js +1 -1
  218. package/dist/src/utils/model/modelCapabilities.js +1 -1
  219. package/dist/src/utils/model/modelOptions.js +1 -1
  220. package/dist/src/utils/model/modelStrings.js +1 -1
  221. package/dist/src/utils/model/providerBaseUrls.js +1 -1
  222. package/dist/src/utils/model/providerCatalog.js +1 -1
  223. package/dist/src/utils/model/providerModels.js +1 -1
  224. package/dist/src/utils/model/providerProfiles.js +1 -1
  225. package/dist/src/utils/model/providerProfilesDb.js +1 -1
  226. package/dist/src/utils/model/providerSwitch.js +1 -1
  227. package/dist/src/utils/model/providers.js +1 -1
  228. package/dist/src/utils/modelCost.js +1 -1
  229. package/dist/src/utils/modifiers.js +1 -1
  230. package/dist/src/utils/mtls.js +1 -1
  231. package/dist/src/utils/nativeInstaller/download.js +1 -1
  232. package/dist/src/utils/nativeInstaller/installer.js +1 -1
  233. package/dist/src/utils/nativeInstaller/packageManagers.js +1 -1
  234. package/dist/src/utils/nativeInstaller/pidLock.js +1 -1
  235. package/dist/src/utils/notebook.js +1 -1
  236. package/dist/src/utils/pasteStore.js +1 -1
  237. package/dist/src/utils/path.js +1 -1
  238. package/dist/src/utils/permissions/PermissionMode.js +1 -1
  239. package/dist/src/utils/permissions/PermissionPromptToolResultSchema.js +1 -1
  240. package/dist/src/utils/permissions/PermissionUpdate.js +1 -1
  241. package/dist/src/utils/permissions/PermissionUpdateSchema.js +1 -1
  242. package/dist/src/utils/permissions/autoModeState.js +1 -1
  243. package/dist/src/utils/permissions/bypassPermissionsKillswitch.js +1 -1
  244. package/dist/src/utils/permissions/filesystem.js +1 -1
  245. package/dist/src/utils/permissions/getNextPermissionMode.js +1 -1
  246. package/dist/src/utils/permissions/pathValidation.js +1 -1
  247. package/dist/src/utils/permissions/permissionRuleParser.js +1 -1
  248. package/dist/src/utils/permissions/permissionsDb.js +1 -1
  249. package/dist/src/utils/permissions/permissionsLoader.js +1 -1
  250. package/dist/src/utils/permissions/shellRuleMatching.js +1 -1
  251. package/dist/src/utils/planModeV2.js +1 -1
  252. package/dist/src/utils/plans.js +1 -1
  253. package/dist/src/utils/platform.js +1 -1
  254. package/dist/src/utils/plugins/addDirPluginSettings.js +1 -1
  255. package/dist/src/utils/plugins/cacheUtils.js +1 -1
  256. package/dist/src/utils/plugins/dependencyResolver.js +1 -1
  257. package/dist/src/utils/plugins/fetchTelemetry.js +1 -1
  258. package/dist/src/utils/plugins/gitAvailability.js +1 -1
  259. package/dist/src/utils/plugins/hintRecommendation.js +1 -1
  260. package/dist/src/utils/plugins/installedPluginsManager.js +1 -1
  261. package/dist/src/utils/plugins/loadPluginAgents.js +1 -1
  262. package/dist/src/utils/plugins/loadPluginCommands.js +1 -1
  263. package/dist/src/utils/plugins/loadPluginHooks.js +1 -1
  264. package/dist/src/utils/plugins/loadPluginOutputStyles.js +1 -1
  265. package/dist/src/utils/plugins/lspPluginIntegration.js +1 -1
  266. package/dist/src/utils/plugins/lspRecommendation.js +1 -1
  267. package/dist/src/utils/plugins/managedPlugins.js +1 -1
  268. package/dist/src/utils/plugins/marketplaceHelpers.js +1 -1
  269. package/dist/src/utils/plugins/marketplaceManager.js +1 -1
  270. package/dist/src/utils/plugins/mcpPluginIntegration.js +1 -1
  271. package/dist/src/utils/plugins/mcpbHandler.js +1 -1
  272. package/dist/src/utils/plugins/officialMarketplaceGcs.js +1 -1
  273. package/dist/src/utils/plugins/officialMarketplaceStartupCheck.js +1 -1
  274. package/dist/src/utils/plugins/orphanedPluginFilter.js +1 -1
  275. package/dist/src/utils/plugins/performStartupChecks.js +1 -1
  276. package/dist/src/utils/plugins/pluginAutoupdate.js +1 -1
  277. package/dist/src/utils/plugins/pluginBlocklist.js +1 -1
  278. package/dist/src/utils/plugins/pluginDirectories.js +1 -1
  279. package/dist/src/utils/plugins/pluginFlagging.js +1 -1
  280. package/dist/src/utils/plugins/pluginInstallationHelpers.js +1 -1
  281. package/dist/src/utils/plugins/pluginLoader.js +1 -1
  282. package/dist/src/utils/plugins/pluginOptionsStorage.js +1 -1
  283. package/dist/src/utils/plugins/pluginPolicy.js +1 -1
  284. package/dist/src/utils/plugins/pluginStartupCheck.js +1 -1
  285. package/dist/src/utils/plugins/pluginVersioning.js +1 -1
  286. package/dist/src/utils/plugins/reconciler.js +1 -1
  287. package/dist/src/utils/plugins/refresh.js +1 -1
  288. package/dist/src/utils/plugins/schemas.js +1 -1
  289. package/dist/src/utils/plugins/walkPluginMarkdown.js +1 -1
  290. package/dist/src/utils/plugins/zipCache.js +1 -1
  291. package/dist/src/utils/powershell/parser.js +1 -1
  292. package/dist/src/utils/processUserInput/processBashCommand.js +1 -1
  293. package/dist/src/utils/processUserInput/processSlashCommand.js +1 -1
  294. package/dist/src/utils/processUserInput/processTextPrompt.js +1 -1
  295. package/dist/src/utils/processUserInput/processUserInput.js +1 -1
  296. package/dist/src/utils/profilerBase.js +1 -1
  297. package/dist/src/utils/promptCategory.js +1 -1
  298. package/dist/src/utils/promptEditor.js +1 -1
  299. package/dist/src/utils/promptShellExecution.js +1 -1
  300. package/dist/src/utils/proxy.js +1 -1
  301. package/dist/src/utils/queryHelpers.js +1 -1
  302. package/dist/src/utils/queryProfiler.js +1 -1
  303. package/dist/src/utils/queueProcessor.js +1 -1
  304. package/dist/src/utils/readFileInRange.js +1 -1
  305. package/dist/src/utils/releaseNotes.js +1 -1
  306. package/dist/src/utils/renderOptions.js +1 -1
  307. package/dist/src/utils/ripgrep.js +1 -1
  308. package/dist/src/utils/sandbox/sandbox-adapter.js +1 -1
  309. package/dist/src/utils/sdkEventQueue.js +1 -1
  310. package/dist/src/utils/secureStorage/index.js +1 -1
  311. package/dist/src/utils/secureStorage/macOsKeychainHelpers.js +1 -1
  312. package/dist/src/utils/secureStorage/macOsKeychainStorage.js +1 -1
  313. package/dist/src/utils/secureStorage/plainTextStorage.js +1 -1
  314. package/dist/src/utils/secureStorage/sqliteStorage.js +1 -1
  315. package/dist/src/utils/sessionEnvironment.js +1 -1
  316. package/dist/src/utils/sessionIngressAuth.js +1 -1
  317. package/dist/src/utils/sessionRestore.js +1 -1
  318. package/dist/src/utils/sessionStart.js +1 -1
  319. package/dist/src/utils/sessionTitle.js +1 -1
  320. package/dist/src/utils/settings/managedPath.js +1 -1
  321. package/dist/src/utils/settings/mdm/rawRead.js +1 -1
  322. package/dist/src/utils/settings/mdm/settings.js +1 -1
  323. package/dist/src/utils/settings/permissionValidation.js +1 -1
  324. package/dist/src/utils/settings/pluginOnlyPolicy.js +1 -1
  325. package/dist/src/utils/settings/schemaOutput.js +1 -1
  326. package/dist/src/utils/settings/settings.js +1 -1
  327. package/dist/src/utils/settings/types.js +1 -1
  328. package/dist/src/utils/settings/validateEditTool.js +1 -1
  329. package/dist/src/utils/settings/validation.js +1 -1
  330. package/dist/src/utils/shell/bashProvider.js +1 -1
  331. package/dist/src/utils/shell/powershellDetection.js +1 -1
  332. package/dist/src/utils/shell/powershellProvider.js +1 -1
  333. package/dist/src/utils/shell/readOnlyCommandValidation.js +1 -1
  334. package/dist/src/utils/shell/resolveDefaultShell.js +1 -1
  335. package/dist/src/utils/shell/shellToolUtils.js +1 -1
  336. package/dist/src/utils/shell/specPrefix.js +1 -1
  337. package/dist/src/utils/shellConfig.js +1 -1
  338. package/dist/src/utils/sideQuestion.js +1 -1
  339. package/dist/src/utils/skills/skillChangeDetector.js +1 -1
  340. package/dist/src/utils/slashCommandParsing.js +1 -1
  341. package/dist/src/utils/sliceAnsi.js +1 -1
  342. package/dist/src/utils/slowOperations.js +1 -1
  343. package/dist/src/utils/standaloneAgent.js +1 -1
  344. package/dist/src/utils/startupProfiler.js +1 -1
  345. package/dist/src/utils/staticRender.js +1 -1
  346. package/dist/src/utils/status.js +1 -1
  347. package/dist/src/utils/statusNoticeDefinitions.js +1 -1
  348. package/dist/src/utils/suggestions/commandSuggestions.js +1 -1
  349. package/dist/src/utils/suggestions/directoryCompletion.js +1 -1
  350. package/dist/src/utils/suggestions/shellHistoryCompletion.js +1 -1
  351. package/dist/src/utils/suggestions/skillUsageTracking.js +1 -1
  352. package/dist/src/utils/suggestions/slackChannelSuggestions.js +1 -1
  353. package/dist/src/utils/swarm/backends/detection.js +1 -1
  354. package/dist/src/utils/swarm/permissionSync.js +1 -1
  355. package/dist/src/utils/swarm/reconnection.js +1 -1
  356. package/dist/src/utils/swarm/spawnUtils.js +1 -91
  357. package/dist/src/utils/swarm/teammateInit.js +1 -1
  358. package/dist/src/utils/systemDirectories.js +1 -1
  359. package/dist/src/utils/systemPrompt.js +1 -1
  360. package/dist/src/utils/systemTheme.js +1 -1
  361. package/dist/src/utils/task/TaskOutput.js +1 -1
  362. package/dist/src/utils/task/diskOutput.js +1 -1
  363. package/dist/src/utils/tasks.js +1 -1
  364. package/dist/src/utils/teamDiscovery.js +1 -1
  365. package/dist/src/utils/teamMemoryOps.js +1 -1
  366. package/dist/src/utils/teammateMailbox.js +1 -1
  367. package/dist/src/utils/telemetry/betaSessionTracing.js +1 -1
  368. package/dist/src/utils/telemetry/bigqueryExporter.js +1 -1
  369. package/dist/src/utils/telemetry/events.js +1 -1
  370. package/dist/src/utils/telemetry/instrumentation.js +1 -1
  371. package/dist/src/utils/telemetry/logger.js +1 -1
  372. package/dist/src/utils/telemetry/perfettoTracing.js +1 -1
  373. package/dist/src/utils/telemetry/pluginTelemetry.js +1 -1
  374. package/dist/src/utils/telemetry/sessionTracing.js +1 -1
  375. package/dist/src/utils/telemetryAttributes.js +1 -1
  376. package/dist/src/utils/teleport/api.js +1 -1
  377. package/dist/src/utils/teleport/environments.js +1 -1
  378. package/dist/src/utils/teleport/gitBundle.js +1 -1
  379. package/dist/src/utils/teleport.js +1 -1
  380. package/dist/src/utils/tempfile.js +1 -1
  381. package/dist/src/utils/terminal.js +1 -1
  382. package/dist/src/utils/terminalPanel.js +1 -1
  383. package/dist/src/utils/textHighlighting.js +1 -1
  384. package/dist/src/utils/theme.js +1 -1
  385. package/dist/src/utils/themes/bootstrap.js +1 -1
  386. package/dist/src/utils/themes/loader.js +1 -1
  387. package/dist/src/utils/thinking.js +1 -1
  388. package/dist/src/utils/tmuxSocket.js +1 -1
  389. package/dist/src/utils/tokens.js +1 -1
  390. package/dist/src/utils/toolPool.js +1 -1
  391. package/dist/src/utils/toolResultStorage.js +1 -1
  392. package/dist/src/utils/transcriptSearch.js +1 -1
  393. package/dist/src/utils/truncate.js +1 -1
  394. package/dist/src/utils/ultraplan/keyword.js +1 -1
  395. package/dist/src/utils/unaryLogging.js +1 -1
  396. package/dist/src/utils/undercover.js +1 -1
  397. package/dist/src/utils/user.js +1 -1
  398. package/dist/src/utils/userPromptKeywords.js +1 -1
  399. package/dist/src/utils/which.js +1 -1
  400. package/dist/src/utils/windowsPaths.js +1 -1
  401. package/dist/src/utils/worktree.js +1 -1
  402. package/dist/src/utils/zodToJsonSchema.js +1 -1
  403. package/dist/src/vim/operators.js +1 -1
  404. package/dist/src/vim/textObjects.js +1 -1
  405. package/dist/src/vim/transitions.js +1 -1
  406. package/dist/src/voice/voiceModeEnabled.js +1 -1
  407. package/dist/src/webapp/auth.js +1 -1
  408. package/dist/src/webapp/tunnel.js +1 -1
  409. package/dist/src/whatsapp/bridge.js +1 -1
  410. package/dist/src/whatsapp/mirror.js +1 -1
  411. package/package.json +41 -3
@@ -1 +1 @@
1
- import{stringWidth as e}from"./stringWidth.js";import{createTokenizer as t}from"./termio/tokenize.js";export function expandTabs(s,n=8){if(!s.includes("\t"))return s;const o=t(),r=o.feed(s);r.push(...o.flush());let i="",f=0;for(const t of r)if("sequence"===t.type)i+=t.value;else{const s=t.value.split(/(\t|\n)/);for(const t of s)if("\t"===t){const e=n-f%n;i+=" ".repeat(e),f+=e}else"\n"===t?(i+=t,f=0):(i+=t,f+=e(t))}return i}
1
+ import{stringWidth as e}from"./stringWidth.js";import{createTokenizer as t}from"./termio/tokenize.js";export function expandTabs(o,n=8){if(!o.includes("\t"))return o;const s=t(),r=s.feed(o);r.push(...s.flush());let f="",i=0;for(const t of r)if("sequence"===t.type)f+=t.value;else{const o=t.value.split(/(\t|\n)/);for(const t of o)if("\t"===t){const e=n-i%n;f+=" ".repeat(e),i+=e}else"\n"===t?(f+=t,i=0):(f+=t,i+=e(t))}return f}
@@ -1 +1 @@
1
- import{coerce as e}from"semver";import{env as r}from"../utils/env.js";import{gte as s}from"../utils/semver.js";import{getClearTerminalSequence as t}from"./clearTerminal.js";import{cursorMove as o,cursorTo as n,eraseLines as i}from"./termio/csi.js";import{BSU as c,ESU as a,HIDE_CURSOR as u,SHOW_CURSOR as p}from"./termio/dec.js";import{link as m}from"./termio/osc.js";export function isProgressReportingAvailable(){if(!process.stdout.isTTY)return!1;if(process.env.WT_SESSION)return!1;if(process.env.ConEmuANSI||process.env.ConEmuPID||process.env.ConEmuTask)return!0;const r=e(process.env.TERM_PROGRAM_VERSION);return!!r&&("ghostty"===process.env.TERM_PROGRAM?s(r.version,"1.2.0"):"iTerm.app"===process.env.TERM_PROGRAM&&s(r.version,"3.6.6"))}export function isSynchronizedOutputSupported(){if(process.env.TMUX)return!1;const e=process.env.TERM_PROGRAM,r=process.env.TERM;if("iTerm.app"===e||"WezTerm"===e||"WarpTerminal"===e||"ghostty"===e||"contour"===e||"vscode"===e||"alacritty"===e)return!0;if(r?.includes("kitty")||process.env.KITTY_WINDOW_ID)return!0;if("xterm-ghostty"===r)return!0;if(r?.startsWith("foot"))return!0;if(r?.includes("alacritty"))return!0;if(process.env.ZED_TERM)return!0;if(process.env.WT_SESSION)return!0;const s=process.env.VTE_VERSION;return!!(s&&parseInt(s,10)>=6800)}let T;export function setXtversionName(e){void 0===T&&(T=e)}export function isXtermJs(){return"vscode"===process.env.TERM_PROGRAM||(T?.startsWith("xterm.js")??!1)}const f=["iTerm.app","kitty","WezTerm","ghostty","tmux","windows-terminal"];export function supportsExtendedKeys(){return f.includes(r.terminal??"")}export function hasCursorUpViewportYankBug(){return"win32"===process.platform||!!process.env.WT_SESSION}export const SYNC_OUTPUT_SUPPORTED=isSynchronizedOutputSupported();export function writeDiffToTerminal(e,r,s=!1){if(0===r.length)return;const T=!s;let f=T?c:"";for(const e of r)switch(e.type){case"stdout":f+=e.content;break;case"clear":e.count>0&&(f+=i(e.count));break;case"clearTerminal":f+=t();break;case"cursorHide":f+=u;break;case"cursorShow":f+=p;break;case"cursorMove":f+=o(e.x,e.y);break;case"cursorTo":f+=n(e.col);break;case"carriageReturn":f+="\r";break;case"hyperlink":f+=m(e.uri);break;case"styleStr":f+=e.str}T&&(f+=a),e.stdout.write(f)}
1
+ import{coerce as r}from"semver";import{env as e}from"../utils/env.js";import{gte as t}from"../utils/semver.js";import{getClearTerminalSequence as s}from"./clearTerminal.js";import{cursorMove as o,cursorTo as n,eraseLines as i}from"./termio/csi.js";import{BSU as c,ESU as p,HIDE_CURSOR as u,SHOW_CURSOR as a}from"./termio/dec.js";import{link as m}from"./termio/osc.js";export function isProgressReportingAvailable(){if(!process.stdout.isTTY)return!1;if(process.env.WT_SESSION)return!1;if(process.env.ConEmuANSI||process.env.ConEmuPID||process.env.ConEmuTask)return!0;const e=r(process.env.TERM_PROGRAM_VERSION);return!!e&&("ghostty"===process.env.TERM_PROGRAM?t(e.version,"1.2.0"):"iTerm.app"===process.env.TERM_PROGRAM&&t(e.version,"3.6.6"))}export function isSynchronizedOutputSupported(){if(process.env.TMUX)return!1;const r=process.env.TERM_PROGRAM,e=process.env.TERM;if("iTerm.app"===r||"WezTerm"===r||"WarpTerminal"===r||"ghostty"===r||"contour"===r||"vscode"===r||"alacritty"===r)return!0;if(e?.includes("kitty")||process.env.KITTY_WINDOW_ID)return!0;if("xterm-ghostty"===e)return!0;if(e?.startsWith("foot"))return!0;if(e?.includes("alacritty"))return!0;if(process.env.ZED_TERM)return!0;if(process.env.WT_SESSION)return!0;const t=process.env.VTE_VERSION;if(t){if(parseInt(t,10)>=6800)return!0}return!1}let f;export function setXtversionName(r){void 0===f&&(f=r)}export function isXtermJs(){return"vscode"===process.env.TERM_PROGRAM||(f?.startsWith("xterm.js")??!1)}const T=["iTerm.app","kitty","WezTerm","ghostty","tmux","windows-terminal"];export function supportsExtendedKeys(){return T.includes(e.terminal??"")}export function hasCursorUpViewportYankBug(){return"win32"===process.platform||!!process.env.WT_SESSION}export const SYNC_OUTPUT_SUPPORTED=isSynchronizedOutputSupported();export function writeDiffToTerminal(r,e,t=!1){if(0===e.length)return;const f=!t;let T=f?c:"";for(const r of e)switch(r.type){case"stdout":T+=r.content;break;case"clear":r.count>0&&(T+=i(r.count));break;case"clearTerminal":T+=s();break;case"cursorHide":T+=u;break;case"cursorShow":T+=a;break;case"cursorMove":T+=o(r.x,r.y);break;case"cursorTo":T+=n(r.col);break;case"carriageReturn":T+="\r";break;case"hyperlink":T+=m(r.uri);break;case"styleStr":T+=r.str}f&&(T+=p),r.stdout.write(T)}
@@ -1 +1 @@
1
- import{Buffer as t}from"buffer";import{env as e}from"../../utils/env.js";import{execFileNoThrow as o}from"../../utils/execFileNoThrow.js";import{BEL as r,ESC as n,ESC_TYPE as s,SEP as i}from"./ansi.js";export const OSC_PREFIX=n+String.fromCharCode(s.OSC);export const ST=n+"\\";export function osc(...t){const o="kitty"===e.terminal?ST:r;return`${OSC_PREFIX}${t.join(i)}${o}`}export function wrapForMultiplexer(t){return process.env.TMUX?`Ptmux;${t.replaceAll("","")}\\`:process.env.STY?`P${t}\\`:t}export function getClipboardPath(){return"darwin"!==process.platform||process.env.SSH_CONNECTION?process.env.TMUX?"tmux-buffer":"osc52":"native"}export async function tmuxLoadBuffer(t){if(!process.env.TMUX)return!1;const e="iTerm2"===process.env.LC_TERMINAL?["load-buffer","-"]:["load-buffer","-w","-"],{code:r}=await o("tmux",e,{input:t,useCwd:!1,timeout:2e3});return 0===r}export async function setClipboard(e){const s=t.from(e,"utf8").toString("base64"),i=osc(OSC.CLIPBOARD,"c",s);return process.env.SSH_CONNECTION||function(t){const e={input:t,useCwd:!1,timeout:2e3};switch(process.platform){case"darwin":return void o("pbcopy",[],e);case"linux":if(null===c)return;return"wl-copy"===c?void o("wl-copy",[],e):"xclip"===c?void o("xclip",["-selection","clipboard"],e):"xsel"===c?void o("xsel",["--clipboard","--input"],e):void o("wl-copy",[],e).then(t=>{0!==t.code?o("xclip",["-selection","clipboard"],e).then(t=>{0!==t.code?o("xsel",["--clipboard","--input"],e).then(t=>{c=0===t.code?"xsel":null}):c="xclip"}):c="wl-copy"});case"win32":o("clip",[],e)}}(e),await tmuxLoadBuffer(e)?`${n}Ptmux;${`${n}]52;c;${s}${r}`.replaceAll(n,n+n)}${ST}`:i}let c;export function _resetLinuxCopyCache(){c=void 0}export const OSC={SET_TITLE_AND_ICON:0,SET_ICON:1,SET_TITLE:2,SET_COLOR:4,SET_CWD:7,HYPERLINK:8,ITERM2:9,SET_FG_COLOR:10,SET_BG_COLOR:11,SET_CURSOR_COLOR:12,CLIPBOARD:52,KITTY:99,RESET_COLOR:104,RESET_FG_COLOR:110,RESET_BG_COLOR:111,RESET_CURSOR_COLOR:112,SEMANTIC_PROMPT:133,GHOSTTY:777,TAB_STATUS:21337};export function parseOSC(t){const e=t.indexOf(";"),o=e>=0?t.slice(0,e):t,r=e>=0?t.slice(e+1):"",n=parseInt(o,10);if(n===OSC.SET_TITLE_AND_ICON)return{type:"title",action:{type:"both",title:r}};if(n===OSC.SET_ICON)return{type:"title",action:{type:"iconName",name:r}};if(n===OSC.SET_TITLE)return{type:"title",action:{type:"windowTitle",title:r}};if(n===OSC.HYPERLINK){const t=r.split(";"),e=t[0]??"",o=t.slice(1).join(";");if(""===o)return{type:"link",action:{type:"end"}};const n={};if(e)for(const t of e.split(":")){const e=t.indexOf("=");e>=0&&(n[t.slice(0,e)]=t.slice(e+1))}return{type:"link",action:{type:"start",url:o,params:Object.keys(n).length>0?n:void 0}}}return n===OSC.TAB_STATUS?{type:"tabStatus",action:parseTabStatus(r)}:{type:"unknown",sequence:`]${t}`}}export function parseOscColor(t){const e=t.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(e)return{type:"rgb",r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)};const o=t.match(/^rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})$/i);if(o){const scale=t=>Math.round(parseInt(t,16)/(16**t.length-1)*255);return{type:"rgb",r:scale(o[1]),g:scale(o[2]),b:scale(o[3])}}return null}function parseTabStatus(t){const e={};for(const[o,r]of function*(t){let e="",o="",r=!1,n=!1;for(const s of t)n?(r?o+=s:e+=s,n=!1):"\\"===s?n=!0:";"===s?(yield[e,o],e="",o="",r=!1):"="!==s||r?r?o+=s:e+=s:r=!0;(e||r)&&(yield[e,o])}(t))switch(o){case"indicator":e.indicator=""===r?null:parseOscColor(r);break;case"status":e.status=""===r?null:r;break;case"status-color":e.statusColor=""===r?null:parseOscColor(r)}return e}export function link(t,e){if(!t)return LINK_END;const o={id:osc8Id(t),...e},r=Object.entries(o).map(([t,e])=>`${t}=${e}`).join(":");return osc(OSC.HYPERLINK,r,t)}function osc8Id(t){let e=0;for(let o=0;o<t.length;o++)e=(e<<5)-e+t.charCodeAt(o)|0;return(e>>>0).toString(36)}export const LINK_END=osc(OSC.HYPERLINK,"","");export const ITERM2={NOTIFY:0,BADGE:2,PROGRESS:4};export const PROGRESS={CLEAR:0,SET:1,ERROR:2,INDETERMINATE:3};export const CLEAR_ITERM2_PROGRESS=`${OSC_PREFIX}${OSC.ITERM2};${ITERM2.PROGRESS};${PROGRESS.CLEAR};${r}`;export const CLEAR_TERMINAL_TITLE=`${OSC_PREFIX}${OSC.SET_TITLE_AND_ICON};${r}`;export const CLEAR_TAB_STATUS=osc(OSC.TAB_STATUS,"indicator=;status=;status-color=");export function supportsTabStatus(){return"ant"===process.env.USER_TYPE}export function tabStatus(t){const e=[],rgb=t=>"rgb"===t.type?`#${[t.r,t.g,t.b].map(t=>t.toString(16).padStart(2,"0")).join("")}`:"";return"indicator"in t&&e.push(`indicator=${t.indicator?rgb(t.indicator):""}`),"status"in t&&e.push(`status=${t.status?.replaceAll("\\","\\\\").replaceAll(";","\\;")??""}`),"statusColor"in t&&e.push(`status-color=${t.statusColor?rgb(t.statusColor):""}`),osc(OSC.TAB_STATUS,e.join(";"))}
1
+ import{Buffer as t}from"buffer";import{env as e}from"../../utils/env.js";import{execFileNoThrow as o}from"../../utils/execFileNoThrow.js";import{BEL as r,ESC as n,ESC_TYPE as s,SEP as i}from"./ansi.js";export const OSC_PREFIX=n+String.fromCharCode(s.OSC);export const ST=n+"\\";export function osc(...t){const o="kitty"===e.terminal?ST:r;return`${OSC_PREFIX}${t.join(i)}${o}`}export function wrapForMultiplexer(t){if(process.env.TMUX){return`Ptmux;${t.replaceAll("","")}\\`}return process.env.STY?`P${t}\\`:t}export function getClipboardPath(){return"darwin"===process.platform&&!process.env.SSH_CONNECTION?"native":process.env.TMUX?"tmux-buffer":"osc52"}export async function tmuxLoadBuffer(t){if(!process.env.TMUX)return!1;const e="iTerm2"===process.env.LC_TERMINAL?["load-buffer","-"]:["load-buffer","-w","-"],{code:r}=await o("tmux",e,{input:t,useCwd:!1,timeout:2e3});return 0===r}export async function setClipboard(e){const s=t.from(e,"utf8").toString("base64"),i=osc(OSC.CLIPBOARD,"c",s);process.env.SSH_CONNECTION||function(t){const e={input:t,useCwd:!1,timeout:2e3};switch(process.platform){case"darwin":return void o("pbcopy",[],e);case"linux":if(null===c)return;return"wl-copy"===c?void o("wl-copy",[],e):"xclip"===c?void o("xclip",["-selection","clipboard"],e):"xsel"===c?void o("xsel",["--clipboard","--input"],e):void o("wl-copy",[],e).then(t=>{0!==t.code?o("xclip",["-selection","clipboard"],e).then(t=>{0!==t.code?o("xsel",["--clipboard","--input"],e).then(t=>{c=0===t.code?"xsel":null}):c="xclip"}):c="wl-copy"});case"win32":o("clip",[],e)}}(e);return await tmuxLoadBuffer(e)?`${n}Ptmux;${`${n}]52;c;${s}${r}`.replaceAll(n,n+n)}${ST}`:i}let c;export function _resetLinuxCopyCache(){c=void 0}export const OSC={SET_TITLE_AND_ICON:0,SET_ICON:1,SET_TITLE:2,SET_COLOR:4,SET_CWD:7,HYPERLINK:8,ITERM2:9,SET_FG_COLOR:10,SET_BG_COLOR:11,SET_CURSOR_COLOR:12,CLIPBOARD:52,KITTY:99,RESET_COLOR:104,RESET_FG_COLOR:110,RESET_BG_COLOR:111,RESET_CURSOR_COLOR:112,SEMANTIC_PROMPT:133,GHOSTTY:777,TAB_STATUS:21337};export function parseOSC(t){const e=t.indexOf(";"),o=e>=0?t.slice(0,e):t,r=e>=0?t.slice(e+1):"",n=parseInt(o,10);if(n===OSC.SET_TITLE_AND_ICON)return{type:"title",action:{type:"both",title:r}};if(n===OSC.SET_ICON)return{type:"title",action:{type:"iconName",name:r}};if(n===OSC.SET_TITLE)return{type:"title",action:{type:"windowTitle",title:r}};if(n===OSC.HYPERLINK){const t=r.split(";"),e=t[0]??"",o=t.slice(1).join(";");if(""===o)return{type:"link",action:{type:"end"}};const n={};if(e)for(const t of e.split(":")){const e=t.indexOf("=");e>=0&&(n[t.slice(0,e)]=t.slice(e+1))}return{type:"link",action:{type:"start",url:o,params:Object.keys(n).length>0?n:void 0}}}return n===OSC.TAB_STATUS?{type:"tabStatus",action:parseTabStatus(r)}:{type:"unknown",sequence:`]${t}`}}export function parseOscColor(t){const e=t.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(e)return{type:"rgb",r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)};const o=t.match(/^rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})$/i);if(o){const scale=t=>Math.round(parseInt(t,16)/(16**t.length-1)*255);return{type:"rgb",r:scale(o[1]),g:scale(o[2]),b:scale(o[3])}}return null}function parseTabStatus(t){const e={};for(const[o,r]of function*(t){let e="",o="",r=!1,n=!1;for(const s of t)n?(r?o+=s:e+=s,n=!1):"\\"===s?n=!0:";"===s?(yield[e,o],e="",o="",r=!1):"="!==s||r?r?o+=s:e+=s:r=!0;(e||r)&&(yield[e,o])}(t))switch(o){case"indicator":e.indicator=""===r?null:parseOscColor(r);break;case"status":e.status=""===r?null:r;break;case"status-color":e.statusColor=""===r?null:parseOscColor(r)}return e}export function link(t,e){if(!t)return LINK_END;const o={id:osc8Id(t),...e},r=Object.entries(o).map(([t,e])=>`${t}=${e}`).join(":");return osc(OSC.HYPERLINK,r,t)}function osc8Id(t){let e=0;for(let o=0;o<t.length;o++)e=(e<<5)-e+t.charCodeAt(o)|0;return(e>>>0).toString(36)}export const LINK_END=osc(OSC.HYPERLINK,"","");export const ITERM2={NOTIFY:0,BADGE:2,PROGRESS:4};export const PROGRESS={CLEAR:0,SET:1,ERROR:2,INDETERMINATE:3};export const CLEAR_ITERM2_PROGRESS=`${OSC_PREFIX}${OSC.ITERM2};${ITERM2.PROGRESS};${PROGRESS.CLEAR};${r}`;export const CLEAR_TERMINAL_TITLE=`${OSC_PREFIX}${OSC.SET_TITLE_AND_ICON};${r}`;export const CLEAR_TAB_STATUS=osc(OSC.TAB_STATUS,"indicator=;status=;status-color=");export function supportsTabStatus(){return"ant"===process.env.USER_TYPE}export function tabStatus(t){const e=[],rgb=t=>"rgb"===t.type?`#${[t.r,t.g,t.b].map(t=>t.toString(16).padStart(2,"0")).join("")}`:"";return"indicator"in t&&e.push(`indicator=${t.indicator?rgb(t.indicator):""}`),"status"in t&&e.push(`status=${t.status?.replaceAll("\\","\\\\").replaceAll(";","\\;")??""}`),"statusColor"in t&&e.push(`status-color=${t.statusColor?rgb(t.statusColor):""}`),osc(OSC.TAB_STATUS,e.join(";"))}
@@ -1 +1 @@
1
- import{getGraphemeSegmenter as e}from"../../utils/intl.js";import{C0 as t}from"./ansi.js";import{CSI as r,CURSOR_STYLES as n,ERASE_DISPLAY as o,ERASE_LINE_REGION as s}from"./csi.js";import{DEC as i}from"./dec.js";import{parseEsc as c}from"./esc.js";import{parseOSC as p}from"./osc.js";import{applySGR as u}from"./sgr.js";import{createTokenizer as a}from"./tokenize.js";import{defaultStyle as y}from"./types.js";function graphemeWidth(e){if(function(e){let t=0;for(const r of e)if(t++,t>1)return!0;return!1}(e))return 2;const t=e.codePointAt(0);return void 0===t?1:function(e){return e>=9728&&e<=9983||e>=9984&&e<=10175||e>=127744&&e<=129535||e>=129536&&e<=129791||e>=127456&&e<=127487}(t)||function(e){return e>=4352&&e<=4447||e>=11904&&e<=40959||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65055||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072&&e<=196605||e>=196608&&e<=262141}(t)?2:1}function*segmentGraphemes(t){for(const{segment:r}of e().segment(t))yield{value:r,width:graphemeWidth(r)}}function parseCSI(e){const t=e.slice(2);if(0===t.length)return null;const c=t.charCodeAt(t.length-1),p=t.slice(0,-1);let u="",a=p,y="";p.length>0&&"?>=".includes(p[0])&&(u=p[0],a=p.slice(1));const f=a.match(/([^0-9;:]+)$/);f&&(y=f[1],a=a.slice(0,-y.length));const l=function(e){return""===e?[]:e.split(/[;:]/).map(e=>""===e?0:parseInt(e,10))}(a),m=l[0]??1,h=l[1]??1;if(c===r.SGR&&""===u)return{type:"sgr",params:a};if(c===r.CUU)return{type:"cursor",action:{type:"move",direction:"up",count:m}};if(c===r.CUD)return{type:"cursor",action:{type:"move",direction:"down",count:m}};if(c===r.CUF)return{type:"cursor",action:{type:"move",direction:"forward",count:m}};if(c===r.CUB)return{type:"cursor",action:{type:"move",direction:"back",count:m}};if(c===r.CNL)return{type:"cursor",action:{type:"nextLine",count:m}};if(c===r.CPL)return{type:"cursor",action:{type:"prevLine",count:m}};if(c===r.CHA)return{type:"cursor",action:{type:"column",col:m}};if(c===r.CUP||c===r.HVP)return{type:"cursor",action:{type:"position",row:m,col:h}};if(c===r.VPA)return{type:"cursor",action:{type:"row",row:m}};if(c===r.ED)return{type:"erase",action:{type:"display",region:o[l[0]??0]??"toEnd"}};if(c===r.EL)return{type:"erase",action:{type:"line",region:s[l[0]??0]??"toEnd"}};if(c===r.ECH)return{type:"erase",action:{type:"chars",count:m}};if(c===r.SU)return{type:"scroll",action:{type:"up",count:m}};if(c===r.SD)return{type:"scroll",action:{type:"down",count:m}};if(c===r.DECSTBM)return{type:"scroll",action:{type:"setRegion",top:m,bottom:h}};if(c===r.SCOSC)return{type:"cursor",action:{type:"save"}};if(c===r.SCORC)return{type:"cursor",action:{type:"restore"}};if(c===r.DECSCUSR&&" "===y)return{type:"cursor",action:{type:"style",...n[m]??n[0]}};if("?"===u&&(c===r.SM||c===r.RM)){const e=c===r.SM;if(m===i.CURSOR_VISIBLE)return{type:"cursor",action:e?{type:"show"}:{type:"hide"}};if(m===i.ALT_SCREEN_CLEAR||m===i.ALT_SCREEN)return{type:"mode",action:{type:"alternateScreen",enabled:e}};if(m===i.BRACKETED_PASTE)return{type:"mode",action:{type:"bracketedPaste",enabled:e}};if(m===i.MOUSE_NORMAL)return{type:"mode",action:{type:"mouseTracking",mode:e?"normal":"off"}};if(m===i.MOUSE_BUTTON)return{type:"mode",action:{type:"mouseTracking",mode:e?"button":"off"}};if(m===i.MOUSE_ANY)return{type:"mode",action:{type:"mouseTracking",mode:e?"any":"off"}};if(m===i.FOCUS_EVENTS)return{type:"mode",action:{type:"focusEvents",enabled:e}}}return{type:"unknown",sequence:e}}export class Parser{tokenizer=a();style=y();inLink=!1;linkUrl;reset(){this.tokenizer.reset(),this.style=y(),this.inLink=!1,this.linkUrl=void 0}feed(e){const t=this.tokenizer.feed(e),r=[];for(const e of t){const t=this.processToken(e);r.push(...t)}return r}processToken(e){switch(e.type){case"text":return this.processText(e.value);case"sequence":return this.processSequence(e.value)}}processText(e){const r=[];let n="";for(const o of e)if(o.charCodeAt(0)===t.BEL){if(n){const e=[...segmentGraphemes(n)];e.length>0&&r.push({type:"text",graphemes:e,style:{...this.style}}),n=""}r.push({type:"bell"})}else n+=o;if(n){const e=[...segmentGraphemes(n)];e.length>0&&r.push({type:"text",graphemes:e,style:{...this.style}})}return r}processSequence(e){const r=function(e){if(e.length<2)return"unknown";if(e.charCodeAt(0)!==t.ESC)return"unknown";const r=e.charCodeAt(1);return 91===r?"csi":93===r?"osc":79===r?"ss3":"esc"}(e);switch(r){case"csi":{const t=parseCSI(e);return t?"sgr"===t.type?(this.style=u(t.params,this.style),[]):[t]:[]}case"osc":{let t=e.slice(2);t.endsWith("")?t=t.slice(0,-1):t.endsWith("\\")&&(t=t.slice(0,-2));const r=p(t);return r?("link"===r.type&&("start"===r.action.type?(this.inLink=!0,this.linkUrl=r.action.url):(this.inLink=!1,this.linkUrl=void 0)),[r]):[]}case"esc":{const t=e.slice(1),r=c(t);return r?[r]:[]}default:return[{type:"unknown",sequence:e}]}}}
1
+ import{getGraphemeSegmenter as e}from"../../utils/intl.js";import{C0 as t}from"./ansi.js";import{CSI as r,CURSOR_STYLES as n,ERASE_DISPLAY as o,ERASE_LINE_REGION as s}from"./csi.js";import{DEC as i}from"./dec.js";import{parseEsc as c}from"./esc.js";import{parseOSC as u}from"./osc.js";import{applySGR as p}from"./sgr.js";import{createTokenizer as a}from"./tokenize.js";import{defaultStyle as y}from"./types.js";function graphemeWidth(e){if(function(e){let t=0;for(const r of e)if(t++,t>1)return!0;return!1}(e))return 2;const t=e.codePointAt(0);return void 0===t?1:function(e){return e>=9728&&e<=9983||e>=9984&&e<=10175||e>=127744&&e<=129535||e>=129536&&e<=129791||e>=127456&&e<=127487}(t)||function(e){return e>=4352&&e<=4447||e>=11904&&e<=40959||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65055||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072&&e<=196605||e>=196608&&e<=262141}(t)?2:1}function*segmentGraphemes(t){for(const{segment:r}of e().segment(t))yield{value:r,width:graphemeWidth(r)}}function parseCSI(e){const t=e.slice(2);if(0===t.length)return null;const c=t.charCodeAt(t.length-1),u=t.slice(0,-1);let p="",a=u,y="";u.length>0&&"?>=".includes(u[0])&&(p=u[0],a=u.slice(1));const f=a.match(/([^0-9;:]+)$/);f&&(y=f[1],a=a.slice(0,-y.length));const l=function(e){return""===e?[]:e.split(/[;:]/).map(e=>""===e?0:parseInt(e,10))}(a),m=l[0]??1,h=l[1]??1;if(c===r.SGR&&""===p)return{type:"sgr",params:a};if(c===r.CUU)return{type:"cursor",action:{type:"move",direction:"up",count:m}};if(c===r.CUD)return{type:"cursor",action:{type:"move",direction:"down",count:m}};if(c===r.CUF)return{type:"cursor",action:{type:"move",direction:"forward",count:m}};if(c===r.CUB)return{type:"cursor",action:{type:"move",direction:"back",count:m}};if(c===r.CNL)return{type:"cursor",action:{type:"nextLine",count:m}};if(c===r.CPL)return{type:"cursor",action:{type:"prevLine",count:m}};if(c===r.CHA)return{type:"cursor",action:{type:"column",col:m}};if(c===r.CUP||c===r.HVP)return{type:"cursor",action:{type:"position",row:m,col:h}};if(c===r.VPA)return{type:"cursor",action:{type:"row",row:m}};if(c===r.ED){return{type:"erase",action:{type:"display",region:o[l[0]??0]??"toEnd"}}}if(c===r.EL){return{type:"erase",action:{type:"line",region:s[l[0]??0]??"toEnd"}}}if(c===r.ECH)return{type:"erase",action:{type:"chars",count:m}};if(c===r.SU)return{type:"scroll",action:{type:"up",count:m}};if(c===r.SD)return{type:"scroll",action:{type:"down",count:m}};if(c===r.DECSTBM)return{type:"scroll",action:{type:"setRegion",top:m,bottom:h}};if(c===r.SCOSC)return{type:"cursor",action:{type:"save"}};if(c===r.SCORC)return{type:"cursor",action:{type:"restore"}};if(c===r.DECSCUSR&&" "===y){return{type:"cursor",action:{type:"style",...n[m]??n[0]}}}if("?"===p&&(c===r.SM||c===r.RM)){const e=c===r.SM;if(m===i.CURSOR_VISIBLE)return{type:"cursor",action:e?{type:"show"}:{type:"hide"}};if(m===i.ALT_SCREEN_CLEAR||m===i.ALT_SCREEN)return{type:"mode",action:{type:"alternateScreen",enabled:e}};if(m===i.BRACKETED_PASTE)return{type:"mode",action:{type:"bracketedPaste",enabled:e}};if(m===i.MOUSE_NORMAL)return{type:"mode",action:{type:"mouseTracking",mode:e?"normal":"off"}};if(m===i.MOUSE_BUTTON)return{type:"mode",action:{type:"mouseTracking",mode:e?"button":"off"}};if(m===i.MOUSE_ANY)return{type:"mode",action:{type:"mouseTracking",mode:e?"any":"off"}};if(m===i.FOCUS_EVENTS)return{type:"mode",action:{type:"focusEvents",enabled:e}}}return{type:"unknown",sequence:e}}export class Parser{tokenizer=a();style=y();inLink=!1;linkUrl;reset(){this.tokenizer.reset(),this.style=y(),this.inLink=!1,this.linkUrl=void 0}feed(e){const t=this.tokenizer.feed(e),r=[];for(const e of t){const t=this.processToken(e);r.push(...t)}return r}processToken(e){switch(e.type){case"text":return this.processText(e.value);case"sequence":return this.processSequence(e.value)}}processText(e){const r=[];let n="";for(const o of e)if(o.charCodeAt(0)===t.BEL){if(n){const e=[...segmentGraphemes(n)];e.length>0&&r.push({type:"text",graphemes:e,style:{...this.style}}),n=""}r.push({type:"bell"})}else n+=o;if(n){const e=[...segmentGraphemes(n)];e.length>0&&r.push({type:"text",graphemes:e,style:{...this.style}})}return r}processSequence(e){const r=function(e){if(e.length<2)return"unknown";if(e.charCodeAt(0)!==t.ESC)return"unknown";const r=e.charCodeAt(1);return 91===r?"csi":93===r?"osc":79===r?"ss3":"esc"}(e);switch(r){case"csi":{const t=parseCSI(e);return t?"sgr"===t.type?(this.style=p(t.params,this.style),[]):[t]:[]}case"osc":{let t=e.slice(2);t.endsWith("")?t=t.slice(0,-1):t.endsWith("\\")&&(t=t.slice(0,-2));const r=u(t);return r?("link"===r.type&&("start"===r.action.type?(this.inLink=!0,this.linkUrl=r.action.url):(this.inLink=!1,this.linkUrl=void 0)),[r]):[]}case"esc":{const t=e.slice(1),r=c(t);return r?[r]:[]}default:return[{type:"unknown",sequence:e}]}}}
@@ -1 +1 @@
1
- import{C0 as e,ESC_TYPE as t,isEscFinal as s}from"./ansi.js";import{isCSIFinal as a,isCSIIntermediate as c,isCSIParam as n}from"./csi.js";export function createTokenizer(e){let t="ground",s="";const a=e?.x10Mouse??!1;return{feed(e){const c=tokenize(e,t,s,!1,a);return t=c.state.state,s=c.state.buffer,c.tokens},flush(){const e=tokenize("",t,s,!0,a);return t=e.state.state,s=e.state.buffer,e.tokens},reset(){t="ground",s=""},buffer:()=>s}}function tokenize(r,o,i,u,l){const d=[],f={state:o,buffer:""},g=i+r;let h=0,C=0,p=0;const flushText=()=>{if(h>C){const e=g.slice(C,h);e&&d.push({type:"text",value:e})}C=h},emitSequence=e=>{e&&d.push({type:"sequence",value:e}),f.state="ground",C=h};for(;h<g.length;){const r=g.charCodeAt(h);switch(f.state){case"ground":r===e.ESC?(flushText(),p=h,f.state="escape",h++):h++;break;case"escape":r===t.CSI?(f.state="csi",h++):r===t.OSC?(f.state="osc",h++):r===t.DCS?(f.state="dcs",h++):r===t.APC?(f.state="apc",h++):79===r?(f.state="ss3",h++):c(r)?(f.state="escapeIntermediate",h++):s(r)?(h++,emitSequence(g.slice(p,h))):r===e.ESC?(emitSequence(g.slice(p,h)),p=h,f.state="escape",h++):(f.state="ground",C=p);break;case"escapeIntermediate":c(r)?h++:s(r)?(h++,emitSequence(g.slice(p,h))):(f.state="ground",C=p);break;case"csi":if(l&&77===r&&h-p===2&&(h+1>=g.length||g.charCodeAt(h+1)>=32)&&(h+2>=g.length||g.charCodeAt(h+2)>=32)&&(h+3>=g.length||g.charCodeAt(h+3)>=32)){h+4<=g.length?(h+=4,emitSequence(g.slice(p,h))):h=g.length;break}a(r)?(h++,emitSequence(g.slice(p,h))):n(r)||c(r)?h++:(f.state="ground",C=p);break;case"ss3":r>=64&&r<=126?(h++,emitSequence(g.slice(p,h))):(f.state="ground",C=p);break;case"osc":case"dcs":case"apc":r===e.BEL?(h++,emitSequence(g.slice(p,h))):r===e.ESC&&h+1<g.length&&g.charCodeAt(h+1)===t.ST?(h+=2,emitSequence(g.slice(p,h))):h++}}if("ground"===f.state)flushText();else if(u){const e=g.slice(p);e&&d.push({type:"sequence",value:e}),f.state="ground"}else f.buffer=g.slice(p);return{tokens:d,state:f}}
1
+ import{C0 as e,ESC_TYPE as t,isEscFinal as s}from"./ansi.js";import{isCSIFinal as a,isCSIIntermediate as c,isCSIParam as n}from"./csi.js";export function createTokenizer(e){let t="ground",s="";const a=e?.x10Mouse??!1;return{feed(e){const c=tokenize(e,t,s,!1,a);return t=c.state.state,s=c.state.buffer,c.tokens},flush(){const e=tokenize("",t,s,!0,a);return t=e.state.state,s=e.state.buffer,e.tokens},reset(){t="ground",s=""},buffer:()=>s}}function tokenize(r,o,u,i,l){const f=[],d={state:o,buffer:""},g=u+r;let h=0,p=0,k=0;const flushText=()=>{if(h>p){const e=g.slice(p,h);e&&f.push({type:"text",value:e})}p=h},emitSequence=e=>{e&&f.push({type:"sequence",value:e}),d.state="ground",p=h};for(;h<g.length;){const r=g.charCodeAt(h);switch(d.state){case"ground":r===e.ESC?(flushText(),k=h,d.state="escape",h++):h++;break;case"escape":r===t.CSI?(d.state="csi",h++):r===t.OSC?(d.state="osc",h++):r===t.DCS?(d.state="dcs",h++):r===t.APC?(d.state="apc",h++):79===r?(d.state="ss3",h++):c(r)?(d.state="escapeIntermediate",h++):s(r)?(h++,emitSequence(g.slice(k,h))):r===e.ESC?(emitSequence(g.slice(k,h)),k=h,d.state="escape",h++):(d.state="ground",p=k);break;case"escapeIntermediate":c(r)?h++:s(r)?(h++,emitSequence(g.slice(k,h))):(d.state="ground",p=k);break;case"csi":if(l&&77===r&&h-k===2&&(h+1>=g.length||g.charCodeAt(h+1)>=32)&&(h+2>=g.length||g.charCodeAt(h+2)>=32)&&(h+3>=g.length||g.charCodeAt(h+3)>=32)){h+4<=g.length?(h+=4,emitSequence(g.slice(k,h))):h=g.length;break}a(r)?(h++,emitSequence(g.slice(k,h))):n(r)||c(r)?h++:(d.state="ground",p=k);break;case"ss3":r>=64&&r<=126?(h++,emitSequence(g.slice(k,h))):(d.state="ground",p=k);break;case"osc":case"dcs":case"apc":r===e.BEL?(h++,emitSequence(g.slice(k,h))):r===e.ESC&&h+1<g.length&&g.charCodeAt(h+1)===t.ST?(h+=2,emitSequence(g.slice(k,h))):h++}}if("ground"===d.state)flushText();else if(i){const e=g.slice(k);e&&f.push({type:"sequence",value:e}),d.state="ground"}else d.buffer=g.slice(k);return{tokens:f,state:d}}
@@ -1 +1 @@
1
- import{createContext as e,useCallback as t,useContext as r,useMemo as i}from"react";import{isProgressReportingAvailable as o}from"./terminal.js";import{BEL as s}from"./termio/ansi.js";import{ITERM2 as n,OSC as a,osc as m,PROGRESS as R,wrapForMultiplexer as T}from"./termio/osc.js";export const TerminalWriteContext=e(null);export const TerminalWriteProvider=TerminalWriteContext.Provider;export function useTerminalNotification(){const e=r(TerminalWriteContext);if(!e)throw new Error("useTerminalNotification must be used within TerminalWriteProvider");const l=t(({message:t,title:r})=>{const i=r?`${r}:\n${t}`:t;e(T(m(a.ITERM2,`\n\n${i}`)))},[e]),E=t(({message:t,title:r,id:i})=>{e(T(m(a.KITTY,`i=${i}:d=0:p=title`,r))),e(T(m(a.KITTY,`i=${i}:p=body`,t))),e(T(m(a.KITTY,`i=${i}:d=1:a=focus`,"")))},[e]),c=t(({message:t,title:r})=>{e(T(m(a.GHOSTTY,"notify",r,t)))},[e]),f=t(()=>{e(s)},[e]),u=t((t,r)=>{if(!o())return;if(!t)return void e(T(m(a.ITERM2,n.PROGRESS,R.CLEAR,"")));const i=Math.max(0,Math.min(100,Math.round(r??0)));switch(t){case"completed":e(T(m(a.ITERM2,n.PROGRESS,R.CLEAR,"")));break;case"error":e(T(m(a.ITERM2,n.PROGRESS,R.ERROR,i)));break;case"indeterminate":e(T(m(a.ITERM2,n.PROGRESS,R.INDETERMINATE,"")));break;case"running":e(T(m(a.ITERM2,n.PROGRESS,R.SET,i)))}},[e]);return i(()=>({notifyITerm2:l,notifyKitty:E,notifyGhostty:c,notifyBell:f,progress:u}),[l,E,c,f,u])}
1
+ import{createContext as t,useCallback as e,useContext as i,useMemo as r}from"react";import{isProgressReportingAvailable as o}from"./terminal.js";import{BEL as n}from"./termio/ansi.js";import{ITERM2 as s,OSC as a,osc as m,PROGRESS as T,wrapForMultiplexer as R}from"./termio/osc.js";export const TerminalWriteContext=t(null);export const TerminalWriteProvider=TerminalWriteContext.Provider;export function useTerminalNotification(){const t=i(TerminalWriteContext);if(!t)throw new Error("useTerminalNotification must be used within TerminalWriteProvider");const E=e(({message:e,title:i})=>{const r=i?`${i}:\n${e}`:e;t(R(m(a.ITERM2,`\n\n${r}`)))},[t]),c=e(({message:e,title:i,id:r})=>{t(R(m(a.KITTY,`i=${r}:d=0:p=title`,i))),t(R(m(a.KITTY,`i=${r}:p=body`,e))),t(R(m(a.KITTY,`i=${r}:d=1:a=focus`,"")))},[t]),l=e(({message:e,title:i})=>{t(R(m(a.GHOSTTY,"notify",i,e)))},[t]),f=e(()=>{t(n)},[t]),d=e((e,i)=>{if(!o())return;if(!e)return void t(R(m(a.ITERM2,s.PROGRESS,T.CLEAR,"")));const r=Math.max(0,Math.min(100,Math.round(i??0)));switch(e){case"completed":t(R(m(a.ITERM2,s.PROGRESS,T.CLEAR,"")));break;case"error":t(R(m(a.ITERM2,s.PROGRESS,T.ERROR,r)));break;case"indeterminate":t(R(m(a.ITERM2,s.PROGRESS,T.INDETERMINATE,"")));break;case"running":t(R(m(a.ITERM2,s.PROGRESS,T.SET,r)))}},[t]);return r(()=>({notifyITerm2:E,notifyKitty:c,notifyGhostty:l,notifyBell:f,progress:d}),[E,c,l,f,d])}
@@ -1 +1 @@
1
- import{logForDebugging as e}from"../utils/debug.js";export function ifNotInteger(o,g){void 0!==o&&(Number.isInteger(o)||e(`${g} should be an integer, got ${o}`,{level:"warn"}))}
1
+ import{logForDebugging as e}from"../utils/debug.js";export function ifNotInteger(t,o){void 0!==t&&(Number.isInteger(t)||e(`${o} should be an integer, got ${t}`,{level:"warn"}))}
@@ -1 +1 @@
1
- import{lineWidth as t}from"./line-width-cache.js";export function widestLine(i){let n=0,e=0;for(;e<=i.length;){const r=i.indexOf("\n",e),s=-1===r?i.substring(e):i.substring(e,r);if(n=Math.max(n,t(s)),-1===r)break;e=r+1}return n}
1
+ import{lineWidth as t}from"./line-width-cache.js";export function widestLine(n){let e=0,i=0;for(;i<=n.length;){const r=n.indexOf("\n",i),s=-1===r?n.substring(i):n.substring(i,r);if(e=Math.max(e,t(s)),-1===r)break;i=r+1}return e}
@@ -1 +1 @@
1
- import t from"../utils/sliceAnsi.js";import{stringWidth as r}from"./stringWidth.js";import{wrapAnsi as i}from"./wrapAnsi.js";const n="…";function sliceFit(i,n,e){const s=t(i,n,e);return r(s)>e-n?t(i,n,e-1):s}export default function wrapText(t,e,s){if("wrap"===s)return i(t,e,{trim:!1,hard:!0});if("wrap-trim"===s)return i(t,e,{trim:!0,hard:!0});if(s.startsWith("truncate")){let i="end";return"truncate-middle"===s&&(i="middle"),"truncate-start"===s&&(i="start"),function(t,i,e){if(i<1)return"";if(1===i)return n;const s=r(t);if(s<=i)return t;if("start"===e)return n+sliceFit(t,s-i+1,s);if("middle"===e){const r=Math.floor(i/2);return sliceFit(t,0,r)+n+sliceFit(t,s-(i-r)+1,s)}return sliceFit(t,0,i-1)+n}(t,e,i)}return t}
1
+ import t from"../utils/sliceAnsi.js";import{stringWidth as r}from"./stringWidth.js";import{wrapAnsi as i}from"./wrapAnsi.js";const e="…";function sliceFit(i,e,n){const s=t(i,e,n);return r(s)>n-e?t(i,e,n-1):s}export default function wrapText(t,n,s){if("wrap"===s)return i(t,n,{trim:!1,hard:!0});if("wrap-trim"===s)return i(t,n,{trim:!0,hard:!0});if(s.startsWith("truncate")){let i="end";return"truncate-middle"===s&&(i="middle"),"truncate-start"===s&&(i="start"),function(t,i,n){if(i<1)return"";if(1===i)return e;const s=r(t);if(s<=i)return t;if("start"===n)return e+sliceFit(t,s-i+1,s);if("middle"===n){const r=Math.floor(i/2);return sliceFit(t,0,r)+e+sliceFit(t,s-(i-r)+1,s)}return sliceFit(t,0,i-1)+e}(t,n,i)}return t}
@@ -1 +1 @@
1
- import n from"wrap-ansi";const p=("undefined"!=typeof Bun&&"function"==typeof Bun.wrapAnsi?Bun.wrapAnsi:null)??n;export{p as wrapAnsi};
1
+ import n from"wrap-ansi";const o=("undefined"!=typeof Bun&&"function"==typeof Bun.wrapAnsi?Bun.wrapAnsi:null)??n;export{o as wrapAnsi};
@@ -1 +1 @@
1
- import{Align as e,BoxSizing as t,Dimension as i,Direction as s,Display as n,Edge as a,Errata as r,ExperimentalFeature as l,FlexDirection as o,Gutter as u,Justify as h,MeasureMode as c,Overflow as f,PositionType as d,Unit as y,Wrap as g}from"./enums.js";export{e as Align,t as BoxSizing,i as Dimension,s as Direction,n as Display,a as Edge,r as Errata,l as ExperimentalFeature,o as FlexDirection,u as Gutter,h as Justify,c as MeasureMode,f as Overflow,d as PositionType,y as Unit,g as Wrap};const m={unit:y.Undefined,value:NaN},_={unit:y.Auto,value:NaN};function pointValue(e){return{unit:y.Point,value:e}}function percentValue(e){return{unit:y.Percent,value:e}}function resolveValue(e,t){switch(e.unit){case y.Point:return e.value;case y.Percent:return isNaN(t)?NaN:e.value*t/100;default:return NaN}}function isDefined(e){return!isNaN(e)}function sameFloat(e,t){return e===t||e!=e&&t!=t}function defaultStyle(){return{direction:s.Inherit,flexDirection:o.Column,justifyContent:h.FlexStart,alignItems:e.Stretch,alignSelf:e.Auto,alignContent:e.FlexStart,flexWrap:g.NoWrap,overflow:f.Visible,display:n.Flex,positionType:d.Relative,flexGrow:0,flexShrink:0,flexBasis:_,margin:new Array(9).fill(m),padding:new Array(9).fill(m),border:new Array(9).fill(m),position:new Array(9).fill(m),gap:new Array(3).fill(m),width:_,height:_,minWidth:m,minHeight:m,maxWidth:m,maxHeight:m}}function resolveEdge(e,t,i,s=!1){let n=e[t];return n.unit===y.Undefined&&(n=0===t||2===t?e[a.Horizontal]:e[a.Vertical]),n.unit===y.Undefined&&(n=e[a.All]),n.unit===y.Undefined&&(0===t&&(n=e[a.Start]),2===t&&(n=e[a.End])),n.unit===y.Undefined?0:n.unit===y.Auto?s?NaN:0:resolveValue(n,i)}function resolveEdgeRaw(e,t){let i=e[t];return i.unit===y.Undefined&&(i=0===t||2===t?e[a.Horizontal]:e[a.Vertical]),i.unit===y.Undefined&&(i=e[a.All]),i.unit===y.Undefined&&(0===t&&(i=e[a.Start]),2===t&&(i=e[a.End])),i}function isMarginAuto(e,t){return resolveEdgeRaw(e,t).unit===y.Auto}function hasAnyAutoEdge(e){for(let t=0;t<9;t++)if(3===e[t].unit)return!0;return!1}function hasAnyDefinedEdge(e){for(let t=0;t<9;t++)if(0!==e[t].unit)return!0;return!1}function resolveEdges4Into(e,t,i){const s=e[6],n=e[7],a=e[8],r=e[4],l=e[5],o=isNaN(t)?NaN:t/100;let u=e[0];0===u.unit&&(u=s),0===u.unit&&(u=a),0===u.unit&&(u=r),i[0]=1===u.unit?u.value:2===u.unit?u.value*o:0,u=e[1],0===u.unit&&(u=n),0===u.unit&&(u=a),i[1]=1===u.unit?u.value:2===u.unit?u.value*o:0,u=e[2],0===u.unit&&(u=s),0===u.unit&&(u=a),0===u.unit&&(u=l),i[2]=1===u.unit?u.value:2===u.unit?u.value*o:0,u=e[3],0===u.unit&&(u=n),0===u.unit&&(u=a),i[3]=1===u.unit?u.value:2===u.unit?u.value*o:0}function isRow(e){return e===o.Row||e===o.RowReverse}function isReverse(e){return e===o.RowReverse||e===o.ColumnReverse}function leadingEdge(e){switch(e){case o.Row:return 0;case o.RowReverse:return 2;case o.Column:return 1;case o.ColumnReverse:return 3}}function trailingEdge(e){switch(e){case o.Row:return 2;case o.RowReverse:return 0;case o.Column:return 3;case o.ColumnReverse:return 1}}function createConfig(){const e={pointScaleFactor:1,errata:r.None,useWebDefaults:!1,free(){},isExperimentalFeatureEnabled:()=>!1,setExperimentalFeatureEnabled(){},setPointScaleFactor(t){e.pointScaleFactor=t},getErrata:()=>e.errata,setErrata(t){e.errata=t},setUseWebDefaults(t){e.useWebDefaults=t}};return e}export class Node{style;layout;parent;children;measureFunc;config;isDirty_;isReferenceBaseline_;_flexBasis=0;_mainSize=0;_crossSize=0;_lineIndex=0;_hasAutoMargin=!1;_hasPosition=!1;_hasPadding=!1;_hasBorder=!1;_hasMargin=!1;_lW=NaN;_lH=NaN;_lWM=0;_lHM=0;_lOW=NaN;_lOH=NaN;_lFW=!1;_lFH=!1;_lOutW=NaN;_lOutH=NaN;_hasL=!1;_mW=NaN;_mH=NaN;_mWM=0;_mHM=0;_mOW=NaN;_mOH=NaN;_mOutW=NaN;_mOutH=NaN;_hasM=!1;_fbBasis=NaN;_fbOwnerW=NaN;_fbOwnerH=NaN;_fbAvailMain=NaN;_fbAvailCross=NaN;_fbCrossMode=0;_fbGen=-1;_cIn=null;_cOut=null;_cGen=-1;_cN=0;_cWr=0;constructor(e){this.style=defaultStyle(),this.layout={left:0,top:0,width:0,height:0,border:[0,0,0,0],padding:[0,0,0,0],margin:[0,0,0,0]},this.parent=null,this.children=[],this.measureFunc=null,this.config=e??p,this.isDirty_=!0,this.isReferenceBaseline_=!1,M++}insertChild(e,t){e.parent=this,this.children.splice(t,0,e),this.markDirty()}removeChild(e){const t=this.children.indexOf(e);t>=0&&(this.children.splice(t,1),e.parent=null,this.markDirty())}getChild(e){return this.children[e]}getChildCount(){return this.children.length}getParent(){return this.parent}free(){this.parent=null,this.children=[],this.measureFunc=null,this._cIn=null,this._cOut=null,M--}freeRecursive(){for(const e of this.children)e.freeRecursive();this.free()}reset(){this.style=defaultStyle(),this.children=[],this.parent=null,this.measureFunc=null,this.isDirty_=!0,this._hasAutoMargin=!1,this._hasPosition=!1,this._hasPadding=!1,this._hasBorder=!1,this._hasMargin=!1,this._hasL=!1,this._hasM=!1,this._cN=0,this._cWr=0,this._fbBasis=NaN}markDirty(){this.isDirty_=!0,this.parent&&!this.parent.isDirty_&&this.parent.markDirty()}isDirty(){return this.isDirty_}hasNewLayout(){return!0}markLayoutSeen(){}setMeasureFunc(e){this.measureFunc=e,this.markDirty()}unsetMeasureFunc(){this.measureFunc=null,this.markDirty()}getComputedLeft(){return this.layout.left}getComputedTop(){return this.layout.top}getComputedWidth(){return this.layout.width}getComputedHeight(){return this.layout.height}getComputedRight(){const e=this.parent;return e?e.layout.width-this.layout.left-this.layout.width:0}getComputedBottom(){const e=this.parent;return e?e.layout.height-this.layout.top-this.layout.height:0}getComputedLayout(){return{left:this.layout.left,top:this.layout.top,right:this.getComputedRight(),bottom:this.getComputedBottom(),width:this.layout.width,height:this.layout.height}}getComputedBorder(e){return this.layout.border[physicalEdge(e)]}getComputedPadding(e){return this.layout.padding[physicalEdge(e)]}getComputedMargin(e){return this.layout.margin[physicalEdge(e)]}setWidth(e){this.style.width=parseDimension(e),this.markDirty()}setWidthPercent(e){this.style.width=percentValue(e),this.markDirty()}setWidthAuto(){this.style.width=_,this.markDirty()}setHeight(e){this.style.height=parseDimension(e),this.markDirty()}setHeightPercent(e){this.style.height=percentValue(e),this.markDirty()}setHeightAuto(){this.style.height=_,this.markDirty()}setMinWidth(e){this.style.minWidth=parseDimension(e),this.markDirty()}setMinWidthPercent(e){this.style.minWidth=percentValue(e),this.markDirty()}setMinHeight(e){this.style.minHeight=parseDimension(e),this.markDirty()}setMinHeightPercent(e){this.style.minHeight=percentValue(e),this.markDirty()}setMaxWidth(e){this.style.maxWidth=parseDimension(e),this.markDirty()}setMaxWidthPercent(e){this.style.maxWidth=percentValue(e),this.markDirty()}setMaxHeight(e){this.style.maxHeight=parseDimension(e),this.markDirty()}setMaxHeightPercent(e){this.style.maxHeight=percentValue(e),this.markDirty()}setFlexDirection(e){this.style.flexDirection=e,this.markDirty()}setFlexGrow(e){this.style.flexGrow=e??0,this.markDirty()}setFlexShrink(e){this.style.flexShrink=e??0,this.markDirty()}setFlex(e){void 0===e||isNaN(e)?(this.style.flexGrow=0,this.style.flexShrink=0):e>0?(this.style.flexGrow=e,this.style.flexShrink=1,this.style.flexBasis=pointValue(0)):e<0?(this.style.flexGrow=0,this.style.flexShrink=-e):(this.style.flexGrow=0,this.style.flexShrink=0),this.markDirty()}setFlexBasis(e){this.style.flexBasis=parseDimension(e),this.markDirty()}setFlexBasisPercent(e){this.style.flexBasis=percentValue(e),this.markDirty()}setFlexBasisAuto(){this.style.flexBasis=_,this.markDirty()}setFlexWrap(e){this.style.flexWrap=e,this.markDirty()}setAlignItems(e){this.style.alignItems=e,this.markDirty()}setAlignSelf(e){this.style.alignSelf=e,this.markDirty()}setAlignContent(e){this.style.alignContent=e,this.markDirty()}setJustifyContent(e){this.style.justifyContent=e,this.markDirty()}setDisplay(e){this.style.display=e,this.markDirty()}getDisplay(){return this.style.display}setPositionType(e){this.style.positionType=e,this.markDirty()}setPosition(e,t){this.style.position[e]=parseDimension(t),this._hasPosition=hasAnyDefinedEdge(this.style.position),this.markDirty()}setPositionPercent(e,t){this.style.position[e]=percentValue(t),this._hasPosition=!0,this.markDirty()}setPositionAuto(e){this.style.position[e]=_,this._hasPosition=!0,this.markDirty()}setOverflow(e){this.style.overflow=e,this.markDirty()}setDirection(e){this.style.direction=e,this.markDirty()}setBoxSizing(e){}setMargin(e,t){const i=parseDimension(t);this.style.margin[e]=i,i.unit===y.Auto?this._hasAutoMargin=!0:this._hasAutoMargin=hasAnyAutoEdge(this.style.margin),this._hasMargin=this._hasAutoMargin||hasAnyDefinedEdge(this.style.margin),this.markDirty()}setMarginPercent(e,t){this.style.margin[e]=percentValue(t),this._hasAutoMargin=hasAnyAutoEdge(this.style.margin),this._hasMargin=!0,this.markDirty()}setMarginAuto(e){this.style.margin[e]=_,this._hasAutoMargin=!0,this._hasMargin=!0,this.markDirty()}setPadding(e,t){this.style.padding[e]=parseDimension(t),this._hasPadding=hasAnyDefinedEdge(this.style.padding),this.markDirty()}setPaddingPercent(e,t){this.style.padding[e]=percentValue(t),this._hasPadding=!0,this.markDirty()}setBorder(e,t){this.style.border[e]=void 0===t?m:pointValue(t),this._hasBorder=hasAnyDefinedEdge(this.style.border),this.markDirty()}setGap(e,t){this.style.gap[e]=parseDimension(t),this.markDirty()}setGapPercent(e,t){this.style.gap[e]=percentValue(t),this.markDirty()}getFlexDirection(){return this.style.flexDirection}getJustifyContent(){return this.style.justifyContent}getAlignItems(){return this.style.alignItems}getAlignSelf(){return this.style.alignSelf}getAlignContent(){return this.style.alignContent}getFlexGrow(){return this.style.flexGrow}getFlexShrink(){return this.style.flexShrink}getFlexBasis(){return this.style.flexBasis}getFlexWrap(){return this.style.flexWrap}getWidth(){return this.style.width}getHeight(){return this.style.height}getOverflow(){return this.style.overflow}getPositionType(){return this.style.positionType}getDirection(){return this.style.direction}copyStyle(e){}setDirtiedFunc(e){}unsetDirtiedFunc(){}setIsReferenceBaseline(e){this.isReferenceBaseline_=e,this.markDirty()}isReferenceBaseline(){return this.isReferenceBaseline_}setAspectRatio(e){}getAspectRatio(){return NaN}setAlwaysFormsContainingBlock(e){}calculateLayout(e,t,i){v=0,w=0,A=0,D++;const s=void 0===e?NaN:e,n=void 0===t?NaN:t;layoutNode(this,s,n,isDefined(s)?c.Exactly:c.Undefined,isDefined(n)?c.Exactly:c.Undefined,s,n,!0);const a=this.layout.margin,r=resolveValue(resolveEdgeRaw(this.style.position,0),isDefined(s)?s:0),l=resolveValue(resolveEdgeRaw(this.style.position,1),isDefined(s)?s:0);this.layout.left=a[0]+(isDefined(r)?r:0),this.layout.top=a[1]+(isDefined(l)?l:0),roundLayout(this,this.config.pointScaleFactor,0,0)}}const p=createConfig(),x=4;function cacheWrite(e,t,i,s,n,a,r,l,o,u){e._cIn||(e._cIn=new Float64Array(8*x),e._cOut=new Float64Array(2*x)),u&&e._cGen!==D&&(e._cN=0,e._cWr=0);const h=e._cWr++%x;e._cN<x&&(e._cN=e._cWr);const c=8*h,f=e._cIn;f[c]=t,f[c+1]=i,f[c+2]=s,f[c+3]=n,f[c+4]=a,f[c+5]=r,f[c+6]=l?1:0,f[c+7]=o?1:0,e._cOut[2*h]=e.layout.width,e._cOut[2*h+1]=e.layout.height,e._cGen=D}function commitCacheOutputs(e,t){t?(e._lOutW=e.layout.width,e._lOutH=e.layout.height):(e._mOutW=e.layout.width,e._mOutH=e.layout.height)}let D=0,v=0,w=0,A=0,M=0;export function getYogaCounters(){return{visited:v,measured:w,cacheHits:A,live:M}}function layoutNode(t,i,s,n,a,r,l,d,y=!1,m=!1){v++;const _=t.style,p=t.layout,x=t._cGen===D&&!d;if(!t.isDirty_||x){if(!t.isDirty_&&t._hasL&&t._lWM===n&&t._lHM===a&&t._lFW===y&&t._lFH===m&&sameFloat(t._lW,i)&&sameFloat(t._lH,s)&&sameFloat(t._lOW,r)&&sameFloat(t._lOH,l))return A++,p.width=t._lOutW,void(p.height=t._lOutH);if(t._cN>0&&(x||!t.isDirty_)){const e=t._cIn;for(let o=0;o<t._cN;o++){const u=8*o;if(e[u+2]===n&&e[u+3]===a&&e[u+6]===(y?1:0)&&e[u+7]===(m?1:0)&&sameFloat(e[u],i)&&sameFloat(e[u+1],s)&&sameFloat(e[u+4],r)&&sameFloat(e[u+5],l))return p.width=t._cOut[2*o],p.height=t._cOut[2*o+1],void A++}}if(!t.isDirty_&&!d&&t._hasM&&t._mWM===n&&t._mHM===a&&sameFloat(t._mW,i)&&sameFloat(t._mH,s)&&sameFloat(t._mOW,r)&&sameFloat(t._mOH,l))return p.width=t._mOutW,p.height=t._mOutH,void A++}const M=t.isDirty_;d?(t._lW=i,t._lH=s,t._lWM=n,t._lHM=a,t._lOW=r,t._lOH=l,t._lFW=y,t._lFH=m,t._hasL=!0,t.isDirty_=!1,M&&(t._hasM=!1)):(t._mW=i,t._mH=s,t._mWM=n,t._mHM=a,t._mOW=r,t._mOH=l,t._hasM=!0,M&&(t._hasL=!1));const N=p.padding,b=p.border,E=p.margin;t._hasPadding?resolveEdges4Into(_.padding,r,N):N[0]=N[1]=N[2]=N[3]=0,t._hasBorder?resolveEdges4Into(_.border,r,b):b[0]=b[1]=b[2]=b[3]=0,t._hasMargin?resolveEdges4Into(_.margin,r,E):E[0]=E[1]=E[2]=E[3]=0;const F=N[0]+N[2]+b[0]+b[2],S=N[1]+N[3]+b[1]+b[3],k=y?NaN:resolveValue(_.width,r),W=m?NaN:resolveValue(_.height,l);let C=i,B=s,R=n,H=a;if(isDefined(k)&&(C=k,R=c.Exactly),isDefined(W)&&(B=W,H=c.Exactly),C=boundAxis(_,!0,C,r,l),B=boundAxis(_,!1,B,r,l),t.measureFunc&&0===t.children.length){const e=R===c.Undefined?NaN:Math.max(0,C-F),o=H===c.Undefined?NaN:Math.max(0,B-S);w++;const u=t.measureFunc(e,R,o,H);return t.layout.width=R===c.Exactly?C:boundAxis(_,!0,(u.width??0)+F,r,l),t.layout.height=H===c.Exactly?B:boundAxis(_,!1,(u.height??0)+S,r,l),commitCacheOutputs(t,d),void cacheWrite(t,i,s,n,a,r,l,y,m,M)}if(0===t.children.length)return t.layout.width=R===c.Exactly?C:boundAxis(_,!0,F,r,l),t.layout.height=H===c.Exactly?B:boundAxis(_,!1,S,r,l),commitCacheOutputs(t,d),void cacheWrite(t,i,s,n,a,r,l,y,m,M);const V=_.flexDirection,O=isRow(V)?o.Column:o.Row,P=isRow(V),I=P?C:B,G=P?B:C,z=P?R:H,L=P?H:R,U=P?F:S,T=P?S:F,j=isDefined(I)?Math.max(0,I-U):NaN,J=isDefined(G)?Math.max(0,G-T):NaN,Y=resolveGap(_,P?u.Column:u.Row,j),q=[],K=[];collectLayoutChildren(t,q,K);const Q=isDefined(C)?C:NaN,X=isDefined(B)?B:NaN,Z=_.flexWrap!==g.NoWrap,$=resolveGap(_,P?u.Row:u.Column,J);for(const e of q)e._flexBasis=computeFlexBasis(e,V,j,J,L,Q,X);const ee=[];if(Z&&isDefined(j)&&0!==q.length){let e=0,t=0;for(let i=0;i<q.length;i++){const s=q[i],n=boundAxis(s.style,P,s._flexBasis,Q,X),a=Math.max(0,n)+childMarginForAxis(s,V,Q),r=i>e?Y:0;i>e&&t+r+a>j?(ee.push(q.slice(e,i)),e=i,t=a):t+=r+a,s._lineIndex=ee.length}ee.push(q.slice(e))}else{for(const e of q)e._lineIndex=0;ee.push(q)}const te=ee.length,ie=function(t,i){if(!isRow(t.style.flexDirection))return!1;if(t.style.alignItems===e.Baseline)return!0;for(const t of i)if(t.style.alignSelf===e.Baseline)return!0;return!1}(t,q),se=new Array(te),ne=new Array(te),ae=ie?new Array(te).fill(0):[];let re=0,le=0;for(let i=0;i<te;i++){const s=ee[i],n=s.length>1?Y*(s.length-1):0;let a=n;for(const e of s)a+=e._flexBasis+childMarginForAxis(e,V,Q);let o=j;if(!isDefined(o)){const e=P?r:l,t=resolveValue(P?_.minWidth:_.minHeight,e),i=resolveValue(P?_.maxWidth:_.maxHeight,e);isDefined(i)&&a>i-U?o=Math.max(0,i-U):isDefined(t)&&a<t-U&&(o=Math.max(0,t-U))}resolveFlexibleLengths(s,o,a,P,Q,X);let u=0;for(const t of s){const i=t.style,s=i.alignSelf===e.Auto?_.alignItems:i.alignSelf,n=childMarginForAxis(t,O,Q);let a=NaN,r=c.Undefined;const l=resolveValue(P?i.height:i.width,P?X:Q),o=P?1:0,h=P?3:2,f=t._hasAutoMargin&&(isMarginAuto(i.margin,o)||isMarginAuto(i.margin,h));isDefined(l)?(a=l,r=c.Exactly):s!==e.Stretch||f||Z||!isDefined(J)||L!==c.Exactly?!Z&&isDefined(J)&&(a=Math.max(0,J-n),r=c.AtMost):(a=Math.max(0,J-n),r=c.Exactly),layoutNode(t,P?t._mainSize:a,P?a:t._mainSize,P?c.Exactly:r,P?r:c.Exactly,Q,X,d,P,!P),t._crossSize=P?t.layout.height:t.layout.width,u=Math.max(u,t._crossSize+n)}if(ie){let n=0,a=0;for(const i of s){if(resolveChildAlign(t,i)!==e.Baseline)continue;const s=resolveEdge(i.style.margin,1,Q),r=resolveEdge(i.style.margin,3,Q),l=calculateBaseline(i)+s,o=i.layout.height+s+r-l;l>n&&(n=l),o>a&&(a=o)}ae[i]=n,n+a>u&&(u=n+a)}const h=leadingEdge(V),f=trailingEdge(V);let y=n;for(const e of s){const t=e.layout.margin;y+=e._mainSize+t[h]+t[f]}se[i]=y,ne[i]=u,re=Math.max(re,y),le+=u}le+=te>1?$*(te-1):0;const oe=_.overflow===f.Scroll,ue=re+U,he=z===c.Exactly?I:z===c.AtMost&&oe?Math.max(Math.min(I,ue),U):Z&&te>1&&z===c.AtMost?I:ue,ce=le+T,fe=L===c.Exactly?G:L===c.AtMost&&oe?Math.max(Math.min(G,ce),T):ce;if(t.layout.width=boundAxis(_,!0,P?he:fe,r,l),t.layout.height=boundAxis(_,!1,P?fe:he,r,l),commitCacheOutputs(t,d),cacheWrite(t,i,s,n,a,r,l,y,m,M),!d)return;const de=(P?t.layout.width:t.layout.height)-U,ye=(P?t.layout.height:t.layout.width)-T,ge=leadingEdge(V),me=trailingEdge(V),_e=P?1:0,pe=P?3:2,xe=isReverse(V),De=P?t.layout.width:t.layout.height;let ve=N[_e]+b[_e],we=$;const Ae=ye-le;if(1!==te||Z||ie){const t=Math.max(0,Ae);switch(_.alignContent){case e.FlexStart:break;case e.Center:ve+=Ae/2;break;case e.FlexEnd:ve+=Ae;break;case e.Stretch:if(te>0&&t>0){const e=t/te;for(let t=0;t<te;t++)ne[t]+=e}break;case e.SpaceBetween:te>1&&(we+=t/(te-1));break;case e.SpaceAround:te>0&&(we+=t/te,ve+=t/te/2);break;case e.SpaceEvenly:te>0&&(we+=t/(te+1),ve+=t/(te+1))}}else ne[0]=ye;const Me=_.flexWrap===g.WrapReverse,Ne=P?t.layout.height:t.layout.width;let be=ve;for(let t=0;t<te;t++){const i=ee[t],s=ne[t],n=se[t],a=i.length;if(Z||L!==c.Exactly)for(const t of i){const i=t.style,n=i.alignSelf===e.Auto?_.alignItems:i.alignSelf,a=isDefined(resolveValue(P?i.height:i.width,P?X:Q)),r=t._hasAutoMargin&&(isMarginAuto(i.margin,_e)||isMarginAuto(i.margin,pe));if(n===e.Stretch&&!a&&!r){const e=childMarginForAxis(t,O,Q),i=Math.max(0,s-e);t._crossSize!==i&&(layoutNode(t,P?t._mainSize:i,P?i:t._mainSize,c.Exactly,c.Exactly,Q,X,d,P,!P),t._crossSize=i)}}let r=N[ge]+b[ge],l=Y,o=0;for(const e of i)e._hasAutoMargin&&(isMarginAuto(e.style.margin,ge)&&o++,isMarginAuto(e.style.margin,me)&&o++);const u=de-n,f=Math.max(0,u),y=o>0&&f>0?f/o:0;if(0===o)switch(_.justifyContent){case h.FlexStart:break;case h.Center:r+=u/2;break;case h.FlexEnd:r+=u;break;case h.SpaceBetween:a>1&&(l+=f/(a-1));break;case h.SpaceAround:a>0&&(l+=f/a,r+=f/a/2);break;case h.SpaceEvenly:a>0&&(l+=f/(a+1),r+=f/(a+1))}const g=Me?Ne-be-s:be;let m=r;for(const n of i){const i=n.style.margin,a=n.layout.margin;let r,o,u,h,c=!1,f=!1,d=!1,p=!1;n._hasAutoMargin?(c=isMarginAuto(i,ge),f=isMarginAuto(i,me),d=isMarginAuto(i,_e),p=isMarginAuto(i,pe),r=c?y:a[ge],o=f?y:a[me],u=d?0:a[_e],h=p?0:a[pe]):(r=a[ge],o=a[me],u=a[_e],h=a[pe]);const x=xe?De-(m+r)-n._mainSize:m+r,D=n.style.alignSelf===e.Auto?_.alignItems:n.style.alignSelf;let v=g+u;const w=s-n._crossSize-u-h;if(d&&p)v+=Math.max(0,w)/2;else if(d)v+=Math.max(0,w);else if(p);else switch(D){case e.FlexStart:case e.Stretch:Me&&(v+=w);break;case e.Center:v+=w/2;break;case e.FlexEnd:Me||(v+=w);break;case e.Baseline:ie&&(v=g+ae[t]-calculateBaseline(n))}let A=0,M=0;if(n._hasPosition){const e=resolveValue(resolveEdgeRaw(n.style.position,0),Q),t=resolveValue(resolveEdgeRaw(n.style.position,2),Q),i=resolveValue(resolveEdgeRaw(n.style.position,1),Q),s=resolveValue(resolveEdgeRaw(n.style.position,3),Q);A=isDefined(e)?e:isDefined(t)?-t:0,M=isDefined(i)?i:isDefined(s)?-s:0}P?(n.layout.left=x+A,n.layout.top=v+M):(n.layout.left=v+A,n.layout.top=x+M),m+=n._mainSize+r+o+l}be+=s+we}for(const e of K)layoutAbsoluteChild(t,e,t.layout.width,t.layout.height,N,b)}function layoutAbsoluteChild(t,i,s,n,a,r){const l=i.style,o=resolveEdgeRaw(l.position,0),u=resolveEdgeRaw(l.position,2),h=resolveEdgeRaw(l.position,1),f=resolveEdgeRaw(l.position,3),d=resolveValue(o,s),y=resolveValue(u,s),m=resolveValue(h,n),_=resolveValue(f,n),p=s-r[0]-r[2],x=n-r[1]-r[3];let D=resolveValue(l.width,p),v=resolveValue(l.height,x);!isDefined(D)&&isDefined(d)&&isDefined(y)&&(D=p-d-y),!isDefined(v)&&isDefined(m)&&isDefined(_)&&(v=x-m-_),layoutNode(i,D,v,isDefined(D)?c.Exactly:c.Undefined,isDefined(v)?c.Exactly:c.Undefined,p,x,!0);const w=resolveEdge(l.margin,0,s),A=resolveEdge(l.margin,1,s),M=resolveEdge(l.margin,2,s),N=resolveEdge(l.margin,3,s),b=t.style.flexDirection,E=isReverse(b),F=isRow(b),S=t.style.flexWrap===g.WrapReverse,k=l.alignSelf===e.Auto?t.style.alignItems:l.alignSelf;let W,C;if(isDefined(d))W=r[0]+d+w;else if(isDefined(y))W=s-r[2]-y-i.layout.width-M;else if(F){const e=a[0]+r[0],n=s-a[2]-r[2];W=E?n-i.layout.width-M:justifyAbsolute(t.style.justifyContent,e,n,i.layout.width)+w}else W=alignAbsolute(k,a[0]+r[0],s-a[2]-r[2],i.layout.width,S)+w;if(isDefined(m))C=r[1]+m+A;else if(isDefined(_))C=n-r[3]-_-i.layout.height-N;else if(F)C=alignAbsolute(k,a[1]+r[1],n-a[3]-r[3],i.layout.height,S)+A;else{const e=a[1]+r[1],s=n-a[3]-r[3];C=E?s-i.layout.height-N:justifyAbsolute(t.style.justifyContent,e,s,i.layout.height)+A}i.layout.left=W,i.layout.top=C}function justifyAbsolute(e,t,i,s){switch(e){case h.Center:return t+(i-t-s)/2;case h.FlexEnd:return i-s;default:return t}}function alignAbsolute(t,i,s,n,a){switch(t){case e.Center:return i+(s-i-n)/2;case e.FlexEnd:return a?i:s-n;default:return a?s-n:i}}function computeFlexBasis(t,i,s,n,a,r,l){if((t._fbGen===D||!t.isDirty_)&&t._fbCrossMode===a&&sameFloat(t._fbOwnerW,r)&&sameFloat(t._fbOwnerH,l)&&sameFloat(t._fbAvailMain,s)&&sameFloat(t._fbAvailCross,n))return t._fbBasis;const o=t.style,u=isRow(i),h=resolveValue(o.flexBasis,s);if(isDefined(h)){const e=Math.max(0,h);return t._fbBasis=e,t._fbOwnerW=r,t._fbOwnerH=l,t._fbAvailMain=s,t._fbAvailCross=n,t._fbCrossMode=a,t._fbGen=D,e}const f=resolveValue(u?o.width:o.height,u?r:l);if(isDefined(f)){const e=Math.max(0,f);return t._fbBasis=e,t._fbOwnerW=r,t._fbOwnerH=l,t._fbAvailMain=s,t._fbAvailCross=n,t._fbCrossMode=a,t._fbGen=D,e}let d=resolveValue(u?o.height:o.width,u?l:r),y=isDefined(d)?c.Exactly:c.Undefined;!isDefined(d)&&isDefined(n)&&(d=n,y=a===c.Exactly&&function(t){const i=t.parent;if(!i)return!1;return(t.style.alignSelf===e.Auto?i.style.alignItems:t.style.alignSelf)===e.Stretch}(t)?c.Exactly:c.AtMost);let g=NaN,m=c.Undefined;u&&isDefined(s)&&hasMeasureFuncInSubtree(t)&&(g=s,m=c.AtMost),layoutNode(t,u?g:d,u?d:g,u?m:y,u?y:m,r,l,!1);const _=u?t.layout.width:t.layout.height;return t._fbBasis=_,t._fbOwnerW=r,t._fbOwnerH=l,t._fbAvailMain=s,t._fbAvailCross=n,t._fbCrossMode=a,t._fbGen=D,_}function hasMeasureFuncInSubtree(e){if(e.measureFunc)return!0;for(const t of e.children)if(hasMeasureFuncInSubtree(t))return!0;return!1}function resolveFlexibleLengths(e,t,i,s,n,a){const r=e.length,l=new Array(r).fill(!1),o=isDefined(t)?t-i:0;for(let i=0;i<r;i++){const r=e[i],u=boundAxis(r.style,s,r._flexBasis,n,a);isDefined(t)&&(o>=0?0!==r.style.flexGrow:0!==r.style.flexShrink)?r._mainSize=r._flexBasis:(r._mainSize=Math.max(0,u),l[i]=!0)}const u=new Array(r);for(let t=0;t<=r;t++){let t=0,i=0,h=0,c=0;for(let s=0;s<r;s++){const n=e[s];l[s]?t+=n._mainSize-n._flexBasis:(i+=n.style.flexGrow,h+=n.style.flexShrink*n._flexBasis,c++)}if(0===c)break;let f=o-t;if(f>0&&i>0&&i<1){const e=o*i;e<f&&(f=e)}else if(f<0&&h>0){let t=0;for(let i=0;i<r;i++)l[i]||(t+=e[i].style.flexShrink);if(t<1){const e=o*t;e>f&&(f=e)}}let d=0;for(let t=0;t<r;t++){if(l[t])continue;const r=e[t];let o=r._flexBasis;f>0&&i>0?o+=f*r.style.flexGrow/i:f<0&&h>0&&(o+=f*(r.style.flexShrink*r._flexBasis)/h),u[t]=o;const c=Math.max(0,boundAxis(r.style,s,o,n,a));r._mainSize=c,d+=c-o}if(0===d)break;let y=!1;for(let t=0;t<r;t++){if(l[t])continue;const i=e[t]._mainSize-u[t];(d>0&&i>0||d<0&&i<0)&&(l[t]=!0,y=!0)}if(!y)break}}function resolveChildAlign(t,i){return i.style.alignSelf===e.Auto?t.style.alignItems:i.style.alignSelf}function calculateBaseline(t){let i=null;for(const s of t.children){if(s._lineIndex>0)break;if(s.style.positionType!==d.Absolute&&s.style.display!==n.None){if(resolveChildAlign(t,s)===e.Baseline||s.isReferenceBaseline_){i=s;break}null===i&&(i=s)}}return null===i?t.layout.height:calculateBaseline(i)+i.layout.top}function childMarginForAxis(e,t,i){return e._hasMargin?resolveEdge(e.style.margin,leadingEdge(t),i)+resolveEdge(e.style.margin,trailingEdge(t),i):0}function resolveGap(e,t,i){let s=e.gap[t];s.unit===y.Undefined&&(s=e.gap[u.All]);const n=resolveValue(s,i);return isDefined(n)?Math.max(0,n):0}function boundAxis(e,t,i,s,n){const a=t?e.minWidth:e.minHeight,r=t?e.maxWidth:e.maxHeight,l=a.unit,o=r.unit;if(0===l&&0===o)return i;const u=t?s:n;let h=i;if(1===o)h>r.value&&(h=r.value);else if(2===o){const e=r.value*u/100;e==e&&h>e&&(h=e)}if(1===l)h<a.value&&(h=a.value);else if(2===l){const e=a.value*u/100;e==e&&h<e&&(h=e)}return h}function zeroLayoutRecursive(e){for(const t of e.children)t.layout.left=0,t.layout.top=0,t.layout.width=0,t.layout.height=0,t.isDirty_=!0,t._hasL=!1,t._hasM=!1,zeroLayoutRecursive(t)}function collectLayoutChildren(e,t,i){for(const s of e.children){const e=s.style.display;e===n.None?(s.layout.left=0,s.layout.top=0,s.layout.width=0,s.layout.height=0,zeroLayoutRecursive(s)):e===n.Contents?(s.layout.left=0,s.layout.top=0,s.layout.width=0,s.layout.height=0,collectLayoutChildren(s,t,i)):s.style.positionType===d.Absolute?i.push(s):t.push(s)}}function roundLayout(e,t,i,s){if(0===t)return;const n=e.layout,a=n.left,r=n.top,l=n.width,o=n.height,u=i+a,h=s+r,c=null!==e.measureFunc;n.left=roundValue(a,t,!1,c),n.top=roundValue(r,t,!1,c);const f=u+l,d=h+o,y=!isWholeNumber(l*t),g=!isWholeNumber(o*t);n.width=roundValue(f,t,c&&y,c&&!y)-roundValue(u,t,!1,c),n.height=roundValue(d,t,c&&g,c&&!g)-roundValue(h,t,!1,c);for(const i of e.children)roundLayout(i,t,u,h)}function isWholeNumber(e){const t=e-Math.floor(e);return t<1e-4||t>.9999}function roundValue(e,t,i,s){let n=e*t,a=n-Math.floor(n);return a<0&&(a+=1),n=a<1e-4?Math.floor(n):a>.9999||i?Math.ceil(n):s?Math.floor(n):Math.floor(n)+(a>=.4999?1:0),n/t}function parseDimension(e){if(void 0===e)return m;if("auto"===e)return _;if("number"==typeof e)return Number.isFinite(e)?pointValue(e):m;if("string"==typeof e&&e.endsWith("%"))return percentValue(parseFloat(e));const t=parseFloat(e);return isNaN(t)?m:pointValue(t)}function physicalEdge(e){switch(e){case a.Left:case a.Start:return 0;case a.Top:return 1;case a.Right:case a.End:return 2;case a.Bottom:return 3;default:return 0}}const N={Config:{create:createConfig,destroy(){}},Node:{create:e=>new Node(e),createDefault:()=>new Node,createWithConfig:e=>new Node(e),destroy(){}}};export function loadYoga(){return Promise.resolve(N)}export default N;
1
+ import{Align as e,BoxSizing as t,Dimension as i,Direction as s,Display as n,Edge as a,Errata as l,ExperimentalFeature as r,FlexDirection as o,Gutter as u,Justify as h,MeasureMode as c,Overflow as f,PositionType as d,Unit as y,Wrap as g}from"./enums.js";export{e as Align,t as BoxSizing,i as Dimension,s as Direction,n as Display,a as Edge,l as Errata,r as ExperimentalFeature,o as FlexDirection,u as Gutter,h as Justify,c as MeasureMode,f as Overflow,d as PositionType,y as Unit,g as Wrap};const m={unit:y.Undefined,value:NaN},_={unit:y.Auto,value:NaN};function pointValue(e){return{unit:y.Point,value:e}}function percentValue(e){return{unit:y.Percent,value:e}}function resolveValue(e,t){switch(e.unit){case y.Point:return e.value;case y.Percent:return isNaN(t)?NaN:e.value*t/100;default:return NaN}}function isDefined(e){return!isNaN(e)}function sameFloat(e,t){return e===t||e!=e&&t!=t}function defaultStyle(){return{direction:s.Inherit,flexDirection:o.Column,justifyContent:h.FlexStart,alignItems:e.Stretch,alignSelf:e.Auto,alignContent:e.FlexStart,flexWrap:g.NoWrap,overflow:f.Visible,display:n.Flex,positionType:d.Relative,flexGrow:0,flexShrink:0,flexBasis:_,margin:new Array(9).fill(m),padding:new Array(9).fill(m),border:new Array(9).fill(m),position:new Array(9).fill(m),gap:new Array(3).fill(m),width:_,height:_,minWidth:m,minHeight:m,maxWidth:m,maxHeight:m}}function resolveEdge(e,t,i,s=!1){let n=e[t];return n.unit===y.Undefined&&(n=0===t||2===t?e[a.Horizontal]:e[a.Vertical]),n.unit===y.Undefined&&(n=e[a.All]),n.unit===y.Undefined&&(0===t&&(n=e[a.Start]),2===t&&(n=e[a.End])),n.unit===y.Undefined?0:n.unit===y.Auto?s?NaN:0:resolveValue(n,i)}function resolveEdgeRaw(e,t){let i=e[t];return i.unit===y.Undefined&&(i=0===t||2===t?e[a.Horizontal]:e[a.Vertical]),i.unit===y.Undefined&&(i=e[a.All]),i.unit===y.Undefined&&(0===t&&(i=e[a.Start]),2===t&&(i=e[a.End])),i}function isMarginAuto(e,t){return resolveEdgeRaw(e,t).unit===y.Auto}function hasAnyAutoEdge(e){for(let t=0;t<9;t++)if(3===e[t].unit)return!0;return!1}function hasAnyDefinedEdge(e){for(let t=0;t<9;t++)if(0!==e[t].unit)return!0;return!1}function resolveEdges4Into(e,t,i){const s=e[6],n=e[7],a=e[8],l=e[4],r=e[5],o=isNaN(t)?NaN:t/100;let u=e[0];0===u.unit&&(u=s),0===u.unit&&(u=a),0===u.unit&&(u=l),i[0]=1===u.unit?u.value:2===u.unit?u.value*o:0,u=e[1],0===u.unit&&(u=n),0===u.unit&&(u=a),i[1]=1===u.unit?u.value:2===u.unit?u.value*o:0,u=e[2],0===u.unit&&(u=s),0===u.unit&&(u=a),0===u.unit&&(u=r),i[2]=1===u.unit?u.value:2===u.unit?u.value*o:0,u=e[3],0===u.unit&&(u=n),0===u.unit&&(u=a),i[3]=1===u.unit?u.value:2===u.unit?u.value*o:0}function isRow(e){return e===o.Row||e===o.RowReverse}function isReverse(e){return e===o.RowReverse||e===o.ColumnReverse}function leadingEdge(e){switch(e){case o.Row:return 0;case o.RowReverse:return 2;case o.Column:return 1;case o.ColumnReverse:return 3}}function trailingEdge(e){switch(e){case o.Row:return 2;case o.RowReverse:return 0;case o.Column:return 3;case o.ColumnReverse:return 1}}function createConfig(){const e={pointScaleFactor:1,errata:l.None,useWebDefaults:!1,free(){},isExperimentalFeatureEnabled:()=>!1,setExperimentalFeatureEnabled(){},setPointScaleFactor(t){e.pointScaleFactor=t},getErrata:()=>e.errata,setErrata(t){e.errata=t},setUseWebDefaults(t){e.useWebDefaults=t}};return e}export class Node{style;layout;parent;children;measureFunc;config;isDirty_;isReferenceBaseline_;_flexBasis=0;_mainSize=0;_crossSize=0;_lineIndex=0;_hasAutoMargin=!1;_hasPosition=!1;_hasPadding=!1;_hasBorder=!1;_hasMargin=!1;_lW=NaN;_lH=NaN;_lWM=0;_lHM=0;_lOW=NaN;_lOH=NaN;_lFW=!1;_lFH=!1;_lOutW=NaN;_lOutH=NaN;_hasL=!1;_mW=NaN;_mH=NaN;_mWM=0;_mHM=0;_mOW=NaN;_mOH=NaN;_mOutW=NaN;_mOutH=NaN;_hasM=!1;_fbBasis=NaN;_fbOwnerW=NaN;_fbOwnerH=NaN;_fbAvailMain=NaN;_fbAvailCross=NaN;_fbCrossMode=0;_fbGen=-1;_cIn=null;_cOut=null;_cGen=-1;_cN=0;_cWr=0;constructor(e){this.style=defaultStyle(),this.layout={left:0,top:0,width:0,height:0,border:[0,0,0,0],padding:[0,0,0,0],margin:[0,0,0,0]},this.parent=null,this.children=[],this.measureFunc=null,this.config=e??p,this.isDirty_=!0,this.isReferenceBaseline_=!1,M++}insertChild(e,t){e.parent=this,this.children.splice(t,0,e),this.markDirty()}removeChild(e){const t=this.children.indexOf(e);t>=0&&(this.children.splice(t,1),e.parent=null,this.markDirty())}getChild(e){return this.children[e]}getChildCount(){return this.children.length}getParent(){return this.parent}free(){this.parent=null,this.children=[],this.measureFunc=null,this._cIn=null,this._cOut=null,M--}freeRecursive(){for(const e of this.children)e.freeRecursive();this.free()}reset(){this.style=defaultStyle(),this.children=[],this.parent=null,this.measureFunc=null,this.isDirty_=!0,this._hasAutoMargin=!1,this._hasPosition=!1,this._hasPadding=!1,this._hasBorder=!1,this._hasMargin=!1,this._hasL=!1,this._hasM=!1,this._cN=0,this._cWr=0,this._fbBasis=NaN}markDirty(){this.isDirty_=!0,this.parent&&!this.parent.isDirty_&&this.parent.markDirty()}isDirty(){return this.isDirty_}hasNewLayout(){return!0}markLayoutSeen(){}setMeasureFunc(e){this.measureFunc=e,this.markDirty()}unsetMeasureFunc(){this.measureFunc=null,this.markDirty()}getComputedLeft(){return this.layout.left}getComputedTop(){return this.layout.top}getComputedWidth(){return this.layout.width}getComputedHeight(){return this.layout.height}getComputedRight(){const e=this.parent;return e?e.layout.width-this.layout.left-this.layout.width:0}getComputedBottom(){const e=this.parent;return e?e.layout.height-this.layout.top-this.layout.height:0}getComputedLayout(){return{left:this.layout.left,top:this.layout.top,right:this.getComputedRight(),bottom:this.getComputedBottom(),width:this.layout.width,height:this.layout.height}}getComputedBorder(e){return this.layout.border[physicalEdge(e)]}getComputedPadding(e){return this.layout.padding[physicalEdge(e)]}getComputedMargin(e){return this.layout.margin[physicalEdge(e)]}setWidth(e){this.style.width=parseDimension(e),this.markDirty()}setWidthPercent(e){this.style.width=percentValue(e),this.markDirty()}setWidthAuto(){this.style.width=_,this.markDirty()}setHeight(e){this.style.height=parseDimension(e),this.markDirty()}setHeightPercent(e){this.style.height=percentValue(e),this.markDirty()}setHeightAuto(){this.style.height=_,this.markDirty()}setMinWidth(e){this.style.minWidth=parseDimension(e),this.markDirty()}setMinWidthPercent(e){this.style.minWidth=percentValue(e),this.markDirty()}setMinHeight(e){this.style.minHeight=parseDimension(e),this.markDirty()}setMinHeightPercent(e){this.style.minHeight=percentValue(e),this.markDirty()}setMaxWidth(e){this.style.maxWidth=parseDimension(e),this.markDirty()}setMaxWidthPercent(e){this.style.maxWidth=percentValue(e),this.markDirty()}setMaxHeight(e){this.style.maxHeight=parseDimension(e),this.markDirty()}setMaxHeightPercent(e){this.style.maxHeight=percentValue(e),this.markDirty()}setFlexDirection(e){this.style.flexDirection=e,this.markDirty()}setFlexGrow(e){this.style.flexGrow=e??0,this.markDirty()}setFlexShrink(e){this.style.flexShrink=e??0,this.markDirty()}setFlex(e){void 0===e||isNaN(e)?(this.style.flexGrow=0,this.style.flexShrink=0):e>0?(this.style.flexGrow=e,this.style.flexShrink=1,this.style.flexBasis=pointValue(0)):e<0?(this.style.flexGrow=0,this.style.flexShrink=-e):(this.style.flexGrow=0,this.style.flexShrink=0),this.markDirty()}setFlexBasis(e){this.style.flexBasis=parseDimension(e),this.markDirty()}setFlexBasisPercent(e){this.style.flexBasis=percentValue(e),this.markDirty()}setFlexBasisAuto(){this.style.flexBasis=_,this.markDirty()}setFlexWrap(e){this.style.flexWrap=e,this.markDirty()}setAlignItems(e){this.style.alignItems=e,this.markDirty()}setAlignSelf(e){this.style.alignSelf=e,this.markDirty()}setAlignContent(e){this.style.alignContent=e,this.markDirty()}setJustifyContent(e){this.style.justifyContent=e,this.markDirty()}setDisplay(e){this.style.display=e,this.markDirty()}getDisplay(){return this.style.display}setPositionType(e){this.style.positionType=e,this.markDirty()}setPosition(e,t){this.style.position[e]=parseDimension(t),this._hasPosition=hasAnyDefinedEdge(this.style.position),this.markDirty()}setPositionPercent(e,t){this.style.position[e]=percentValue(t),this._hasPosition=!0,this.markDirty()}setPositionAuto(e){this.style.position[e]=_,this._hasPosition=!0,this.markDirty()}setOverflow(e){this.style.overflow=e,this.markDirty()}setDirection(e){this.style.direction=e,this.markDirty()}setBoxSizing(e){}setMargin(e,t){const i=parseDimension(t);this.style.margin[e]=i,i.unit===y.Auto?this._hasAutoMargin=!0:this._hasAutoMargin=hasAnyAutoEdge(this.style.margin),this._hasMargin=this._hasAutoMargin||hasAnyDefinedEdge(this.style.margin),this.markDirty()}setMarginPercent(e,t){this.style.margin[e]=percentValue(t),this._hasAutoMargin=hasAnyAutoEdge(this.style.margin),this._hasMargin=!0,this.markDirty()}setMarginAuto(e){this.style.margin[e]=_,this._hasAutoMargin=!0,this._hasMargin=!0,this.markDirty()}setPadding(e,t){this.style.padding[e]=parseDimension(t),this._hasPadding=hasAnyDefinedEdge(this.style.padding),this.markDirty()}setPaddingPercent(e,t){this.style.padding[e]=percentValue(t),this._hasPadding=!0,this.markDirty()}setBorder(e,t){this.style.border[e]=void 0===t?m:pointValue(t),this._hasBorder=hasAnyDefinedEdge(this.style.border),this.markDirty()}setGap(e,t){this.style.gap[e]=parseDimension(t),this.markDirty()}setGapPercent(e,t){this.style.gap[e]=percentValue(t),this.markDirty()}getFlexDirection(){return this.style.flexDirection}getJustifyContent(){return this.style.justifyContent}getAlignItems(){return this.style.alignItems}getAlignSelf(){return this.style.alignSelf}getAlignContent(){return this.style.alignContent}getFlexGrow(){return this.style.flexGrow}getFlexShrink(){return this.style.flexShrink}getFlexBasis(){return this.style.flexBasis}getFlexWrap(){return this.style.flexWrap}getWidth(){return this.style.width}getHeight(){return this.style.height}getOverflow(){return this.style.overflow}getPositionType(){return this.style.positionType}getDirection(){return this.style.direction}copyStyle(e){}setDirtiedFunc(e){}unsetDirtiedFunc(){}setIsReferenceBaseline(e){this.isReferenceBaseline_=e,this.markDirty()}isReferenceBaseline(){return this.isReferenceBaseline_}setAspectRatio(e){}getAspectRatio(){return NaN}setAlwaysFormsContainingBlock(e){}calculateLayout(e,t,i){v=0,w=0,A=0,D++;const s=void 0===e?NaN:e,n=void 0===t?NaN:t;layoutNode(this,s,n,isDefined(s)?c.Exactly:c.Undefined,isDefined(n)?c.Exactly:c.Undefined,s,n,!0);const a=this.layout.margin,l=resolveValue(resolveEdgeRaw(this.style.position,0),isDefined(s)?s:0),r=resolveValue(resolveEdgeRaw(this.style.position,1),isDefined(s)?s:0);this.layout.left=a[0]+(isDefined(l)?l:0),this.layout.top=a[1]+(isDefined(r)?r:0),roundLayout(this,this.config.pointScaleFactor,0,0)}}const p=createConfig(),x=4;function cacheWrite(e,t,i,s,n,a,l,r,o,u){e._cIn||(e._cIn=new Float64Array(8*x),e._cOut=new Float64Array(2*x)),u&&e._cGen!==D&&(e._cN=0,e._cWr=0);const h=e._cWr++%x;e._cN<x&&(e._cN=e._cWr);const c=8*h,f=e._cIn;f[c]=t,f[c+1]=i,f[c+2]=s,f[c+3]=n,f[c+4]=a,f[c+5]=l,f[c+6]=r?1:0,f[c+7]=o?1:0,e._cOut[2*h]=e.layout.width,e._cOut[2*h+1]=e.layout.height,e._cGen=D}function commitCacheOutputs(e,t){t?(e._lOutW=e.layout.width,e._lOutH=e.layout.height):(e._mOutW=e.layout.width,e._mOutH=e.layout.height)}let D=0,v=0,w=0,A=0,M=0;export function getYogaCounters(){return{visited:v,measured:w,cacheHits:A,live:M}}function layoutNode(t,i,s,n,a,l,r,d,y=!1,m=!1){v++;const _=t.style,p=t.layout,x=t._cGen===D&&!d;if(!t.isDirty_||x){if(!t.isDirty_&&t._hasL&&t._lWM===n&&t._lHM===a&&t._lFW===y&&t._lFH===m&&sameFloat(t._lW,i)&&sameFloat(t._lH,s)&&sameFloat(t._lOW,l)&&sameFloat(t._lOH,r))return A++,p.width=t._lOutW,void(p.height=t._lOutH);if(t._cN>0&&(x||!t.isDirty_)){const e=t._cIn;for(let o=0;o<t._cN;o++){const u=8*o;if(e[u+2]===n&&e[u+3]===a&&e[u+6]===(y?1:0)&&e[u+7]===(m?1:0)&&sameFloat(e[u],i)&&sameFloat(e[u+1],s)&&sameFloat(e[u+4],l)&&sameFloat(e[u+5],r))return p.width=t._cOut[2*o],p.height=t._cOut[2*o+1],void A++}}if(!t.isDirty_&&!d&&t._hasM&&t._mWM===n&&t._mHM===a&&sameFloat(t._mW,i)&&sameFloat(t._mH,s)&&sameFloat(t._mOW,l)&&sameFloat(t._mOH,r))return p.width=t._mOutW,p.height=t._mOutH,void A++}const M=t.isDirty_;d?(t._lW=i,t._lH=s,t._lWM=n,t._lHM=a,t._lOW=l,t._lOH=r,t._lFW=y,t._lFH=m,t._hasL=!0,t.isDirty_=!1,M&&(t._hasM=!1)):(t._mW=i,t._mH=s,t._mWM=n,t._mHM=a,t._mOW=l,t._mOH=r,t._hasM=!0,M&&(t._hasL=!1));const N=p.padding,b=p.border,F=p.margin;t._hasPadding?resolveEdges4Into(_.padding,l,N):N[0]=N[1]=N[2]=N[3]=0,t._hasBorder?resolveEdges4Into(_.border,l,b):b[0]=b[1]=b[2]=b[3]=0,t._hasMargin?resolveEdges4Into(_.margin,l,F):F[0]=F[1]=F[2]=F[3]=0;const E=N[0]+N[2]+b[0]+b[2],S=N[1]+N[3]+b[1]+b[3],k=y?NaN:resolveValue(_.width,l),W=m?NaN:resolveValue(_.height,r);let C=i,B=s,R=n,H=a;if(isDefined(k)&&(C=k,R=c.Exactly),isDefined(W)&&(B=W,H=c.Exactly),C=boundAxis(_,!0,C,l,r),B=boundAxis(_,!1,B,l,r),t.measureFunc&&0===t.children.length){const e=R===c.Undefined?NaN:Math.max(0,C-E),o=H===c.Undefined?NaN:Math.max(0,B-S);w++;const u=t.measureFunc(e,R,o,H);return t.layout.width=R===c.Exactly?C:boundAxis(_,!0,(u.width??0)+E,l,r),t.layout.height=H===c.Exactly?B:boundAxis(_,!1,(u.height??0)+S,l,r),commitCacheOutputs(t,d),void cacheWrite(t,i,s,n,a,l,r,y,m,M)}if(0===t.children.length)return t.layout.width=R===c.Exactly?C:boundAxis(_,!0,E,l,r),t.layout.height=H===c.Exactly?B:boundAxis(_,!1,S,l,r),commitCacheOutputs(t,d),void cacheWrite(t,i,s,n,a,l,r,y,m,M);const V=_.flexDirection,O=isRow(V)?o.Column:o.Row;const P=isRow(V),I=P?C:B,G=P?B:C,z=P?R:H,L=P?H:R,U=P?E:S,j=P?S:E,T=isDefined(I)?Math.max(0,I-U):NaN,J=isDefined(G)?Math.max(0,G-j):NaN,Y=resolveGap(_,P?u.Column:u.Row,T),q=[],K=[];collectLayoutChildren(t,q,K);const Q=isDefined(C)?C:NaN,X=isDefined(B)?B:NaN,Z=_.flexWrap!==g.NoWrap,$=resolveGap(_,P?u.Row:u.Column,J);for(const e of q)e._flexBasis=computeFlexBasis(e,V,T,J,L,Q,X);const ee=[];if(Z&&isDefined(T)&&0!==q.length){let e=0,t=0;for(let i=0;i<q.length;i++){const s=q[i],n=boundAxis(s.style,P,s._flexBasis,Q,X),a=Math.max(0,n)+childMarginForAxis(s,V,Q),l=i>e?Y:0;i>e&&t+l+a>T?(ee.push(q.slice(e,i)),e=i,t=a):t+=l+a,s._lineIndex=ee.length}ee.push(q.slice(e))}else{for(const e of q)e._lineIndex=0;ee.push(q)}const te=ee.length,ie=function(t,i){if(!isRow(t.style.flexDirection))return!1;if(t.style.alignItems===e.Baseline)return!0;for(const t of i)if(t.style.alignSelf===e.Baseline)return!0;return!1}(t,q),se=new Array(te),ne=new Array(te),ae=ie?new Array(te).fill(0):[];let le=0,re=0;for(let i=0;i<te;i++){const s=ee[i],n=s.length>1?Y*(s.length-1):0;let a=n;for(const e of s)a+=e._flexBasis+childMarginForAxis(e,V,Q);let o=T;if(!isDefined(o)){const e=P?l:r,t=resolveValue(P?_.minWidth:_.minHeight,e),i=resolveValue(P?_.maxWidth:_.maxHeight,e);isDefined(i)&&a>i-U?o=Math.max(0,i-U):isDefined(t)&&a<t-U&&(o=Math.max(0,t-U))}resolveFlexibleLengths(s,o,a,P,Q,X);let u=0;for(const t of s){const i=t.style,s=i.alignSelf===e.Auto?_.alignItems:i.alignSelf,n=childMarginForAxis(t,O,Q);let a=NaN,l=c.Undefined;const r=resolveValue(P?i.height:i.width,P?X:Q),o=P?1:0,h=P?3:2,f=t._hasAutoMargin&&(isMarginAuto(i.margin,o)||isMarginAuto(i.margin,h));isDefined(r)?(a=r,l=c.Exactly):s!==e.Stretch||f||Z||!isDefined(J)||L!==c.Exactly?!Z&&isDefined(J)&&(a=Math.max(0,J-n),l=c.AtMost):(a=Math.max(0,J-n),l=c.Exactly);layoutNode(t,P?t._mainSize:a,P?a:t._mainSize,P?c.Exactly:l,P?l:c.Exactly,Q,X,d,P,!P),t._crossSize=P?t.layout.height:t.layout.width,u=Math.max(u,t._crossSize+n)}if(ie){let n=0,a=0;for(const i of s){if(resolveChildAlign(t,i)!==e.Baseline)continue;const s=resolveEdge(i.style.margin,1,Q),l=resolveEdge(i.style.margin,3,Q),r=calculateBaseline(i)+s,o=i.layout.height+s+l-r;r>n&&(n=r),o>a&&(a=o)}ae[i]=n,n+a>u&&(u=n+a)}const h=leadingEdge(V),f=trailingEdge(V);let y=n;for(const e of s){const t=e.layout.margin;y+=e._mainSize+t[h]+t[f]}se[i]=y,ne[i]=u,le=Math.max(le,y),re+=u}re+=te>1?$*(te-1):0;const oe=_.overflow===f.Scroll,ue=le+U,he=z===c.Exactly?I:z===c.AtMost&&oe?Math.max(Math.min(I,ue),U):Z&&te>1&&z===c.AtMost?I:ue,ce=re+j,fe=L===c.Exactly?G:L===c.AtMost&&oe?Math.max(Math.min(G,ce),j):ce;if(t.layout.width=boundAxis(_,!0,P?he:fe,l,r),t.layout.height=boundAxis(_,!1,P?fe:he,l,r),commitCacheOutputs(t,d),cacheWrite(t,i,s,n,a,l,r,y,m,M),!d)return;const de=(P?t.layout.width:t.layout.height)-U,ye=(P?t.layout.height:t.layout.width)-j,ge=leadingEdge(V),me=trailingEdge(V),_e=P?1:0,pe=P?3:2,xe=isReverse(V),De=P?t.layout.width:t.layout.height;let ve=N[_e]+b[_e],we=$;const Ae=ye-re;if(1!==te||Z||ie){const t=Math.max(0,Ae);switch(_.alignContent){case e.FlexStart:break;case e.Center:ve+=Ae/2;break;case e.FlexEnd:ve+=Ae;break;case e.Stretch:if(te>0&&t>0){const e=t/te;for(let t=0;t<te;t++)ne[t]+=e}break;case e.SpaceBetween:te>1&&(we+=t/(te-1));break;case e.SpaceAround:te>0&&(we+=t/te,ve+=t/te/2);break;case e.SpaceEvenly:te>0&&(we+=t/(te+1),ve+=t/(te+1))}}else ne[0]=ye;const Me=_.flexWrap===g.WrapReverse,Ne=P?t.layout.height:t.layout.width;let be=ve;for(let t=0;t<te;t++){const i=ee[t],s=ne[t],n=se[t],a=i.length;if(Z||L!==c.Exactly)for(const t of i){const i=t.style,n=i.alignSelf===e.Auto?_.alignItems:i.alignSelf,a=isDefined(resolveValue(P?i.height:i.width,P?X:Q)),l=t._hasAutoMargin&&(isMarginAuto(i.margin,_e)||isMarginAuto(i.margin,pe));if(n===e.Stretch&&!a&&!l){const e=childMarginForAxis(t,O,Q),i=Math.max(0,s-e);if(t._crossSize!==i){layoutNode(t,P?t._mainSize:i,P?i:t._mainSize,c.Exactly,c.Exactly,Q,X,d,P,!P),t._crossSize=i}}}let l=N[ge]+b[ge],r=Y,o=0;for(const e of i)e._hasAutoMargin&&(isMarginAuto(e.style.margin,ge)&&o++,isMarginAuto(e.style.margin,me)&&o++);const u=de-n,f=Math.max(0,u),y=o>0&&f>0?f/o:0;if(0===o)switch(_.justifyContent){case h.FlexStart:break;case h.Center:l+=u/2;break;case h.FlexEnd:l+=u;break;case h.SpaceBetween:a>1&&(r+=f/(a-1));break;case h.SpaceAround:a>0&&(r+=f/a,l+=f/a/2);break;case h.SpaceEvenly:a>0&&(r+=f/(a+1),l+=f/(a+1))}const g=Me?Ne-be-s:be;let m=l;for(const n of i){const i=n.style.margin,a=n.layout.margin;let l,o,u,h,c=!1,f=!1,d=!1,p=!1;n._hasAutoMargin?(c=isMarginAuto(i,ge),f=isMarginAuto(i,me),d=isMarginAuto(i,_e),p=isMarginAuto(i,pe),l=c?y:a[ge],o=f?y:a[me],u=d?0:a[_e],h=p?0:a[pe]):(l=a[ge],o=a[me],u=a[_e],h=a[pe]);const x=xe?De-(m+l)-n._mainSize:m+l,D=n.style.alignSelf===e.Auto?_.alignItems:n.style.alignSelf;let v=g+u;const w=s-n._crossSize-u-h;if(d&&p)v+=Math.max(0,w)/2;else if(d)v+=Math.max(0,w);else if(p);else switch(D){case e.FlexStart:case e.Stretch:Me&&(v+=w);break;case e.Center:v+=w/2;break;case e.FlexEnd:Me||(v+=w);break;case e.Baseline:ie&&(v=g+ae[t]-calculateBaseline(n))}let A=0,M=0;if(n._hasPosition){const e=resolveValue(resolveEdgeRaw(n.style.position,0),Q),t=resolveValue(resolveEdgeRaw(n.style.position,2),Q),i=resolveValue(resolveEdgeRaw(n.style.position,1),Q),s=resolveValue(resolveEdgeRaw(n.style.position,3),Q);A=isDefined(e)?e:isDefined(t)?-t:0,M=isDefined(i)?i:isDefined(s)?-s:0}P?(n.layout.left=x+A,n.layout.top=v+M):(n.layout.left=v+A,n.layout.top=x+M),m+=n._mainSize+l+o+r}be+=s+we}for(const e of K)layoutAbsoluteChild(t,e,t.layout.width,t.layout.height,N,b)}function layoutAbsoluteChild(t,i,s,n,a,l){const r=i.style,o=resolveEdgeRaw(r.position,0),u=resolveEdgeRaw(r.position,2),h=resolveEdgeRaw(r.position,1),f=resolveEdgeRaw(r.position,3),d=resolveValue(o,s),y=resolveValue(u,s),m=resolveValue(h,n),_=resolveValue(f,n),p=s-l[0]-l[2],x=n-l[1]-l[3];let D=resolveValue(r.width,p),v=resolveValue(r.height,x);!isDefined(D)&&isDefined(d)&&isDefined(y)&&(D=p-d-y),!isDefined(v)&&isDefined(m)&&isDefined(_)&&(v=x-m-_),layoutNode(i,D,v,isDefined(D)?c.Exactly:c.Undefined,isDefined(v)?c.Exactly:c.Undefined,p,x,!0);const w=resolveEdge(r.margin,0,s),A=resolveEdge(r.margin,1,s),M=resolveEdge(r.margin,2,s),N=resolveEdge(r.margin,3,s),b=t.style.flexDirection,F=isReverse(b),E=isRow(b),S=t.style.flexWrap===g.WrapReverse,k=r.alignSelf===e.Auto?t.style.alignItems:r.alignSelf;let W,C;if(isDefined(d))W=l[0]+d+w;else if(isDefined(y))W=s-l[2]-y-i.layout.width-M;else if(E){const e=a[0]+l[0],n=s-a[2]-l[2];W=F?n-i.layout.width-M:justifyAbsolute(t.style.justifyContent,e,n,i.layout.width)+w}else W=alignAbsolute(k,a[0]+l[0],s-a[2]-l[2],i.layout.width,S)+w;if(isDefined(m))C=l[1]+m+A;else if(isDefined(_))C=n-l[3]-_-i.layout.height-N;else if(E)C=alignAbsolute(k,a[1]+l[1],n-a[3]-l[3],i.layout.height,S)+A;else{const e=a[1]+l[1],s=n-a[3]-l[3];C=F?s-i.layout.height-N:justifyAbsolute(t.style.justifyContent,e,s,i.layout.height)+A}i.layout.left=W,i.layout.top=C}function justifyAbsolute(e,t,i,s){switch(e){case h.Center:return t+(i-t-s)/2;case h.FlexEnd:return i-s;default:return t}}function alignAbsolute(t,i,s,n,a){switch(t){case e.Center:return i+(s-i-n)/2;case e.FlexEnd:return a?i:s-n;default:return a?s-n:i}}function computeFlexBasis(t,i,s,n,a,l,r){if((t._fbGen===D||!t.isDirty_)&&t._fbCrossMode===a&&sameFloat(t._fbOwnerW,l)&&sameFloat(t._fbOwnerH,r)&&sameFloat(t._fbAvailMain,s)&&sameFloat(t._fbAvailCross,n))return t._fbBasis;const o=t.style,u=isRow(i),h=resolveValue(o.flexBasis,s);if(isDefined(h)){const e=Math.max(0,h);return t._fbBasis=e,t._fbOwnerW=l,t._fbOwnerH=r,t._fbAvailMain=s,t._fbAvailCross=n,t._fbCrossMode=a,t._fbGen=D,e}const f=resolveValue(u?o.width:o.height,u?l:r);if(isDefined(f)){const e=Math.max(0,f);return t._fbBasis=e,t._fbOwnerW=l,t._fbOwnerH=r,t._fbAvailMain=s,t._fbAvailCross=n,t._fbCrossMode=a,t._fbGen=D,e}let d=resolveValue(u?o.height:o.width,u?r:l),y=isDefined(d)?c.Exactly:c.Undefined;!isDefined(d)&&isDefined(n)&&(d=n,y=a===c.Exactly&&function(t){const i=t.parent;if(!i)return!1;const s=t.style.alignSelf===e.Auto?i.style.alignItems:t.style.alignSelf;return s===e.Stretch}(t)?c.Exactly:c.AtMost);let g=NaN,m=c.Undefined;u&&isDefined(s)&&hasMeasureFuncInSubtree(t)&&(g=s,m=c.AtMost);layoutNode(t,u?g:d,u?d:g,u?m:y,u?y:m,l,r,!1);const _=u?t.layout.width:t.layout.height;return t._fbBasis=_,t._fbOwnerW=l,t._fbOwnerH=r,t._fbAvailMain=s,t._fbAvailCross=n,t._fbCrossMode=a,t._fbGen=D,_}function hasMeasureFuncInSubtree(e){if(e.measureFunc)return!0;for(const t of e.children)if(hasMeasureFuncInSubtree(t))return!0;return!1}function resolveFlexibleLengths(e,t,i,s,n,a){const l=e.length,r=new Array(l).fill(!1),o=isDefined(t)?t-i:0;for(let i=0;i<l;i++){const l=e[i],u=boundAxis(l.style,s,l._flexBasis,n,a);!isDefined(t)||(o>=0?0===l.style.flexGrow:0===l.style.flexShrink)?(l._mainSize=Math.max(0,u),r[i]=!0):l._mainSize=l._flexBasis}const u=new Array(l);for(let t=0;t<=l;t++){let t=0,i=0,h=0,c=0;for(let s=0;s<l;s++){const n=e[s];r[s]?t+=n._mainSize-n._flexBasis:(i+=n.style.flexGrow,h+=n.style.flexShrink*n._flexBasis,c++)}if(0===c)break;let f=o-t;if(f>0&&i>0&&i<1){const e=o*i;e<f&&(f=e)}else if(f<0&&h>0){let t=0;for(let i=0;i<l;i++)r[i]||(t+=e[i].style.flexShrink);if(t<1){const e=o*t;e>f&&(f=e)}}let d=0;for(let t=0;t<l;t++){if(r[t])continue;const l=e[t];let o=l._flexBasis;f>0&&i>0?o+=f*l.style.flexGrow/i:f<0&&h>0&&(o+=f*(l.style.flexShrink*l._flexBasis)/h),u[t]=o;const c=Math.max(0,boundAxis(l.style,s,o,n,a));l._mainSize=c,d+=c-o}if(0===d)break;let y=!1;for(let t=0;t<l;t++){if(r[t])continue;const i=e[t]._mainSize-u[t];(d>0&&i>0||d<0&&i<0)&&(r[t]=!0,y=!0)}if(!y)break}}function resolveChildAlign(t,i){return i.style.alignSelf===e.Auto?t.style.alignItems:i.style.alignSelf}function calculateBaseline(t){let i=null;for(const s of t.children){if(s._lineIndex>0)break;if(s.style.positionType!==d.Absolute&&s.style.display!==n.None){if(resolveChildAlign(t,s)===e.Baseline||s.isReferenceBaseline_){i=s;break}null===i&&(i=s)}}return null===i?t.layout.height:calculateBaseline(i)+i.layout.top}function childMarginForAxis(e,t,i){if(!e._hasMargin)return 0;return resolveEdge(e.style.margin,leadingEdge(t),i)+resolveEdge(e.style.margin,trailingEdge(t),i)}function resolveGap(e,t,i){let s=e.gap[t];s.unit===y.Undefined&&(s=e.gap[u.All]);const n=resolveValue(s,i);return isDefined(n)?Math.max(0,n):0}function boundAxis(e,t,i,s,n){const a=t?e.minWidth:e.minHeight,l=t?e.maxWidth:e.maxHeight,r=a.unit,o=l.unit;if(0===r&&0===o)return i;const u=t?s:n;let h=i;if(1===o)h>l.value&&(h=l.value);else if(2===o){const e=l.value*u/100;e==e&&h>e&&(h=e)}if(1===r)h<a.value&&(h=a.value);else if(2===r){const e=a.value*u/100;e==e&&h<e&&(h=e)}return h}function zeroLayoutRecursive(e){for(const t of e.children)t.layout.left=0,t.layout.top=0,t.layout.width=0,t.layout.height=0,t.isDirty_=!0,t._hasL=!1,t._hasM=!1,zeroLayoutRecursive(t)}function collectLayoutChildren(e,t,i){for(const s of e.children){const e=s.style.display;e===n.None?(s.layout.left=0,s.layout.top=0,s.layout.width=0,s.layout.height=0,zeroLayoutRecursive(s)):e===n.Contents?(s.layout.left=0,s.layout.top=0,s.layout.width=0,s.layout.height=0,collectLayoutChildren(s,t,i)):s.style.positionType===d.Absolute?i.push(s):t.push(s)}}function roundLayout(e,t,i,s){if(0===t)return;const n=e.layout,a=n.left,l=n.top,r=n.width,o=n.height,u=i+a,h=s+l,c=null!==e.measureFunc;n.left=roundValue(a,t,!1,c),n.top=roundValue(l,t,!1,c);const f=u+r,d=h+o,y=!isWholeNumber(r*t),g=!isWholeNumber(o*t);n.width=roundValue(f,t,c&&y,c&&!y)-roundValue(u,t,!1,c),n.height=roundValue(d,t,c&&g,c&&!g)-roundValue(h,t,!1,c);for(const i of e.children)roundLayout(i,t,u,h)}function isWholeNumber(e){const t=e-Math.floor(e);return t<1e-4||t>.9999}function roundValue(e,t,i,s){let n=e*t,a=n-Math.floor(n);return a<0&&(a+=1),n=a<1e-4?Math.floor(n):a>.9999||i?Math.ceil(n):s?Math.floor(n):Math.floor(n)+(a>=.4999?1:0),n/t}function parseDimension(e){if(void 0===e)return m;if("auto"===e)return _;if("number"==typeof e)return Number.isFinite(e)?pointValue(e):m;if("string"==typeof e&&e.endsWith("%"))return percentValue(parseFloat(e));const t=parseFloat(e);return isNaN(t)?m:pointValue(t)}function physicalEdge(e){switch(e){case a.Left:case a.Start:return 0;case a.Top:return 1;case a.Right:case a.End:return 2;case a.Bottom:return 3;default:return 0}}const N={Config:{create:createConfig,destroy(){}},Node:{create:e=>new Node(e),createDefault:()=>new Node,createWithConfig:e=>new Node(e),destroy(){}}};export function loadYoga(){return Promise.resolve(N)}export default N;
@@ -1 +1 @@
1
- import{HOOK_EVENTS as e}from"src/entrypoints/agentSdkTypes.js";import{z as o}from"zod/v4";import{lazySchema as t}from"../utils/lazySchema.js";import{SHELL_TYPES as s}from"../utils/shell/shellProvider.js";const i=t(()=>o.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));export const HookCommandSchema=t(()=>{const{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:r,HttpHookSchema:n}={BashCommandHookSchema:o.object({type:o.literal("command").describe("Shell command hook type"),command:o.string().describe("Shell command to execute"),if:i(),shell:o.enum(s).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash."),timeout:o.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:o.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:o.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async.")}),PromptHookSchema:o.object({type:o.literal("prompt").describe("LLM prompt hook type"),prompt:o.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:i(),timeout:o.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:o.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-4-6"). If not specified, uses the default small fast model.'),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution")}),HttpHookSchema:o.object({type:o.literal("http").describe("HTTP hook type"),url:o.string().url().describe("URL to POST the hook input JSON to"),if:i(),timeout:o.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:o.record(o.string(),o.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:o.array(o.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution")}),AgentHookSchema:o.object({type:o.literal("agent").describe("Agentic verifier hook type"),prompt:o.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:i(),timeout:o.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:o.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution")})};return o.discriminatedUnion("type",[e,t,r,n])});export const HookMatcherSchema=t(()=>o.object({matcher:o.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:o.array(HookCommandSchema()).describe("List of hooks to execute when the matcher matches")}));export const HooksSchema=t(()=>o.partialRecord(o.enum(e),o.array(HookMatcherSchema())));
1
+ import{HOOK_EVENTS as e}from"../entrypoints/agentSdkTypes.js";import{z as o}from"zod/v4";import{lazySchema as t}from"../utils/lazySchema.js";import{SHELL_TYPES as s}from"../utils/shell/shellProvider.js";const i=t(()=>o.string().optional().describe('Permission rule syntax to filter when this hook runs (e.g., "Bash(git *)"). Only runs if the tool call matches the pattern. Avoids spawning hooks for non-matching commands.'));export const HookCommandSchema=t(()=>{const{BashCommandHookSchema:e,PromptHookSchema:t,AgentHookSchema:r,HttpHookSchema:n}={BashCommandHookSchema:o.object({type:o.literal("command").describe("Shell command hook type"),command:o.string().describe("Shell command to execute"),if:i(),shell:o.enum(s).optional().describe("Shell interpreter. 'bash' uses your $SHELL (bash/zsh/sh); 'powershell' uses pwsh. Defaults to bash."),timeout:o.number().positive().optional().describe("Timeout in seconds for this specific command"),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution"),async:o.boolean().optional().describe("If true, hook runs in background without blocking"),asyncRewake:o.boolean().optional().describe("If true, hook runs in background and wakes the model on exit code 2 (blocking error). Implies async.")}),PromptHookSchema:o.object({type:o.literal("prompt").describe("LLM prompt hook type"),prompt:o.string().describe("Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON."),if:i(),timeout:o.number().positive().optional().describe("Timeout in seconds for this specific prompt evaluation"),model:o.string().optional().describe('Model to use for this prompt hook (e.g., "claude-sonnet-4-6"). If not specified, uses the default small fast model.'),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution")}),HttpHookSchema:o.object({type:o.literal("http").describe("HTTP hook type"),url:o.string().url().describe("URL to POST the hook input JSON to"),if:i(),timeout:o.number().positive().optional().describe("Timeout in seconds for this specific request"),headers:o.record(o.string(),o.string()).optional().describe('Additional headers to include in the request. Values may reference environment variables using $VAR_NAME or ${VAR_NAME} syntax (e.g., "Authorization": "Bearer $MY_TOKEN"). Only variables listed in allowedEnvVars will be interpolated.'),allowedEnvVars:o.array(o.string()).optional().describe("Explicit list of environment variable names that may be interpolated in header values. Only variables listed here will be resolved; all other $VAR references are left as empty strings. Required for env var interpolation to work."),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution")}),AgentHookSchema:o.object({type:o.literal("agent").describe("Agentic verifier hook type"),prompt:o.string().describe('Prompt describing what to verify (e.g. "Verify that unit tests ran and passed."). Use $ARGUMENTS placeholder for hook input JSON.'),if:i(),timeout:o.number().positive().optional().describe("Timeout in seconds for agent execution (default 60)"),model:o.string().optional().describe('Model to use for this agent hook (e.g., "claude-sonnet-4-6"). If not specified, uses Haiku.'),statusMessage:o.string().optional().describe("Custom status message to display in spinner while hook runs"),once:o.boolean().optional().describe("If true, hook runs once and is removed after execution")})};return o.discriminatedUnion("type",[e,t,r,n])});export const HookMatcherSchema=t(()=>o.object({matcher:o.string().optional().describe('String pattern to match (e.g. tool names like "Write")'),hooks:o.array(HookCommandSchema()).describe("List of hooks to execute when the matcher matches")}));export const HooksSchema=t(()=>o.partialRecord(o.enum(e),o.array(HookMatcherSchema())));
@@ -1 +1 @@
1
- import{isFsInaccessible as e}from"../../utils/errors.js";import{getFsImplementation as t}from"../../utils/fsOperations.js";import{getSessionMemoryPath as o}from"../../utils/permissions/filesystem.js";import{sleep as n}from"../../utils/sleep.js";import{logEvent as s}from"../analytics/index.js";export const DEFAULT_SESSION_MEMORY_CONFIG={minimumMessageTokensToInit:1e4,minimumTokensBetweenUpdate:5e3,toolCallsBetweenUpdates:3};let i,r,a={...DEFAULT_SESSION_MEMORY_CONFIG},m=0,u=!1;export function getLastSummarizedMessageId(){return i}export function setLastSummarizedMessageId(e){i=e}export function markExtractionStarted(){r=Date.now()}export function markExtractionCompleted(){r=void 0}export async function waitForSessionMemoryExtraction(){const e=Date.now();for(;r;){if(Date.now()-r>6e4)return;if(Date.now()-e>15e3)return;await n(1e3)}}export async function getSessionMemoryContent(){const n=t(),i=o();try{const e=await n.readFile(i,{encoding:"utf-8"});return s("tengu_session_memory_loaded",{content_length:e.length}),e}catch(t){if(e(t))return null;throw t}}export function setSessionMemoryConfig(e){a={...a,...e}}export function getSessionMemoryConfig(){return{...a}}export function recordExtractionTokenCount(e){m=e}export function isSessionMemoryInitialized(){return u}export function markSessionMemoryInitialized(){u=!0}export function hasMetInitializationThreshold(e){return e>=a.minimumMessageTokensToInit}export function hasMetUpdateThreshold(e){return e-m>=a.minimumTokensBetweenUpdate}export function getToolCallsBetweenUpdates(){return a.toolCallsBetweenUpdates}export function resetSessionMemoryState(){a={...DEFAULT_SESSION_MEMORY_CONFIG},m=0,u=!1,i=void 0,r=void 0}
1
+ import{isFsInaccessible as e}from"../../utils/errors.js";import{getFsImplementation as t}from"../../utils/fsOperations.js";import{getSessionMemoryPath as o}from"../../utils/permissions/filesystem.js";import{sleep as n}from"../../utils/sleep.js";import{logEvent as r}from"../analytics/index.js";export const DEFAULT_SESSION_MEMORY_CONFIG={minimumMessageTokensToInit:1e4,minimumTokensBetweenUpdate:5e3,toolCallsBetweenUpdates:3};let i,s,a={...DEFAULT_SESSION_MEMORY_CONFIG},m=0,u=!1;export function getLastSummarizedMessageId(){return i}export function setLastSummarizedMessageId(e){i=e}export function markExtractionStarted(){s=Date.now()}export function markExtractionCompleted(){s=void 0}export async function waitForSessionMemoryExtraction(){const e=Date.now();for(;s;){if(Date.now()-s>6e4)return;if(Date.now()-e>15e3)return;await n(1e3)}}export async function getSessionMemoryContent(){const n=t(),i=o();try{const e=await n.readFile(i,{encoding:"utf-8"});return r("tengu_session_memory_loaded",{content_length:e.length}),e}catch(t){if(e(t))return null;throw t}}export function setSessionMemoryConfig(e){a={...a,...e}}export function getSessionMemoryConfig(){return{...a}}export function recordExtractionTokenCount(e){m=e}export function isSessionMemoryInitialized(){return u}export function markSessionMemoryInitialized(){u=!0}export function hasMetInitializationThreshold(e){return e>=a.minimumMessageTokensToInit}export function hasMetUpdateThreshold(e){return e-m>=a.minimumTokensBetweenUpdate}export function getToolCallsBetweenUpdates(){return a.toolCallsBetweenUpdates}export function resetSessionMemoryState(){a={...DEFAULT_SESSION_MEMORY_CONFIG},m=0,u=!1,i=void 0,s=void 0}
@@ -1 +1 @@
1
- import e from"@anthropic-ai/sdk/index.js";import{randomUUID as r}from"crypto";import{checkAndRefreshOAuthTokenIfNeeded as s,getAnthropicApiKey as o,getApiKeyFromApiKeyHelper as t,getClaudeAIOAuthTokens as n,getMiniMaxAccessToken as i,isClaudeAISubscriber as c,refreshAndGetAwsCredentials as a,refreshGcpCredentialsIfNeeded as E}from"src/utils/auth.js";import{getUserAgent as _}from"src/utils/http.js";import{getSmallFastModel as p}from"src/utils/model/model.js";import{getAPIProvider as A,isFirstPartyAnthropicBaseUrl as T}from"src/utils/model/providers.js";import{getConfiguredProviderBaseUrl as O}from"src/utils/model/providerBaseUrls.js";import{getProxyFetchOptions as C}from"src/utils/proxy.js";import{getIsNonInteractiveSession as D,getSessionId as l}from"../../bootstrap/state.js";import{getOauthConfig as u}from"../../constants/oauth.js";import{isDebugToStdErr as d,logForDebugging as R}from"../../utils/debug.js";import{getAWSRegion as I,getVertexRegionForModel as g,isEnvTruthy as S}from"../../utils/envUtils.js";function createStderrLogger(){return{error:(e,...r)=>console.error("[Anthropic SDK ERROR]",e,...r),warn:(e,...r)=>console.error("[Anthropic SDK WARN]",e,...r),info:(e,...r)=>console.error("[Anthropic SDK INFO]",e,...r),debug:(e,...r)=>console.error("[Anthropic SDK DEBUG]",e,...r)}}export async function getAnthropicClient({apiKey:m,maxRetries:U,model:h,fetchOverride:v,source:N}){const f=A(),P=process.env.CONTEXT_CODE_CONTAINER_ID??process.env.CLAUDE_CODE_CONTAINER_ID,L=process.env.CONTEXT_CODE_REMOTE_SESSION_ID??process.env.CLAUDE_CODE_REMOTE_SESSION_ID,K=process.env.CLAUDE_AGENT_SDK_CLIENT_APP,H=function(){const e={},r=process.env.ANTHROPIC_CUSTOM_HEADERS;if(!r)return e;const s=r.split(/\n|\r\n/);for(const r of s){if(!r.trim())continue;const s=r.indexOf(":");if(-1===s)continue;const o=r.slice(0,s).trim(),t=r.slice(s+1).trim();o&&(e[o]=t)}return e}(),w={"x-app":"cli","User-Agent":_(),"X-Claude-Code-Session-Id":l(),...H,...P?{"x-claude-remote-container-id":P}:{},...L?{"x-claude-remote-session-id":L}:{},...K?{"x-client-app":K}:{}};R(`[API:request] Creating client, ANTHROPIC_CUSTOM_HEADERS present: ${!!process.env.ANTHROPIC_CUSTOM_HEADERS}, has Authorization header: ${!!H.Authorization}`),S(process.env.CONTEXT_CODE_ADDITIONAL_PROTECTION??process.env.CLAUDE_CODE_ADDITIONAL_PROTECTION)&&(w["x-anthropic-additional-protection"]="true"),R("[API:auth] OAuth token check starting"),await s(),R("[API:auth] OAuth token check complete"),"minimax"===f||c()||await async function(e,r){const s=process.env.ANTHROPIC_AUTH_TOKEN||await t(r);s&&(e.Authorization=`Bearer ${s}`)}(w,D());const x=function(e,s){const o=e??globalThis.fetch,t="firstParty"===A()&&T();return(e,n)=>{const i=new Headers(n?.headers);t&&!i.has(CLIENT_REQUEST_ID_HEADER)&&i.set(CLIENT_REQUEST_ID_HEADER,r());try{const r=e instanceof Request?e.url:String(e),o=i.get(CLIENT_REQUEST_ID_HEADER);R(`[API REQUEST] ${new URL(r).pathname}${o?` ${CLIENT_REQUEST_ID_HEADER}=${o}`:""} source=${s??"unknown"}`)}catch{}return o(e,{...n,headers:i})}}(v,N),k={defaultHeaders:w,maxRetries:U,timeout:parseInt(process.env.API_TIMEOUT_MS||String(6e5),10),dangerouslyAllowBrowser:!0,fetchOptions:C({forAnthropicAPI:!0}),...x&&{fetch:x}};if(S(process.env.CONTEXT_CODE_USE_BEDROCK)||S(process.env.CLAUDE_CODE_USE_BEDROCK)){const{AnthropicBedrock:e}=await import("@anthropic-ai/bedrock-sdk"),r=h===p()&&process.env.ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION?process.env.ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION:I(),s={...k,awsRegion:r,...(S(process.env.CONTEXT_CODE_SKIP_BEDROCK_AUTH)||S(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH))&&{skipAuth:!0},...d()&&{logger:createStderrLogger()}};if(process.env.AWS_BEARER_TOKEN_BEDROCK)s.skipAuth=!0,s.defaultHeaders={...s.defaultHeaders,Authorization:`Bearer ${process.env.AWS_BEARER_TOKEN_BEDROCK}`};else if(!S(process.env.CONTEXT_CODE_SKIP_BEDROCK_AUTH)&&!S(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH)){const e=await a();e&&(s.awsAccessKey=e.accessKeyId,s.awsSecretKey=e.secretAccessKey,s.awsSessionToken=e.sessionToken)}return new e(s)}if(S(process.env.CONTEXT_CODE_USE_FOUNDRY)||S(process.env.CLAUDE_CODE_USE_FOUNDRY)){const{AnthropicFoundry:e}=await import("@anthropic-ai/foundry-sdk");let r;if(!process.env.ANTHROPIC_FOUNDRY_API_KEY)if(S(process.env.CONTEXT_CODE_SKIP_FOUNDRY_AUTH)||S(process.env.CLAUDE_CODE_SKIP_FOUNDRY_AUTH))r=()=>Promise.resolve("");else{const{DefaultAzureCredential:e,getBearerTokenProvider:s}=await import("@azure/identity");r=s(new e,"https://cognitiveservices.azure.com/.default")}return new e({...k,...r&&{azureADTokenProvider:r},...d()&&{logger:createStderrLogger()}})}if(S(process.env.CONTEXT_CODE_USE_VERTEX)||S(process.env.CLAUDE_CODE_USE_VERTEX)){S(process.env.CONTEXT_CODE_SKIP_VERTEX_AUTH)||S(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH)||await E();const[{AnthropicVertex:e},{GoogleAuth:r}]=await Promise.all([import("@anthropic-ai/vertex-sdk"),import("google-auth-library")]),s=process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project,o=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials,t=S(process.env.CONTEXT_CODE_SKIP_VERTEX_AUTH)||S(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH)?{getClient:()=>({getRequestHeaders:()=>({})})}:new r({scopes:["https://www.googleapis.com/auth/cloud-platform"],...s||o?{}:{projectId:process.env.ANTHROPIC_VERTEX_PROJECT_ID}});return new e({...k,region:g(h),googleAuth:t,...d()&&{logger:createStderrLogger()}})}const y=process.env.MINIMAX_BASE_URL||O("minimax")||"https://api.minimax.io/anthropic",B=i(),X={apiKey:"minimax"===f?B:c()?null:m||o(),authToken:"minimax"===f?B:c()?n()?.accessToken:void 0,..."minimax"===f?{baseURL:y}:{},..."ant"===process.env.USER_TYPE&&S(process.env.USE_STAGING_OAUTH)?{baseURL:u().BASE_API_URL}:{},...k,...d()&&{logger:createStderrLogger()}};return new e(X)}export const CLIENT_REQUEST_ID_HEADER="x-client-request-id";
1
+ import e from"@anthropic-ai/sdk/index.js";import{randomUUID as r}from"crypto";import{checkAndRefreshOAuthTokenIfNeeded as o,getAnthropicApiKey as s,getApiKeyFromApiKeyHelper as t,getClaudeAIOAuthTokens as n,getMiniMaxAccessToken as i,isClaudeAISubscriber as _,refreshAndGetAwsCredentials as E,refreshGcpCredentialsIfNeeded as c}from"../../utils/auth.js";import{getUserAgent as a}from"../../utils/http.js";import{getSmallFastModel as p}from"../../utils/model/model.js";import{getAPIProvider as A,isFirstPartyAnthropicBaseUrl as T}from"../../utils/model/providers.js";import{getConfiguredProviderBaseUrl as O}from"../../utils/model/providerBaseUrls.js";import{getProxyFetchOptions as C}from"../../utils/proxy.js";import{getIsNonInteractiveSession as D,getSessionId as R}from"../../bootstrap/state.js";import{getOauthConfig as u}from"../../constants/oauth.js";import{isDebugToStdErr as l,logForDebugging as I}from"../../utils/debug.js";import{getAWSRegion as S,getVertexRegionForModel as m,isEnvTruthy as d}from"../../utils/envUtils.js";function createStderrLogger(){return{error:(e,...r)=>console.error("[Anthropic SDK ERROR]",e,...r),warn:(e,...r)=>console.error("[Anthropic SDK WARN]",e,...r),info:(e,...r)=>console.error("[Anthropic SDK INFO]",e,...r),debug:(e,...r)=>console.error("[Anthropic SDK DEBUG]",e,...r)}}export async function getAnthropicClient({apiKey:U,maxRetries:v,model:N,fetchOverride:h,source:g}){const f=A(),L=process.env.CONTEXT_CODE_CONTAINER_ID??process.env.CLAUDE_CODE_CONTAINER_ID,P=process.env.CONTEXT_CODE_REMOTE_SESSION_ID??process.env.CLAUDE_CODE_REMOTE_SESSION_ID,H=process.env.CLAUDE_AGENT_SDK_CLIENT_APP,K=function(){const e={},r=process.env.ANTHROPIC_CUSTOM_HEADERS;if(!r)return e;const o=r.split(/\n|\r\n/);for(const r of o){if(!r.trim())continue;const o=r.indexOf(":");if(-1===o)continue;const s=r.slice(0,o).trim(),t=r.slice(o+1).trim();s&&(e[s]=t)}return e}(),w={"x-app":"cli","User-Agent":a(),"X-Claude-Code-Session-Id":R(),...K,...L?{"x-claude-remote-container-id":L}:{},...P?{"x-claude-remote-session-id":P}:{},...H?{"x-client-app":H}:{}};I(`[API:request] Creating client, ANTHROPIC_CUSTOM_HEADERS present: ${!!process.env.ANTHROPIC_CUSTOM_HEADERS}, has Authorization header: ${!!K.Authorization}`);d(process.env.CONTEXT_CODE_ADDITIONAL_PROTECTION??process.env.CLAUDE_CODE_ADDITIONAL_PROTECTION)&&(w["x-anthropic-additional-protection"]="true"),I("[API:auth] OAuth token check starting"),await o(),I("[API:auth] OAuth token check complete"),"minimax"===f||_()||await async function(e,r){const o=process.env.ANTHROPIC_AUTH_TOKEN||await t(r);o&&(e.Authorization=`Bearer ${o}`)}(w,D());const x=function(e,o){const s=e??globalThis.fetch,t="firstParty"===A()&&T();return(e,n)=>{const i=new Headers(n?.headers);t&&!i.has(CLIENT_REQUEST_ID_HEADER)&&i.set(CLIENT_REQUEST_ID_HEADER,r());try{const r=e instanceof Request?e.url:String(e),s=i.get(CLIENT_REQUEST_ID_HEADER);I(`[API REQUEST] ${new URL(r).pathname}${s?` ${CLIENT_REQUEST_ID_HEADER}=${s}`:""} source=${o??"unknown"}`)}catch{}return s(e,{...n,headers:i})}}(h,g),X={defaultHeaders:w,maxRetries:v,timeout:parseInt(process.env.API_TIMEOUT_MS||String(6e5),10),dangerouslyAllowBrowser:!0,fetchOptions:C({forAnthropicAPI:!0}),...x&&{fetch:x}};if(d(process.env.CONTEXT_CODE_USE_BEDROCK)||d(process.env.CLAUDE_CODE_USE_BEDROCK)){const{AnthropicBedrock:e}=await import("@anthropic-ai/bedrock-sdk"),r=N===p()&&process.env.ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION?process.env.ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION:S(),o={...X,awsRegion:r,...(d(process.env.CONTEXT_CODE_SKIP_BEDROCK_AUTH)||d(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH))&&{skipAuth:!0},...l()&&{logger:createStderrLogger()}};if(process.env.AWS_BEARER_TOKEN_BEDROCK)o.skipAuth=!0,o.defaultHeaders={...o.defaultHeaders,Authorization:`Bearer ${process.env.AWS_BEARER_TOKEN_BEDROCK}`};else if(!d(process.env.CONTEXT_CODE_SKIP_BEDROCK_AUTH)&&!d(process.env.CLAUDE_CODE_SKIP_BEDROCK_AUTH)){const e=await E();e&&(o.awsAccessKey=e.accessKeyId,o.awsSecretKey=e.secretAccessKey,o.awsSessionToken=e.sessionToken)}return new e(o)}if(d(process.env.CONTEXT_CODE_USE_FOUNDRY)||d(process.env.CLAUDE_CODE_USE_FOUNDRY)){const{AnthropicFoundry:e}=await import("@anthropic-ai/foundry-sdk");let r;if(!process.env.ANTHROPIC_FOUNDRY_API_KEY)if(d(process.env.CONTEXT_CODE_SKIP_FOUNDRY_AUTH)||d(process.env.CLAUDE_CODE_SKIP_FOUNDRY_AUTH))r=()=>Promise.resolve("");else{const{DefaultAzureCredential:e,getBearerTokenProvider:o}=await import("@azure/identity");r=o(new e,"https://cognitiveservices.azure.com/.default")}return new e({...X,...r&&{azureADTokenProvider:r},...l()&&{logger:createStderrLogger()}})}if(d(process.env.CONTEXT_CODE_USE_VERTEX)||d(process.env.CLAUDE_CODE_USE_VERTEX)){d(process.env.CONTEXT_CODE_SKIP_VERTEX_AUTH)||d(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH)||await c();const[{AnthropicVertex:e},{GoogleAuth:r}]=await Promise.all([import("@anthropic-ai/vertex-sdk"),import("google-auth-library")]),o=process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project,s=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials,t=d(process.env.CONTEXT_CODE_SKIP_VERTEX_AUTH)||d(process.env.CLAUDE_CODE_SKIP_VERTEX_AUTH)?{getClient:()=>({getRequestHeaders:()=>({})})}:new r({scopes:["https://www.googleapis.com/auth/cloud-platform"],...o||s?{}:{projectId:process.env.ANTHROPIC_VERTEX_PROJECT_ID}});return new e({...X,region:m(N),googleAuth:t,...l()&&{logger:createStderrLogger()}})}const k=process.env.MINIMAX_BASE_URL||O("minimax")||"https://api.minimax.io/anthropic",B=i(),y={apiKey:"minimax"===f?B:_()?null:U||s(),authToken:"minimax"===f?B:_()?n()?.accessToken:void 0,..."minimax"===f?{baseURL:k}:{},..."ant"===process.env.USER_TYPE&&d(process.env.USE_STAGING_OAUTH)?{baseURL:u().BASE_API_URL}:{},...X,...l()&&{logger:createStderrLogger()}};return new e(y)}export const CLIENT_REQUEST_ID_HEADER="x-client-request-id";
@@ -1 +1 @@
1
- import{createHash as t}from"crypto";import{promises as e}from"fs";import{dirname as s,join as a}from"path";import{getSessionId as n}from"../../bootstrap/state.js";import{getClaudeConfigHomeDir as o}from"../../utils/envUtils.js";import{jsonParse as i,jsonStringify as r}from"../../utils/slowOperations.js";const p=[],c=new Map;export function getLastApiRequests(){return[...p]}export function clearApiRequestCache(){p.length=0}export function clearDumpState(t){c.delete(t)}export function clearAllDumpState(){c.clear()}export function addApiRequestToCache(t){"ant"===process.env.USER_TYPE&&(p.push({timestamp:(new Date).toISOString(),request:t}),p.length>5&&p.shift())}export function getDumpPromptsPath(t){return a(o(),"dump-prompts",`${t??n()}.jsonl`)}function dumpRequest(a,n,o,p){try{const m=i(a);if(addApiRequestToCache(m),"ant"!==process.env.USER_TYPE)return;const l=[],u=m.messages??[],d=function(t){const e=t.tools,s=t.system,a="string"==typeof s?s.length:Array.isArray(s)?s.reduce((t,e)=>t+(e.text?.length??0),0):0,n=e?.map(t=>t.name??"").join(",")??"";return`${t.model}|${n}|${a}`}(m);if(!o.initialized||d!==o.lastInitFingerprint){const{messages:e,...s}=m,a=r(s),i=(c=a,t("sha256").update(c).digest("hex"));o.lastInitFingerprint=d,o.initialized?i!==o.lastInitDataHash&&(o.lastInitDataHash=i,l.push(`{"type":"system_update","timestamp":"${n}","data":${a}}`)):(o.initialized=!0,o.lastInitDataHash=i,l.push(`{"type":"init","timestamp":"${n}","data":${a}}`))}for(const t of u.slice(o.messageCountSeen))"user"===t.role&&l.push(r({type:"message",timestamp:n,data:t}));o.messageCountSeen=u.length,function(t,a){0!==a.length&&e.mkdir(s(t),{recursive:!0}).then(()=>e.appendFile(t,a.join("\n")+"\n")).catch(()=>{})}(p,l)}catch{}var c}export function createDumpPromptsFetch(t){const s=getDumpPromptsPath(t);return async(a,n)=>{const o=c.get(t)??{initialized:!1,messageCountSeen:0,lastInitDataHash:"",lastInitFingerprint:""};let p;c.set(t,o),"POST"===n?.method&&n.body&&(p=(new Date).toISOString(),setImmediate(dumpRequest,n.body,p,o,s));const m=await globalThis.fetch(a,n);if(p&&m.ok&&"ant"===process.env.USER_TYPE){const t=m.clone();(async()=>{try{const a=t.headers.get("content-type")?.includes("text/event-stream");let n;if(a&&t.body){const e=t.body.getReader(),s=new TextDecoder;let a="";try{for(;;){const{done:t,value:n}=await e.read();if(t)break;a+=s.decode(n,{stream:!0})}}finally{e.releaseLock()}const o=[];for(const t of a.split("\n\n"))for(const e of t.split("\n"))if(e.startsWith("data: ")&&"data: [DONE]"!==e)try{o.push(i(e.slice(6)))}catch{}n={stream:!0,chunks:o}}else n=await t.json();await e.appendFile(s,r({type:"response",timestamp:p,data:n})+"\n")}catch{}})()}return m}}
1
+ import{createHash as t}from"crypto";import{promises as e}from"fs";import{dirname as s,join as n}from"path";import{getSessionId as a}from"../../bootstrap/state.js";import{getClaudeConfigHomeDir as o}from"../../utils/envUtils.js";import{jsonParse as i,jsonStringify as r}from"../../utils/slowOperations.js";const p=[],c=new Map;export function getLastApiRequests(){return[...p]}export function clearApiRequestCache(){p.length=0}export function clearDumpState(t){c.delete(t)}export function clearAllDumpState(){c.clear()}export function addApiRequestToCache(t){"ant"===process.env.USER_TYPE&&(p.push({timestamp:(new Date).toISOString(),request:t}),p.length>5&&p.shift())}export function getDumpPromptsPath(t){return n(o(),"dump-prompts",`${t??a()}.jsonl`)}function dumpRequest(n,a,o,p){try{const m=i(n);if(addApiRequestToCache(m),"ant"!==process.env.USER_TYPE)return;const l=[],u=m.messages??[],d=function(t){const e=t.tools,s=t.system,n="string"==typeof s?s.length:Array.isArray(s)?s.reduce((t,e)=>t+(e.text?.length??0),0):0,a=e?.map(t=>t.name??"").join(",")??"";return`${t.model}|${a}|${n}`}(m);if(!o.initialized||d!==o.lastInitFingerprint){const{messages:e,...s}=m,n=r(s),i=(c=n,t("sha256").update(c).digest("hex"));o.lastInitFingerprint=d,o.initialized?i!==o.lastInitDataHash&&(o.lastInitDataHash=i,l.push(`{"type":"system_update","timestamp":"${a}","data":${n}}`)):(o.initialized=!0,o.lastInitDataHash=i,l.push(`{"type":"init","timestamp":"${a}","data":${n}}`))}for(const t of u.slice(o.messageCountSeen))"user"===t.role&&l.push(r({type:"message",timestamp:a,data:t}));o.messageCountSeen=u.length,function(t,n){0!==n.length&&e.mkdir(s(t),{recursive:!0}).then(()=>e.appendFile(t,n.join("\n")+"\n")).catch(()=>{})}(p,l)}catch{}var c}export function createDumpPromptsFetch(t){const s=getDumpPromptsPath(t);return async(n,a)=>{const o=c.get(t)??{initialized:!1,messageCountSeen:0,lastInitDataHash:"",lastInitFingerprint:""};let p;c.set(t,o),"POST"===a?.method&&a.body&&(p=(new Date).toISOString(),setImmediate(dumpRequest,a.body,p,o,s));const m=await globalThis.fetch(n,a);if(p&&m.ok&&"ant"===process.env.USER_TYPE){const t=m.clone();(async()=>{try{const n=t.headers.get("content-type")?.includes("text/event-stream");let a;if(n&&t.body){const e=t.body.getReader(),s=new TextDecoder;let n="";try{for(;;){const{done:t,value:a}=await e.read();if(t)break;n+=s.decode(a,{stream:!0})}}finally{e.releaseLock()}const o=[];for(const t of n.split("\n\n"))for(const e of t.split("\n"))if(e.startsWith("data: ")&&"data: [DONE]"!==e)try{o.push(i(e.slice(6)))}catch{}a={stream:!0,chunks:o}}else a=await t.json();await e.appendFile(s,r({type:"response",timestamp:p,data:a})+"\n")}catch{}})()}return m}}
@@ -1 +1 @@
1
- const e=new Set(["UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CERT_REVOKED","CERT_REJECTED","CERT_UNTRUSTED","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","CERT_CHAIN_TOO_LONG","PATH_LENGTH_EXCEEDED","ERR_TLS_CERT_ALTNAME_INVALID","HOSTNAME_MISMATCH","ERR_TLS_HANDSHAKE_TIMEOUT","ERR_SSL_WRONG_VERSION_NUMBER","ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC"]);export function extractConnectionErrorDetails(t){if(!t||"object"!=typeof t)return null;let r=t,n=0;for(;r&&n<5;){if(r instanceof Error&&"code"in r&&"string"==typeof r.code){const t=r.code,n=e.has(t);return{code:t,message:r.message,isSSLError:n}}if(!(r instanceof Error&&"cause"in r&&r.cause!==r))break;r=r.cause,n++}return null}export function getSSLErrorHint(e){const t=extractConnectionErrorDetails(e);return t?.isSSLError?`SSL certificate error (${t.code}). If you are behind a corporate proxy or TLS-intercepting firewall, set NODE_EXTRA_CA_CERTS to your CA bundle path, or ask IT to allowlist *.anthropic.com. Run /doctor for details.`:null}function sanitizeMessageHTML(e){if(e.includes("<!DOCTYPE html")||e.includes("<html")){const t=e.match(/<title>([^<]+)<\/title>/);return t&&t[1]?t[1].trim():""}return e}export function sanitizeAPIError(e){const t=e.message;return t?sanitizeMessageHTML(t):""}export function formatAPIError(e){const t=extractConnectionErrorDetails(e);if(t){const{code:e,isSSLError:r}=t;if("ETIMEDOUT"===e)return"Request timed out. Check your internet connection and proxy settings";if(r)switch(e){case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"UNABLE_TO_GET_ISSUER_CERT":case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":return"Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates";case"CERT_HAS_EXPIRED":return"Unable to connect to API: SSL certificate has expired";case"CERT_REVOKED":return"Unable to connect to API: SSL certificate has been revoked";case"DEPTH_ZERO_SELF_SIGNED_CERT":case"SELF_SIGNED_CERT_IN_CHAIN":return"Unable to connect to API: Self-signed certificate detected. Check your proxy or corporate SSL certificates";case"ERR_TLS_CERT_ALTNAME_INVALID":case"HOSTNAME_MISMATCH":return"Unable to connect to API: SSL certificate hostname mismatch";case"CERT_NOT_YET_VALID":return"Unable to connect to API: SSL certificate is not yet valid";default:return`Unable to connect to API: SSL error (${e})`}}if("Connection error."===e.message)return t?.code?`Unable to connect to API (${t.code})`:"Unable to connect to API. Check your internet connection";if(!e.message)return function(e){if("object"!=typeof(t=e)||null===t||!("error"in t)||"object"!=typeof t.error||null===t.error)return null;var t;const r=e.error,n=r?.error?.message;if("string"==typeof n&&n.length>0){const e=sanitizeMessageHTML(n);if(e.length>0)return e}const o=r?.message;if("string"==typeof o&&o.length>0){const e=sanitizeMessageHTML(o);if(e.length>0)return e}return null}(e)??`API error (status ${e.status??"unknown"})`;const r=sanitizeAPIError(e);return r!==e.message&&r.length>0?r:e.message}
1
+ const e=new Set(["UNABLE_TO_VERIFY_LEAF_SIGNATURE","UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","CERT_SIGNATURE_FAILURE","CERT_NOT_YET_VALID","CERT_HAS_EXPIRED","CERT_REVOKED","CERT_REJECTED","CERT_UNTRUSTED","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","CERT_CHAIN_TOO_LONG","PATH_LENGTH_EXCEEDED","ERR_TLS_CERT_ALTNAME_INVALID","HOSTNAME_MISMATCH","ERR_TLS_HANDSHAKE_TIMEOUT","ERR_SSL_WRONG_VERSION_NUMBER","ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC"]);export function extractConnectionErrorDetails(t){if(!t||"object"!=typeof t)return null;let r=t;let n=0;for(;r&&n<5;){if(r instanceof Error&&"code"in r&&"string"==typeof r.code){const t=r.code,n=e.has(t);return{code:t,message:r.message,isSSLError:n}}if(!(r instanceof Error&&"cause"in r&&r.cause!==r))break;r=r.cause,n++}return null}export function getSSLErrorHint(e){const t=extractConnectionErrorDetails(e);return t?.isSSLError?`SSL certificate error (${t.code}). If you are behind a corporate proxy or TLS-intercepting firewall, set NODE_EXTRA_CA_CERTS to your CA bundle path, or ask IT to allowlist *.anthropic.com. Run /doctor for details.`:null}function sanitizeMessageHTML(e){if(e.includes("<!DOCTYPE html")||e.includes("<html")){const t=e.match(/<title>([^<]+)<\/title>/);return t&&t[1]?t[1].trim():""}return e}export function sanitizeAPIError(e){const t=e.message;return t?sanitizeMessageHTML(t):""}export function formatAPIError(e){const t=extractConnectionErrorDetails(e);if(t){const{code:e,isSSLError:r}=t;if("ETIMEDOUT"===e)return"Request timed out. Check your internet connection and proxy settings";if(r)switch(e){case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"UNABLE_TO_GET_ISSUER_CERT":case"UNABLE_TO_GET_ISSUER_CERT_LOCALLY":return"Unable to connect to API: SSL certificate verification failed. Check your proxy or corporate SSL certificates";case"CERT_HAS_EXPIRED":return"Unable to connect to API: SSL certificate has expired";case"CERT_REVOKED":return"Unable to connect to API: SSL certificate has been revoked";case"DEPTH_ZERO_SELF_SIGNED_CERT":case"SELF_SIGNED_CERT_IN_CHAIN":return"Unable to connect to API: Self-signed certificate detected. Check your proxy or corporate SSL certificates";case"ERR_TLS_CERT_ALTNAME_INVALID":case"HOSTNAME_MISMATCH":return"Unable to connect to API: SSL certificate hostname mismatch";case"CERT_NOT_YET_VALID":return"Unable to connect to API: SSL certificate is not yet valid";default:return`Unable to connect to API: SSL error (${e})`}}if("Connection error."===e.message)return t?.code?`Unable to connect to API (${t.code})`:"Unable to connect to API. Check your internet connection";if(!e.message)return function(e){if("object"!=typeof(t=e)||null===t||!("error"in t)||"object"!=typeof t.error||null===t.error)return null;var t;const r=e.error,n=r?.error?.message;if("string"==typeof n&&n.length>0){const e=sanitizeMessageHTML(n);if(e.length>0)return e}const o=r?.message;if("string"==typeof o&&o.length>0){const e=sanitizeMessageHTML(o);if(e.length>0)return e}return null}(e)??`API error (status ${e.status??"unknown"})`;const r=sanitizeAPIError(e);return r!==e.message&&r.length>0?r:e.message}
@@ -1 +1 @@
1
- import{createPatch as e}from"diff";import{mkdir as t,writeFile as a}from"fs/promises";import{join as o}from"path";import{logForDebugging as n}from"src/utils/debug.js";import{djb2Hash as s}from"src/utils/hash.js";import{logError as r}from"src/utils/log.js";import{getClaudeTempDir as l}from"src/utils/permissions/filesystem.js";import{jsonStringify as d}from"src/utils/slowOperations.js";import{logEvent as c}from"../analytics/index.js";const h=new Map,i=["repl_main_thread","sdk","agent:custom","agent:default","agent:builtin"];export const CACHE_TTL_1HOUR_MS=36e5;function getTrackingKey(e,t){if("compact"===e)return"repl_main_thread";for(const a of i)if(e.startsWith(a))return t||e;return null}function stripCacheControl(e){return e.map(e=>{if(!("cache_control"in e))return e;const{cache_control:t,...a}=e;return a})}function computeHash(e){const t=d(e);if("undefined"!=typeof Bun){const e=Bun.hash(t);return"bigint"==typeof e?Number(0xffffffffn&e):e}return s(t)}function sanitizeToolName(e){return e.startsWith("mcp__")?"mcp":e}export function recordPromptState(e){try{const{system:t,toolSchemas:a,querySource:o,model:n,agentId:s,fastMode:r,globalCacheStrategy:l="",betas:c=[],autoModeActive:i=!1,isUsingOverage:g=!1,cachedMCEnabled:u=!1,effortValue:m,extraBodyParams:C}=e,f=getTrackingKey(o,s);if(!f)return;const p=stripCacheControl(t),y=stripCacheControl(a),b=computeHash(p),v=computeHash(y),T=computeHash(t.map(e=>"cache_control"in e?e.cache_control:null)),M=a.map(e=>"name"in e?e.name:"unknown"),computeToolHashes=()=>function(e,t){const a={};for(let o=0;o<e.length;o++)a[t[o]??`__idx_${o}`]=computeHash(e[o]);return a}(y,M),S=function(e){let t=0;for(const a of e)t+=a.text.length;return t}(t),lazyDiffableContent=()=>function(e,t,a){const o=e.map(e=>e.text).join("\n\n"),n=t.map(e=>{if(!("name"in e))return"unknown";const t="description"in e?e.description:"",a="input_schema"in e?d(e.input_schema):"";return`${e.name}\n description: ${t}\n input_schema: ${a}`}).sort().join("\n\n");return`Model: ${a}\n\n=== System Prompt ===\n\n${o}\n\n=== Tools (${t.length}) ===\n\n${n}\n`}(t,a,n),$=r??!1,k=[...c].sort(),x=void 0===m?"":String(m),H=void 0===C?0:computeHash(C),w=h.get(f);if(!w){for(;h.size>=10;){const e=h.keys().next().value;void 0!==e&&h.delete(e)}return void h.set(f,{systemHash:b,toolsHash:v,cacheControlHash:T,toolNames:M,systemCharCount:S,model:n,fastMode:$,globalCacheStrategy:l,betas:k,autoModeActive:i,isUsingOverage:g,cachedMCEnabled:u,effortValue:x,extraBodyHash:H,callCount:1,pendingChanges:null,prevCacheReadTokens:null,cacheDeletionsPending:!1,buildDiffableContent:lazyDiffableContent,perToolHashes:computeToolHashes()})}w.callCount++;const B=b!==w.systemHash,_=v!==w.toolsHash,j=n!==w.model,D=$!==w.fastMode,P=T!==w.cacheControlHash,A=l!==w.globalCacheStrategy,E=k.length!==w.betas.length||k.some((e,t)=>e!==w.betas[t]),R=i!==w.autoModeActive,N=g!==w.isUsingOverage,O=u!==w.cachedMCEnabled,V=x!==w.effortValue,G=H!==w.extraBodyHash;if(B||_||j||D||P||A||E||R||N||O||V||G){const e=new Set(w.toolNames),t=new Set(M),a=new Set(w.betas),o=new Set(k),s=M.filter(t=>!e.has(t)),r=w.toolNames.filter(e=>!t.has(e)),d=[];if(_){const t=computeToolHashes();for(const a of M)e.has(a)&&t[a]!==w.perToolHashes[a]&&d.push(a);w.perToolHashes=t}w.pendingChanges={systemPromptChanged:B,toolSchemasChanged:_,modelChanged:j,fastModeChanged:D,cacheControlChanged:P,globalCacheStrategyChanged:A,betasChanged:E,autoModeChanged:R,overageChanged:N,cachedMCChanged:O,effortChanged:V,extraBodyChanged:G,addedToolCount:s.length,removedToolCount:r.length,addedTools:s,removedTools:r,changedToolSchemas:d,systemCharDelta:S-w.systemCharCount,previousModel:w.model,newModel:n,prevGlobalCacheStrategy:w.globalCacheStrategy,newGlobalCacheStrategy:l,addedBetas:k.filter(e=>!a.has(e)),removedBetas:w.betas.filter(e=>!o.has(e)),prevEffortValue:w.effortValue,newEffortValue:x,buildPrevDiffableContent:w.buildDiffableContent}}else w.pendingChanges=null;w.systemHash=b,w.toolsHash=v,w.cacheControlHash=T,w.toolNames=M,w.systemCharCount=S,w.model=n,w.fastMode=$,w.globalCacheStrategy=l,w.betas=k,w.autoModeActive=i,w.isUsingOverage=g,w.cachedMCEnabled=u,w.effortValue=x,w.extraBodyHash=H,w.buildDiffableContent=lazyDiffableContent}catch(e){r(e)}}export async function checkResponseForCacheBreak(s,d,i,g,u,m){try{const r=getTrackingKey(s,u);if(!r)return;const C=h.get(r);if(!C)return;if(C.model.includes("haiku"))return;const f=C.prevCacheReadTokens;C.prevCacheReadTokens=d;const p=g.findLast(e=>"assistant"===e.type),y=p?Date.now()-new Date(p.timestamp).getTime():null;if(null===f)return;const b=C.pendingChanges;if(C.cacheDeletionsPending)return C.cacheDeletionsPending=!1,n(`[PROMPT CACHE] cache deletion applied, cache read: ${f} → ${d} (expected drop)`),void(C.pendingChanges=null);if(d>=.95*f||f-d<2e3)return void(C.pendingChanges=null);const v=[];if(b){if(b.modelChanged&&v.push(`model changed (${b.previousModel} → ${b.newModel})`),b.systemPromptChanged){const e=b.systemCharDelta,t=0===e?"":e>0?` (+${e} chars)`:` (${e} chars)`;v.push(`system prompt changed${t}`)}if(b.toolSchemasChanged){const e=b.addedToolCount>0||b.removedToolCount>0?` (+${b.addedToolCount}/-${b.removedToolCount} tools)`:" (tool prompt/schema changed, same tool set)";v.push(`tools changed${e}`)}if(b.fastModeChanged&&v.push("fast mode toggled"),b.globalCacheStrategyChanged&&v.push(`global cache strategy changed (${b.prevGlobalCacheStrategy||"none"} → ${b.newGlobalCacheStrategy||"none"})`),!b.cacheControlChanged||b.globalCacheStrategyChanged||b.systemPromptChanged||v.push("cache_control changed (scope or TTL)"),b.betasChanged){const e=[b.addedBetas.length?`+${b.addedBetas.join(",")}`:"",b.removedBetas.length?`-${b.removedBetas.join(",")}`:""].filter(Boolean).join(" ");v.push("betas changed"+(e?` (${e})`:""))}b.autoModeChanged&&v.push("auto mode toggled"),b.overageChanged&&v.push("overage state changed (TTL latched, no flip)"),b.cachedMCChanged&&v.push("cached microcompact toggled"),b.effortChanged&&v.push(`effort changed (${b.prevEffortValue||"default"} → ${b.newEffortValue||"default"})`),b.extraBodyChanged&&v.push("extra body params changed")}const T=null!==y&&y>3e5,M=null!==y&&y>36e5;let S,$;S=v.length>0?v.join(", "):M?"possible 1h TTL expiry (prompt unchanged)":T?"possible 5min TTL expiry (prompt unchanged)":null!==y?"likely server-side (prompt unchanged, <5min gap)":"unknown cause",c("tengu_prompt_cache_break",{systemPromptChanged:b?.systemPromptChanged??!1,toolSchemasChanged:b?.toolSchemasChanged??!1,modelChanged:b?.modelChanged??!1,fastModeChanged:b?.fastModeChanged??!1,cacheControlChanged:b?.cacheControlChanged??!1,globalCacheStrategyChanged:b?.globalCacheStrategyChanged??!1,betasChanged:b?.betasChanged??!1,autoModeChanged:b?.autoModeChanged??!1,overageChanged:b?.overageChanged??!1,cachedMCChanged:b?.cachedMCChanged??!1,effortChanged:b?.effortChanged??!1,extraBodyChanged:b?.extraBodyChanged??!1,addedToolCount:b?.addedToolCount??0,removedToolCount:b?.removedToolCount??0,systemCharDelta:b?.systemCharDelta??0,addedTools:(b?.addedTools??[]).map(sanitizeToolName).join(","),removedTools:(b?.removedTools??[]).map(sanitizeToolName).join(","),changedToolSchemas:(b?.changedToolSchemas??[]).map(sanitizeToolName).join(","),addedBetas:(b?.addedBetas??[]).join(","),removedBetas:(b?.removedBetas??[]).join(","),prevGlobalCacheStrategy:b?.prevGlobalCacheStrategy??"",newGlobalCacheStrategy:b?.newGlobalCacheStrategy??"",callNumber:C.callCount,prevCacheReadTokens:f,cacheReadTokens:d,cacheCreationTokens:i,timeSinceLastAssistantMsg:y??-1,lastAssistantMsgOver5minAgo:T,lastAssistantMsgOver1hAgo:M,requestId:m??""}),b?.buildPrevDiffableContent&&($=await async function(n,s){try{const r=function(){let e="";for(let t=0;t<4;t++)e+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(36*Math.random())];return o(l(),`cache-break-${e}.diff`)}();await t(l(),{recursive:!0});const d=e("prompt-state",n,s,"before","after");return await a(r,d),r}catch{return}}(b.buildPrevDiffableContent(),C.buildDiffableContent()));const k=$?`, diff: ${$}`:"",x=`[PROMPT CACHE BREAK] ${S} [source=${s}, call #${C.callCount}, cache read: ${f} → ${d}, creation: ${i}${k}]`;n(x,{level:"warn"}),C.pendingChanges=null}catch(e){r(e)}}export function notifyCacheDeletion(e,t){const a=getTrackingKey(e,t),o=a?h.get(a):void 0;o&&(o.cacheDeletionsPending=!0)}export function notifyCompaction(e,t){const a=getTrackingKey(e,t),o=a?h.get(a):void 0;o&&(o.prevCacheReadTokens=null)}export function cleanupAgentTracking(e){h.delete(e)}export function resetPromptCacheBreakDetection(){h.clear()}
1
+ import{createPatch as e}from"diff";import{mkdir as t,writeFile as a}from"fs/promises";import{join as o}from"path";import{logForDebugging as n}from"../../utils/debug.js";import{djb2Hash as s}from"../../utils/hash.js";import{logError as r}from"../../utils/log.js";import{getClaudeTempDir as l}from"../../utils/permissions/filesystem.js";import{jsonStringify as d}from"../../utils/slowOperations.js";import{logEvent as c}from"../analytics/index.js";const h=new Map,i=["repl_main_thread","sdk","agent:custom","agent:default","agent:builtin"];export const CACHE_TTL_1HOUR_MS=36e5;function getTrackingKey(e,t){if("compact"===e)return"repl_main_thread";for(const a of i)if(e.startsWith(a))return t||e;return null}function stripCacheControl(e){return e.map(e=>{if(!("cache_control"in e))return e;const{cache_control:t,...a}=e;return a})}function computeHash(e){const t=d(e);if("undefined"!=typeof Bun){const e=Bun.hash(t);return"bigint"==typeof e?Number(0xffffffffn&e):e}return s(t)}function sanitizeToolName(e){return e.startsWith("mcp__")?"mcp":e}export function recordPromptState(e){try{const{system:t,toolSchemas:a,querySource:o,model:n,agentId:s,fastMode:r,globalCacheStrategy:l="",betas:c=[],autoModeActive:i=!1,isUsingOverage:g=!1,cachedMCEnabled:u=!1,effortValue:C,extraBodyParams:m}=e,f=getTrackingKey(o,s);if(!f)return;const p=stripCacheControl(t),y=stripCacheControl(a),b=computeHash(p),v=computeHash(y),T=computeHash(t.map(e=>"cache_control"in e?e.cache_control:null)),M=a.map(e=>"name"in e?e.name:"unknown"),computeToolHashes=()=>function(e,t){const a={};for(let o=0;o<e.length;o++)a[t[o]??`__idx_${o}`]=computeHash(e[o]);return a}(y,M),S=function(e){let t=0;for(const a of e)t+=a.text.length;return t}(t),lazyDiffableContent=()=>function(e,t,a){const o=e.map(e=>e.text).join("\n\n"),n=t.map(e=>{if(!("name"in e))return"unknown";const t="description"in e?e.description:"",a="input_schema"in e?d(e.input_schema):"";return`${e.name}\n description: ${t}\n input_schema: ${a}`}).sort().join("\n\n");return`Model: ${a}\n\n=== System Prompt ===\n\n${o}\n\n=== Tools (${t.length}) ===\n\n${n}\n`}(t,a,n),$=r??!1,k=[...c].sort(),x=void 0===C?"":String(C),H=void 0===m?0:computeHash(m),w=h.get(f);if(!w){for(;h.size>=10;){const e=h.keys().next().value;void 0!==e&&h.delete(e)}return void h.set(f,{systemHash:b,toolsHash:v,cacheControlHash:T,toolNames:M,systemCharCount:S,model:n,fastMode:$,globalCacheStrategy:l,betas:k,autoModeActive:i,isUsingOverage:g,cachedMCEnabled:u,effortValue:x,extraBodyHash:H,callCount:1,pendingChanges:null,prevCacheReadTokens:null,cacheDeletionsPending:!1,buildDiffableContent:lazyDiffableContent,perToolHashes:computeToolHashes()})}w.callCount++;const B=b!==w.systemHash,_=v!==w.toolsHash,P=n!==w.model,D=$!==w.fastMode,j=T!==w.cacheControlHash,A=l!==w.globalCacheStrategy,E=k.length!==w.betas.length||k.some((e,t)=>e!==w.betas[t]),R=i!==w.autoModeActive,N=g!==w.isUsingOverage,O=u!==w.cachedMCEnabled,V=x!==w.effortValue,G=H!==w.extraBodyHash;if(B||_||P||D||j||A||E||R||N||O||V||G){const e=new Set(w.toolNames),t=new Set(M),a=new Set(w.betas),o=new Set(k),s=M.filter(t=>!e.has(t)),r=w.toolNames.filter(e=>!t.has(e)),d=[];if(_){const t=computeToolHashes();for(const a of M)e.has(a)&&t[a]!==w.perToolHashes[a]&&d.push(a);w.perToolHashes=t}w.pendingChanges={systemPromptChanged:B,toolSchemasChanged:_,modelChanged:P,fastModeChanged:D,cacheControlChanged:j,globalCacheStrategyChanged:A,betasChanged:E,autoModeChanged:R,overageChanged:N,cachedMCChanged:O,effortChanged:V,extraBodyChanged:G,addedToolCount:s.length,removedToolCount:r.length,addedTools:s,removedTools:r,changedToolSchemas:d,systemCharDelta:S-w.systemCharCount,previousModel:w.model,newModel:n,prevGlobalCacheStrategy:w.globalCacheStrategy,newGlobalCacheStrategy:l,addedBetas:k.filter(e=>!a.has(e)),removedBetas:w.betas.filter(e=>!o.has(e)),prevEffortValue:w.effortValue,newEffortValue:x,buildPrevDiffableContent:w.buildDiffableContent}}else w.pendingChanges=null;w.systemHash=b,w.toolsHash=v,w.cacheControlHash=T,w.toolNames=M,w.systemCharCount=S,w.model=n,w.fastMode=$,w.globalCacheStrategy=l,w.betas=k,w.autoModeActive=i,w.isUsingOverage=g,w.cachedMCEnabled=u,w.effortValue=x,w.extraBodyHash=H,w.buildDiffableContent=lazyDiffableContent}catch(e){r(e)}}export async function checkResponseForCacheBreak(s,d,i,g,u,C){try{const r=getTrackingKey(s,u);if(!r)return;const m=h.get(r);if(!m)return;if(m.model.includes("haiku"))return;const f=m.prevCacheReadTokens;m.prevCacheReadTokens=d;const p=g.findLast(e=>"assistant"===e.type),y=p?Date.now()-new Date(p.timestamp).getTime():null;if(null===f)return;const b=m.pendingChanges;if(m.cacheDeletionsPending)return m.cacheDeletionsPending=!1,n(`[PROMPT CACHE] cache deletion applied, cache read: ${f} → ${d} (expected drop)`),void(m.pendingChanges=null);if(d>=.95*f||f-d<2e3)return void(m.pendingChanges=null);const v=[];if(b){if(b.modelChanged&&v.push(`model changed (${b.previousModel} → ${b.newModel})`),b.systemPromptChanged){const e=b.systemCharDelta,t=0===e?"":e>0?` (+${e} chars)`:` (${e} chars)`;v.push(`system prompt changed${t}`)}if(b.toolSchemasChanged){const e=b.addedToolCount>0||b.removedToolCount>0?` (+${b.addedToolCount}/-${b.removedToolCount} tools)`:" (tool prompt/schema changed, same tool set)";v.push(`tools changed${e}`)}if(b.fastModeChanged&&v.push("fast mode toggled"),b.globalCacheStrategyChanged&&v.push(`global cache strategy changed (${b.prevGlobalCacheStrategy||"none"} → ${b.newGlobalCacheStrategy||"none"})`),!b.cacheControlChanged||b.globalCacheStrategyChanged||b.systemPromptChanged||v.push("cache_control changed (scope or TTL)"),b.betasChanged){const e=b.addedBetas.length?`+${b.addedBetas.join(",")}`:"",t=[e,b.removedBetas.length?`-${b.removedBetas.join(",")}`:""].filter(Boolean).join(" ");v.push("betas changed"+(t?` (${t})`:""))}b.autoModeChanged&&v.push("auto mode toggled"),b.overageChanged&&v.push("overage state changed (TTL latched, no flip)"),b.cachedMCChanged&&v.push("cached microcompact toggled"),b.effortChanged&&v.push(`effort changed (${b.prevEffortValue||"default"} → ${b.newEffortValue||"default"})`),b.extraBodyChanged&&v.push("extra body params changed")}const T=null!==y&&y>3e5,M=null!==y&&y>36e5;let S,$;S=v.length>0?v.join(", "):M?"possible 1h TTL expiry (prompt unchanged)":T?"possible 5min TTL expiry (prompt unchanged)":null!==y?"likely server-side (prompt unchanged, <5min gap)":"unknown cause",c("tengu_prompt_cache_break",{systemPromptChanged:b?.systemPromptChanged??!1,toolSchemasChanged:b?.toolSchemasChanged??!1,modelChanged:b?.modelChanged??!1,fastModeChanged:b?.fastModeChanged??!1,cacheControlChanged:b?.cacheControlChanged??!1,globalCacheStrategyChanged:b?.globalCacheStrategyChanged??!1,betasChanged:b?.betasChanged??!1,autoModeChanged:b?.autoModeChanged??!1,overageChanged:b?.overageChanged??!1,cachedMCChanged:b?.cachedMCChanged??!1,effortChanged:b?.effortChanged??!1,extraBodyChanged:b?.extraBodyChanged??!1,addedToolCount:b?.addedToolCount??0,removedToolCount:b?.removedToolCount??0,systemCharDelta:b?.systemCharDelta??0,addedTools:(b?.addedTools??[]).map(sanitizeToolName).join(","),removedTools:(b?.removedTools??[]).map(sanitizeToolName).join(","),changedToolSchemas:(b?.changedToolSchemas??[]).map(sanitizeToolName).join(","),addedBetas:(b?.addedBetas??[]).join(","),removedBetas:(b?.removedBetas??[]).join(","),prevGlobalCacheStrategy:b?.prevGlobalCacheStrategy??"",newGlobalCacheStrategy:b?.newGlobalCacheStrategy??"",callNumber:m.callCount,prevCacheReadTokens:f,cacheReadTokens:d,cacheCreationTokens:i,timeSinceLastAssistantMsg:y??-1,lastAssistantMsgOver5minAgo:T,lastAssistantMsgOver1hAgo:M,requestId:C??""}),b?.buildPrevDiffableContent&&($=await async function(n,s){try{const r=function(){const e="abcdefghijklmnopqrstuvwxyz0123456789";let t="";for(let a=0;a<4;a++)t+=e[Math.floor(36*Math.random())];return o(l(),`cache-break-${t}.diff`)}();await t(l(),{recursive:!0});const d=e("prompt-state",n,s,"before","after");return await a(r,d),r}catch{return}}(b.buildPrevDiffableContent(),m.buildDiffableContent()));const k=$?`, diff: ${$}`:"",x=`[PROMPT CACHE BREAK] ${S} [source=${s}, call #${m.callCount}, cache read: ${f} → ${d}, creation: ${i}${k}]`;n(x,{level:"warn"}),m.pendingChanges=null}catch(e){r(e)}}export function notifyCacheDeletion(e,t){const a=getTrackingKey(e,t),o=a?h.get(a):void 0;o&&(o.cacheDeletionsPending=!0)}export function notifyCompaction(e,t){const a=getTrackingKey(e,t),o=a?h.get(a):void 0;o&&(o.prevCacheReadTokens=null)}export function cleanupAgentTracking(e){h.delete(e)}export function resetPromptCacheBreakDetection(){h.clear()}
@@ -1 +1 @@
1
- import{feature as e}from"bun:bundle";import{APIConnectionError as t,APIError as r,APIUserAbortError as s}from"@anthropic-ai/sdk/index.js";import{isAwsCredentialsProviderError as o}from"src/utils/aws.js";import{logForDebugging as n}from"src/utils/debug.js";import{logError as a}from"src/utils/log.js";import{createSystemAPIErrorMessage as i}from"src/utils/messages.js";import{getAPIProviderForStatsig as l}from"src/utils/model/providers.js";import{clearApiKeyHelperCache as u,clearAwsCredentialsCache as c,clearGcpCredentialsCache as d,getClaudeAIOAuthTokens as f,handleOAuth401Error as E,isClaudeAISubscriber as m,isEnterpriseSubscriber as p}from"../../utils/auth.js";import{isEnvTruthy as _}from"../../utils/envUtils.js";import{errorMessage as g}from"../../utils/errors.js";import{handleFastModeOverageRejection as h,handleFastModeRejectedByAPI as R,isFastModeCooldown as C,isFastModeEnabled as y,triggerFastModeCooldown as k}from"../../utils/fastMode.js";import{isNonCustomOpusModel as M}from"../../utils/model/model.js";import{disableKeepAlive as T}from"../../utils/proxy.js";import{sleep as A}from"../../utils/sleep.js";import{getFeatureValue_CACHED_MAY_BE_STALE as x}from"../analytics/growthbook.js";import{logEvent as v}from"../analytics/index.js";import{checkMockRateLimitError as b,isMockRateLimitError as w}from"../rateLimitMocking.js";import{REPEATED_529_ERROR_MESSAGE as O}from"./errors.js";import{extractConnectionErrorDetails as D}from"./errorUtils.js";const abortError=()=>new s;export const BASE_DELAY_MS=500;const S=new Set(["repl_main_thread","repl_main_thread:outputStyle:custom","repl_main_thread:outputStyle:Explanatory","repl_main_thread:outputStyle:Learning","sdk","agent:custom","agent:default","agent:builtin","compact","hook_agent","hook_prompt","verification_agent","side_question","auto_mode",...e("BASH_CLASSIFIER")?["bash_classifier"]:[]]);function shouldRetry529(e){return void 0===e||S.has(e)}const N=3e5,P=216e5;function isPersistentRetryEnabled(){return!!e("UNATTENDED_RETRY")&&(_(process.env.CONTEXT_CODE_UNATTENDED_RETRY)||_(process.env.CLAUDE_CODE_UNATTENDED_RETRY))}function isTransientCapacityError(e){return is529Error(e)||e instanceof r&&429===e.status}function isStaleConnectionError(e){if(!(e instanceof t))return!1;const r=D(e);return"ECONNRESET"===r?.code||"EPIPE"===r?.code}export class CannotRetryError extends Error{originalError;retryContext;constructor(e,t){super(g(e)),this.originalError=e,this.retryContext=t,this.name="RetryError",e instanceof Error&&e.stack&&(this.stack=e.stack)}}export class FallbackTriggeredError extends Error{originalModel;fallbackModel;constructor(e,t){super(`Model fallback triggered: ${e} -> ${t}`),this.originalModel=e,this.fallbackModel=t,this.name="FallbackTriggeredError"}}export async function*withRetry(e,t,o){const u=function(e){return e.maxRetries??getDefaultMaxRetries()}(o),c={model:o.model,thinkingConfig:o.thinkingConfig,...y()&&{fastMode:o.fastMode}};let d,p=null,_=o.initialConsecutive529Errors??0,w=0;for(let D=1;D<=u+1;D++){if(o.signal?.aborted)throw new s;const S=!!y()&&c.fastMode&&!C();try{if("ant"===process.env.USER_TYPE){const e=b(c.model,S);if(e)throw e}const s=isStaleConnectionError(d);if(s&&x("tengu_disable_keepalive_on_econnreset",!1)&&(n("Stale connection (ECONNRESET/EPIPE) — disabling keep-alive for retry"),T()),null===p||d instanceof r&&401===d.status||isOAuthTokenRevokedError(d)||isBedrockAuthError(d)||isVertexAuthError(d)||s){if(d instanceof r&&401===d.status||isOAuthTokenRevokedError(d)){const e=f()?.accessToken;e&&await E(e)}p=await e()}return await t(p,D,c)}catch(e){if(d=e,n(`API error (attempt ${D}/${u+1}): ${e instanceof r?`${e.status} ${e.message}`:g(e)}`,{level:"error"}),S&&!isPersistentRetryEnabled()&&e instanceof r&&(429===e.status||is529Error(e))){const t=e.headers?.get("anthropic-ratelimit-unified-overage-disabled-reason");if(null!=t){h(t),c.fastMode=!1;continue}const r=getRetryAfterMs(e);if(null!==r&&r<j){await A(r,o.signal,{abortError});continue}const s=Math.max(r??L,I),n=is529Error(e)?"overloaded":"rate_limit";k(Date.now()+s,n),y()&&(c.fastMode=!1);continue}if(S&&isFastModeNotEnabledError(e)){R(),c.fastMode=!1;continue}if(is529Error(e)&&!shouldRetry529(o.querySource))throw v("tengu_api_529_background_dropped",{query_source:o.querySource}),new CannotRetryError(e,c);if(is529Error(e)&&(process.env.FALLBACK_FOR_ALL_PRIMARY_MODELS||!m()&&M(o.model))&&(_++,_>=3)){if(o.fallbackModel)throw v("tengu_api_opus_fallback_triggered",{original_model:o.model,fallback_model:o.fallbackModel,provider:l()}),new FallbackTriggeredError(o.model,o.fallbackModel);if("external"===process.env.USER_TYPE&&!process.env.IS_SANDBOX&&!isPersistentRetryEnabled())throw v("tengu_api_custom_529_overloaded_error",{}),new CannotRetryError(new Error(O),c)}const t=isPersistentRetryEnabled()&&isTransientCapacityError(e);if(D>u&&!t)throw new CannotRetryError(e,c);if(!(handleAwsCredentialError(e)||handleGcpCredentialError(e)||e instanceof r&&shouldRetry(e)))throw new CannotRetryError(e,c);if(e instanceof r){const t=parseMaxTokensContextOverflowError(e);if(t){const{inputTokens:r,contextLimit:s}=t,o=1e3,n=Math.max(0,s-r-o);if(n<3e3)throw a(new Error(`availableContext ${n} is less than FLOOR_OUTPUT_TOKENS 3000`)),e;const i=("enabled"===c.thinkingConfig.type?c.thinkingConfig.budgetTokens:0)+1,l=Math.max(3e3,n,i);c.maxTokensOverride=l,v("tengu_max_tokens_context_overflow_adjustment",{inputTokens:r,contextLimit:s,adjustedMaxTokens:l,attempt:D});continue}}const f=getRetryAfter(e);let E;t&&e instanceof r&&429===e.status?(w++,E=getRateLimitResetDelayMs(e)??Math.min(getRetryDelay(w,f,N),P)):t?(w++,E=Math.min(getRetryDelay(w,f,N),P)):E=getRetryDelay(D,f);const p=t?w:D;if(v("tengu_api_retry",{attempt:p,delayMs:E,error:e.message,status:e.status,provider:l()}),t){E>6e4&&v("tengu_api_persistent_retry_wait",{status:e.status,delayMs:E,attempt:p,provider:l()});let t=E;for(;t>0;){if(o.signal?.aborted)throw new s;e instanceof r&&(yield i(e,t,p,u));const n=Math.min(t,3e4);await A(n,o.signal,{abortError}),t-=n}D>=u&&(D=u)}else e instanceof r&&(yield i(e,E,D,u)),await A(E,o.signal,{abortError})}}throw new CannotRetryError(d,c)}function getRetryAfter(e){return(e.headers?.["retry-after"]||e.headers?.get?.("retry-after"))??null}export function getRetryDelay(e,t,r=32e3){if(t){const e=parseInt(t,10);if(!isNaN(e))return 1e3*e}const s=Math.min(500*Math.pow(2,e-1),r);return s+.25*Math.random()*s}export function parseMaxTokensContextOverflowError(e){if(400!==e.status||!e.message)return;if(!e.message.includes("input length and `max_tokens` exceed context limit"))return;const t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t||4!==t.length)return;if(!t[1]||!t[2]||!t[3])return void a(new Error("Unable to parse max_tokens from max_tokens exceed context limit error message"));const r=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(t[3],10);return isNaN(r)||isNaN(s)||isNaN(o)?void 0:{inputTokens:r,maxTokens:s,contextLimit:o}}function isFastModeNotEnabledError(e){return e instanceof r&&400===e.status&&(e.message?.includes("Fast mode is not enabled")??!1)}export function is529Error(e){return e instanceof r&&(529===e.status||(e.message?.includes('"type":"overloaded_error"')??!1))}function isOAuthTokenRevokedError(e){return e instanceof r&&403===e.status&&(e.message?.includes("OAuth token has been revoked")??!1)}function isBedrockAuthError(e){return!(!_(process.env.CONTEXT_CODE_USE_BEDROCK)&&!_(process.env.CLAUDE_CODE_USE_BEDROCK)||!(o(e)||e instanceof r&&403===e.status))}function handleAwsCredentialError(e){return!!isBedrockAuthError(e)&&(c(),!0)}function isVertexAuthError(e){if(_(process.env.CONTEXT_CODE_USE_VERTEX)||_(process.env.CLAUDE_CODE_USE_VERTEX)){if(function(e){if(!(e instanceof Error))return!1;const t=e.message;return t.includes("Could not load the default credentials")||t.includes("Could not refresh access token")||t.includes("invalid_grant")}(e))return!0;if(e instanceof r&&401===e.status)return!0}return!1}function handleGcpCredentialError(e){return!!isVertexAuthError(e)&&(d(),!0)}function shouldRetry(e){if(w(e))return!1;if(isPersistentRetryEnabled()&&isTransientCapacityError(e))return!0;if((_(process.env.CONTEXT_CODE_REMOTE)||_(process.env.CLAUDE_CODE_REMOTE))&&(401===e.status||403===e.status))return!0;if(e.message?.includes('"type":"overloaded_error"'))return!0;if(parseMaxTokensContextOverflowError(e))return!0;if(function(e){if(!(e instanceof r))return!1;const t=e.message?.toLowerCase()??"";return t.includes("insufficient balance")||t.includes("(1008)")}(e))return!1;const s=e.headers?.get("x-should-retry");if("true"===s&&(!m()||p()))return!0;if("false"===s){const t=void 0!==e.status&&e.status>=500;if("ant"!==process.env.USER_TYPE||!t)return!1}return e instanceof t||!!e.status&&(408===e.status||409===e.status||(429===e.status?!m()||p():401===e.status?(u(),!0):!!isOAuthTokenRevokedError(e)||!!(e.status&&e.status>=500)))}export function getDefaultMaxRetries(){const e=process.env.CONTEXT_CODE_MAX_RETRIES;return e?parseInt(e,10):10}const L=18e5,j=2e4,I=6e5;function getRetryAfterMs(e){const t=getRetryAfter(e);if(t){const e=parseInt(t,10);if(!isNaN(e))return 1e3*e}return null}function getRateLimitResetDelayMs(e){const t=e.headers?.get?.("anthropic-ratelimit-unified-reset");if(!t)return null;const r=Number(t);if(!Number.isFinite(r))return null;const s=1e3*r-Date.now();return s<=0?null:Math.min(s,P)}
1
+ import{feature as e}from"../../recovery/bunBundleShim.js";import{APIConnectionError as t,APIError as r,APIUserAbortError as n}from"@anthropic-ai/sdk/index.js";import{isAwsCredentialsProviderError as o}from"../../utils/aws.js";import{logForDebugging as s}from"../../utils/debug.js";import{logError as i}from"../../utils/log.js";import{createSystemAPIErrorMessage as a}from"../../utils/messages.js";import{getAPIProviderForStatsig as u}from"../../utils/model/providers.js";import{clearApiKeyHelperCache as l,clearAwsCredentialsCache as c,clearGcpCredentialsCache as f,getClaudeAIOAuthTokens as d,handleOAuth401Error as E,isClaudeAISubscriber as m,isEnterpriseSubscriber as p}from"../../utils/auth.js";import{isEnvTruthy as _}from"../../utils/envUtils.js";import{errorMessage as g}from"../../utils/errors.js";import{handleFastModeOverageRejection as h,handleFastModeRejectedByAPI as y,isFastModeCooldown as R,isFastModeEnabled as k,triggerFastModeCooldown as C}from"../../utils/fastMode.js";import{isNonCustomOpusModel as T}from"../../utils/model/model.js";import{disableKeepAlive as x}from"../../utils/proxy.js";import{sleep as v}from"../../utils/sleep.js";import{getFeatureValue_CACHED_MAY_BE_STALE as M}from"../analytics/growthbook.js";import{logEvent as w}from"../analytics/index.js";import{checkMockRateLimitError as b,isMockRateLimitError as A}from"../rateLimitMocking.js";import{REPEATED_529_ERROR_MESSAGE as O}from"./errors.js";import{extractConnectionErrorDetails as D}from"./errorUtils.js";const abortError=()=>new n,N=3e3;export const BASE_DELAY_MS=500;const S=new Set(["repl_main_thread","repl_main_thread:outputStyle:custom","repl_main_thread:outputStyle:Explanatory","repl_main_thread:outputStyle:Learning","sdk","agent:custom","agent:default","agent:builtin","compact","hook_agent","hook_prompt","verification_agent","side_question","auto_mode",...e("BASH_CLASSIFIER")?["bash_classifier"]:[]]);function shouldRetry529(e){return void 0===e||S.has(e)}const j=3e5,L=216e5;function isPersistentRetryEnabled(){return!!e("UNATTENDED_RETRY")&&(_(process.env.CONTEXT_CODE_UNATTENDED_RETRY)||_(process.env.CLAUDE_CODE_UNATTENDED_RETRY))}function isTransientCapacityError(e){return is529Error(e)||e instanceof r&&429===e.status}function isStaleConnectionError(e){if(!(e instanceof t))return!1;const r=D(e);return"ECONNRESET"===r?.code||"EPIPE"===r?.code}export class CannotRetryError extends Error{originalError;retryContext;constructor(e,t){super(g(e)),this.originalError=e,this.retryContext=t,this.name="RetryError",e instanceof Error&&e.stack&&(this.stack=e.stack)}}export class FallbackTriggeredError extends Error{originalModel;fallbackModel;constructor(e,t){super(`Model fallback triggered: ${e} -> ${t}`),this.originalModel=e,this.fallbackModel=t,this.name="FallbackTriggeredError"}}export async function*withRetry(e,t,o){const l=function(e){return e.maxRetries??getDefaultMaxRetries()}(o),c={model:o.model,thinkingConfig:o.thinkingConfig,...k()&&{fastMode:o.fastMode}};let f,p=null,_=o.initialConsecutive529Errors??0,A=0;for(let D=1;D<=l+1;D++){if(o.signal?.aborted)throw new n;const S=!!k()&&(c.fastMode&&!R());try{if("ant"===process.env.USER_TYPE){const e=b(c.model,S);if(e)throw e}const n=isStaleConnectionError(f);if(n&&M("tengu_disable_keepalive_on_econnreset",!1)&&(s("Stale connection (ECONNRESET/EPIPE) — disabling keep-alive for retry"),x()),null===p||f instanceof r&&401===f.status||isOAuthTokenRevokedError(f)||isBedrockAuthError(f)||isVertexAuthError(f)||n){if(f instanceof r&&401===f.status||isOAuthTokenRevokedError(f)){const e=d()?.accessToken;e&&await E(e)}p=await e()}return await t(p,D,c)}catch(e){if(f=e,s(`API error (attempt ${D}/${l+1}): ${e instanceof r?`${e.status} ${e.message}`:g(e)}`,{level:"error"}),S&&!isPersistentRetryEnabled()&&e instanceof r&&(429===e.status||is529Error(e))){const t=e.headers?.get("anthropic-ratelimit-unified-overage-disabled-reason");if(null!=t){h(t),c.fastMode=!1;continue}const r=getRetryAfterMs(e);if(null!==r&&r<P){await v(r,o.signal,{abortError});continue}const n=Math.max(r??U,I),s=is529Error(e)?"overloaded":"rate_limit";C(Date.now()+n,s),k()&&(c.fastMode=!1);continue}if(S&&isFastModeNotEnabledError(e)){y(),c.fastMode=!1;continue}if(is529Error(e)&&!shouldRetry529(o.querySource))throw w("tengu_api_529_background_dropped",{query_source:o.querySource}),new CannotRetryError(e,c);if(is529Error(e)&&(process.env.FALLBACK_FOR_ALL_PRIMARY_MODELS||!m()&&T(o.model))&&(_++,_>=3)){if(o.fallbackModel)throw w("tengu_api_opus_fallback_triggered",{original_model:o.model,fallback_model:o.fallbackModel,provider:u()}),new FallbackTriggeredError(o.model,o.fallbackModel);if("external"===process.env.USER_TYPE&&!process.env.IS_SANDBOX&&!isPersistentRetryEnabled())throw w("tengu_api_custom_529_overloaded_error",{}),new CannotRetryError(new Error(O),c)}const t=isPersistentRetryEnabled()&&isTransientCapacityError(e);if(D>l&&!t)throw new CannotRetryError(e,c);if(!(handleAwsCredentialError(e)||handleGcpCredentialError(e)||e instanceof r&&shouldRetry(e)))throw new CannotRetryError(e,c);if(e instanceof r){const t=parseMaxTokensContextOverflowError(e);if(t){const{inputTokens:r,contextLimit:n}=t,o=1e3,s=Math.max(0,n-r-o);if(s<N)throw i(new Error(`availableContext ${s} is less than FLOOR_OUTPUT_TOKENS 3000`)),e;const a=("enabled"===c.thinkingConfig.type?c.thinkingConfig.budgetTokens:0)+1,u=Math.max(N,s,a);c.maxTokensOverride=u,w("tengu_max_tokens_context_overflow_adjustment",{inputTokens:r,contextLimit:n,adjustedMaxTokens:u,attempt:D});continue}}const d=getRetryAfter(e);let E;if(t&&e instanceof r&&429===e.status){A++;E=getRateLimitResetDelayMs(e)??Math.min(getRetryDelay(A,d,j),L)}else t?(A++,E=Math.min(getRetryDelay(A,d,j),L)):E=getRetryDelay(D,d);const p=t?A:D;if(w("tengu_api_retry",{attempt:p,delayMs:E,error:e.message,status:e.status,provider:u()}),t){E>6e4&&w("tengu_api_persistent_retry_wait",{status:e.status,delayMs:E,attempt:p,provider:u()});let t=E;for(;t>0;){if(o.signal?.aborted)throw new n;e instanceof r&&(yield a(e,t,p,l));const s=Math.min(t,3e4);await v(s,o.signal,{abortError}),t-=s}D>=l&&(D=l)}else e instanceof r&&(yield a(e,E,D,l)),await v(E,o.signal,{abortError})}}throw new CannotRetryError(f,c)}function getRetryAfter(e){return(e.headers?.["retry-after"]||e.headers?.get?.("retry-after"))??null}export function getRetryDelay(e,t,r=32e3){if(t){const e=parseInt(t,10);if(!isNaN(e))return 1e3*e}const n=Math.min(500*Math.pow(2,e-1),r);return n+.25*Math.random()*n}export function parseMaxTokensContextOverflowError(e){if(400!==e.status||!e.message)return;if(!e.message.includes("input length and `max_tokens` exceed context limit"))return;const t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t||4!==t.length)return;if(!t[1]||!t[2]||!t[3])return void i(new Error("Unable to parse max_tokens from max_tokens exceed context limit error message"));const r=parseInt(t[1],10),n=parseInt(t[2],10),o=parseInt(t[3],10);return isNaN(r)||isNaN(n)||isNaN(o)?void 0:{inputTokens:r,maxTokens:n,contextLimit:o}}function isFastModeNotEnabledError(e){return e instanceof r&&(400===e.status&&(e.message?.includes("Fast mode is not enabled")??!1))}export function is529Error(e){return e instanceof r&&(529===e.status||(e.message?.includes('"type":"overloaded_error"')??!1))}function isOAuthTokenRevokedError(e){return e instanceof r&&403===e.status&&(e.message?.includes("OAuth token has been revoked")??!1)}function isBedrockAuthError(e){return!(!_(process.env.CONTEXT_CODE_USE_BEDROCK)&&!_(process.env.CLAUDE_CODE_USE_BEDROCK)||!(o(e)||e instanceof r&&403===e.status))}function handleAwsCredentialError(e){return!!isBedrockAuthError(e)&&(c(),!0)}function isVertexAuthError(e){if(_(process.env.CONTEXT_CODE_USE_VERTEX)||_(process.env.CLAUDE_CODE_USE_VERTEX)){if(function(e){if(!(e instanceof Error))return!1;const t=e.message;return t.includes("Could not load the default credentials")||t.includes("Could not refresh access token")||t.includes("invalid_grant")}(e))return!0;if(e instanceof r&&401===e.status)return!0}return!1}function handleGcpCredentialError(e){return!!isVertexAuthError(e)&&(f(),!0)}function shouldRetry(e){if(A(e))return!1;if(isPersistentRetryEnabled()&&isTransientCapacityError(e))return!0;if((_(process.env.CONTEXT_CODE_REMOTE)||_(process.env.CLAUDE_CODE_REMOTE))&&(401===e.status||403===e.status))return!0;if(e.message?.includes('"type":"overloaded_error"'))return!0;if(parseMaxTokensContextOverflowError(e))return!0;if(function(e){if(!(e instanceof r))return!1;const t=e.message?.toLowerCase()??"";return t.includes("insufficient balance")||t.includes("(1008)")}(e))return!1;const n=e.headers?.get("x-should-retry");if("true"===n&&(!m()||p()))return!0;if("false"===n){const t=void 0!==e.status&&e.status>=500;if("ant"!==process.env.USER_TYPE||!t)return!1}return e instanceof t||!!e.status&&(408===e.status||(409===e.status||(429===e.status?!m()||p():401===e.status?(l(),!0):!!isOAuthTokenRevokedError(e)||!!(e.status&&e.status>=500))))}export function getDefaultMaxRetries(){const e=process.env.CONTEXT_CODE_MAX_RETRIES;return e?parseInt(e,10):10}const U=18e5,P=2e4,I=6e5;function getRetryAfterMs(e){const t=getRetryAfter(e);if(t){const e=parseInt(t,10);if(!isNaN(e))return 1e3*e}return null}function getRateLimitResetDelayMs(e){const t=e.headers?.get?.("anthropic-ratelimit-unified-reset");if(!t)return null;const r=Number(t);if(!Number.isFinite(r))return null;const n=1e3*r-Date.now();return n<=0?null:Math.min(n,L)}
@@ -1 +1 @@
1
- import{mkdir as t,readFile as i,stat as o,unlink as s,utimes as a,writeFile as r}from"fs/promises";import{join as e}from"path";import{getOriginalCwd as n}from"../../bootstrap/state.js";import{getAutoMemPath as c}from"../../memdir/paths.js";import{logForDebugging as l}from"../../utils/debug.js";import{isProcessRunning as m}from"../../utils/genericProcessUtils.js";import{listCandidates as u}from"../../utils/listSessionsImpl.js";import{getProjectDir as d}from"../../utils/sessionStorage.js";function lockPath(){return e(c(),".consolidate-lock")}export async function readLastConsolidatedAt(){try{return(await o(lockPath())).mtimeMs}catch{return 0}}export async function tryAcquireConsolidationLock(){const s=lockPath();let a,e,n;try{const[t,r]=await Promise.all([o(s),i(s,"utf8")]);a=t.mtimeMs;const n=parseInt(r.trim(),10);e=Number.isFinite(n)?n:void 0}catch{}if(void 0!==a&&Date.now()-a<36e5&&void 0!==e&&m(e))return l(`[autoDream] lock held by live PID ${e} (mtime ${Math.round((Date.now()-a)/1e3)}s ago)`),null;await t(c(),{recursive:!0}),await r(s,String(process.pid));try{n=await i(s,"utf8")}catch{return null}return parseInt(n.trim(),10)!==process.pid?null:a??0}export async function rollbackConsolidationLock(t){const i=lockPath();try{if(0===t)return void await s(i);await r(i,"");const o=t/1e3;await a(i,o,o)}catch(t){l(`[autoDream] rollback failed: ${t.message} — next trigger delayed to minHours`)}}export async function listSessionsTouchedSince(t){const i=d(n());return(await u(i,!0)).filter(i=>i.mtime>t).map(t=>t.sessionId)}export async function recordConsolidation(){try{await t(c(),{recursive:!0}),await r(lockPath(),String(process.pid))}catch(t){l(`[autoDream] recordConsolidation write failed: ${t.message}`)}}
1
+ import{mkdir as t,readFile as o,stat as i,unlink as r,utimes as e,writeFile as a}from"fs/promises";import{join as s}from"path";import{getOriginalCwd as n}from"../../bootstrap/state.js";import{getAutoMemPath as c}from"../../memdir/paths.js";import{logForDebugging as l}from"../../utils/debug.js";import{isProcessRunning as m}from"../../utils/genericProcessUtils.js";import{listCandidates as u}from"../../utils/listSessionsImpl.js";import{getProjectDir as d}from"../../utils/sessionStorage.js";function lockPath(){return s(c(),".consolidate-lock")}export async function readLastConsolidatedAt(){try{return(await i(lockPath())).mtimeMs}catch{return 0}}export async function tryAcquireConsolidationLock(){const r=lockPath();let e,s,n;try{const[t,a]=await Promise.all([i(r),o(r,"utf8")]);e=t.mtimeMs;const n=parseInt(a.trim(),10);s=Number.isFinite(n)?n:void 0}catch{}if(void 0!==e&&Date.now()-e<36e5&&void 0!==s&&m(s))return l(`[autoDream] lock held by live PID ${s} (mtime ${Math.round((Date.now()-e)/1e3)}s ago)`),null;await t(c(),{recursive:!0}),await a(r,String(process.pid));try{n=await o(r,"utf8")}catch{return null}return parseInt(n.trim(),10)!==process.pid?null:e??0}export async function rollbackConsolidationLock(t){const o=lockPath();try{if(0===t)return void await r(o);await a(o,"");const i=t/1e3;await e(o,i,i)}catch(t){l(`[autoDream] rollback failed: ${t.message} — next trigger delayed to minHours`)}}export async function listSessionsTouchedSince(t){const o=d(n());return(await u(o,!0)).filter(o=>o.mtime>t).map(t=>t.sessionId)}export async function recordConsolidation(){try{await t(c(),{recursive:!0}),await a(lockPath(),String(process.pid))}catch(t){l(`[autoDream] recordConsolidation write failed: ${t.message}`)}}
@@ -1 +1 @@
1
- import{ElicitationCompleteNotificationSchema as i,ElicitRequestSchema as t}from"@modelcontextprotocol/sdk/types.js";import{executeElicitationHooks as e,executeElicitationResultHooks as o,executeNotificationHooks as n}from"../../utils/hooks.js";import{logMCPDebug as a,logMCPError as r}from"../../utils/log.js";import{jsonStringify as c}from"../../utils/slowOperations.js";import{logEvent as s}from"../analytics/index.js";export function registerElicitationHandler(e,o,l){try{e.setRequestHandler(t,async(i,t)=>{a(o,`Received elicitation request: ${c(i)}`);const e="url"===i.params.mode?"url":"form";s("tengu_mcp_elicitation_shown",{mode:e});try{const n=await runElicitationHooks(o,i.params,t.signal);if(n)return a(o,`Elicitation resolved by hook: ${c(n)}`),s("tengu_mcp_elicitation_response",{mode:e,action:n.action}),n;const r="url"===e&&"elicitationId"in i.params?i.params.elicitationId:void 0,u=new Promise(n=>{const onAbort=()=>{n({action:"cancel"})};if(t.signal.aborted)return void onAbort();const a=r?{actionLabel:"Skip confirmation"}:void 0;l(r=>({...r,elicitation:{queue:[...r.elicitation.queue,{serverName:o,requestId:t.requestId,params:i.params,signal:t.signal,waitingState:a,respond:i=>{t.signal.removeEventListener("abort",onAbort),s("tengu_mcp_elicitation_response",{mode:e,action:i.action}),n(i)}}]}})),t.signal.addEventListener("abort",onAbort,{once:!0})}),m=await u;return a(o,`Elicitation response: ${c(m)}`),await runElicitationResultHooks(o,m,t.signal,e,r)}catch(i){return r(o,`Elicitation error: ${i}`),{action:"cancel"}}}),e.setNotificationHandler(i,i=>{const{elicitationId:t}=i.params;a(o,`Received elicitation completion notification: ${t}`),n({message:`MCP server "${o}" confirmed elicitation ${t} complete`,notificationType:"elicitation_complete"});let e=!1;l(i=>{const n=function(i,t,e){return i.findIndex(i=>i.serverName===t&&"url"===i.params.mode&&"elicitationId"in i.params&&i.params.elicitationId===e)}(i.elicitation.queue,o,t);if(-1===n)return i;e=!0;const a=[...i.elicitation.queue];return a[n]={...a[n],completed:!0},{...i,elicitation:{queue:a}}}),e||a(o,`Ignoring completion notification for unknown elicitation: ${t}`)})}catch{return}}export async function runElicitationHooks(i,t,o){try{const n="url"===t.mode?"url":"form",a="url"in t?t.url:void 0,r="elicitationId"in t?t.elicitationId:void 0,{elicitationResponse:c,blockingError:s}=await e({serverName:i,message:t.message,requestedSchema:"requestedSchema"in t?t.requestedSchema:void 0,signal:o,mode:n,url:a,elicitationId:r});return s?{action:"decline"}:c?{action:c.action,content:c.content}:void 0}catch(t){return void r(i,`Elicitation hook error: ${t}`)}}export async function runElicitationResultHooks(i,t,e,a,c){try{const{elicitationResultResponse:r,blockingError:s}=await o({serverName:i,action:t.action,content:t.content,signal:e,mode:a,elicitationId:c});if(s)return n({message:`Elicitation response for server "${i}": decline`,notificationType:"elicitation_response"}),{action:"decline"};const l=r?{action:r.action,content:r.content??t.content}:t;return n({message:`Elicitation response for server "${i}": ${l.action}`,notificationType:"elicitation_response"}),l}catch(e){return r(i,`ElicitationResult hook error: ${e}`),n({message:`Elicitation response for server "${i}": ${t.action}`,notificationType:"elicitation_response"}),t}}
1
+ import{ElicitationCompleteNotificationSchema as i,ElicitRequestSchema as t}from"@modelcontextprotocol/sdk/types.js";import{executeElicitationHooks as e,executeElicitationResultHooks as o,executeNotificationHooks as n}from"../../utils/hooks.js";import{logMCPDebug as a,logMCPError as r}from"../../utils/log.js";import{jsonStringify as c}from"../../utils/slowOperations.js";import{logEvent as s}from"../analytics/index.js";export function registerElicitationHandler(e,o,l){try{e.setRequestHandler(t,async(i,t)=>{a(o,`Received elicitation request: ${c(i)}`);const e="url"===i.params.mode?"url":"form";s("tengu_mcp_elicitation_shown",{mode:e});try{const n=await runElicitationHooks(o,i.params,t.signal);if(n)return a(o,`Elicitation resolved by hook: ${c(n)}`),s("tengu_mcp_elicitation_response",{mode:e,action:n.action}),n;const r="url"===e&&"elicitationId"in i.params?i.params.elicitationId:void 0,u=new Promise(n=>{const onAbort=()=>{n({action:"cancel"})};if(t.signal.aborted)return void onAbort();const a=r?{actionLabel:"Skip confirmation"}:void 0;l(r=>({...r,elicitation:{queue:[...r.elicitation.queue,{serverName:o,requestId:t.requestId,params:i.params,signal:t.signal,waitingState:a,respond:i=>{t.signal.removeEventListener("abort",onAbort),s("tengu_mcp_elicitation_response",{mode:e,action:i.action}),n(i)}}]}})),t.signal.addEventListener("abort",onAbort,{once:!0})}),m=await u;a(o,`Elicitation response: ${c(m)}`);return await runElicitationResultHooks(o,m,t.signal,e,r)}catch(i){return r(o,`Elicitation error: ${i}`),{action:"cancel"}}}),e.setNotificationHandler(i,i=>{const{elicitationId:t}=i.params;a(o,`Received elicitation completion notification: ${t}`),n({message:`MCP server "${o}" confirmed elicitation ${t} complete`,notificationType:"elicitation_complete"});let e=!1;l(i=>{const n=function(i,t,e){return i.findIndex(i=>i.serverName===t&&"url"===i.params.mode&&"elicitationId"in i.params&&i.params.elicitationId===e)}(i.elicitation.queue,o,t);if(-1===n)return i;e=!0;const a=[...i.elicitation.queue];return a[n]={...a[n],completed:!0},{...i,elicitation:{queue:a}}}),e||a(o,`Ignoring completion notification for unknown elicitation: ${t}`)})}catch{return}}export async function runElicitationHooks(i,t,o){try{const n="url"===t.mode?"url":"form",a="url"in t?t.url:void 0,r="elicitationId"in t?t.elicitationId:void 0,{elicitationResponse:c,blockingError:s}=await e({serverName:i,message:t.message,requestedSchema:"requestedSchema"in t?t.requestedSchema:void 0,signal:o,mode:n,url:a,elicitationId:r});return s?{action:"decline"}:c?{action:c.action,content:c.content}:void 0}catch(t){return void r(i,`Elicitation hook error: ${t}`)}}export async function runElicitationResultHooks(i,t,e,a,c){try{const{elicitationResultResponse:r,blockingError:s}=await o({serverName:i,action:t.action,content:t.content,signal:e,mode:a,elicitationId:c});if(s)return n({message:`Elicitation response for server "${i}": decline`,notificationType:"elicitation_response"}),{action:"decline"};const l=r?{action:r.action,content:r.content??t.content}:t;return n({message:`Elicitation response for server "${i}": ${l.action}`,notificationType:"elicitation_response"}),l}catch(e){return r(i,`ElicitationResult hook error: ${e}`),n({message:`Elicitation response for server "${i}": ${t.action}`,notificationType:"elicitation_response"}),t}}
@@ -1 +1 @@
1
- import{normalizeNameForMCP as e}from"./normalization.js";export function mcpInfoFromString(e){const o=e.split("__"),[r,t,...n]=o;return"mcp"===r&&t?{serverName:t,toolName:n.length>0?n.join("__"):void 0}:null}export function getMcpPrefix(o){return`mcp__${e(o)}__`}export function buildMcpToolName(o,r){return`${getMcpPrefix(o)}${e(r)}`}export function getToolNameForPermissionCheck(e){return e.mcpInfo?buildMcpToolName(e.mcpInfo.serverName,e.mcpInfo.toolName):e.name}export function getMcpDisplayName(o,r){const t=`mcp__${e(r)}__`;return o.replace(t,"")}export function extractMcpToolDisplayName(e){let o=e.replace(/\s*\(MCP\)\s*$/,"");o=o.trim();const r=o.indexOf(" - ");return-1!==r?o.substring(r+3).trim():o}
1
+ import{normalizeNameForMCP as e}from"./normalization.js";export function mcpInfoFromString(e){const r=e.split("__"),[o,t,...n]=r;if("mcp"!==o||!t)return null;return{serverName:t,toolName:n.length>0?n.join("__"):void 0}}export function getMcpPrefix(r){return`mcp__${e(r)}__`}export function buildMcpToolName(r,o){return`${getMcpPrefix(r)}${e(o)}`}export function getToolNameForPermissionCheck(e){return e.mcpInfo?buildMcpToolName(e.mcpInfo.serverName,e.mcpInfo.toolName):e.name}export function getMcpDisplayName(r,o){const t=`mcp__${e(o)}__`;return r.replace(t,"")}export function extractMcpToolDisplayName(e){let r=e.replace(/\s*\(MCP\)\s*$/,"");r=r.trim();const o=r.indexOf(" - ");if(-1!==o){return r.substring(o+3).trim()}return r}
@@ -1 +1 @@
1
- import{createServer as t}from"http";import{getPlatform as r}from"../../utils/platform.js";const o="windows"===r()?{min:39152,max:49151}:{min:49152,max:65535};export function buildRedirectUri(t=3118){return`http://localhost:${t}/callback`}export async function findAvailablePort(){const r=function(){const t=parseInt(process.env.MCP_OAUTH_CALLBACK_PORT||"",10);return t>0?t:void 0}();if(r)return r;const{min:n,max:e}=o,a=e-n+1,c=Math.min(a,100);for(let r=0;r<c;r++){const r=n+Math.floor(Math.random()*a);try{return await new Promise((o,n)=>{const e=t();e.once("error",n),e.listen(r,()=>{e.close(()=>o())})}),r}catch{continue}}try{return await new Promise((r,o)=>{const n=t();n.once("error",o),n.listen(3118,()=>{n.close(()=>r())})}),3118}catch{throw new Error("No available ports for OAuth redirect")}}
1
+ import{createServer as t}from"http";import{getPlatform as r}from"../../utils/platform.js";const o="windows"===r()?{min:39152,max:49151}:{min:49152,max:65535},n=3118;export function buildRedirectUri(t=3118){return`http://localhost:${t}/callback`}export async function findAvailablePort(){const r=function(){const t=parseInt(process.env.MCP_OAUTH_CALLBACK_PORT||"",10);return t>0?t:void 0}();if(r)return r;const{min:e,max:i}=o,c=i-e+1,a=Math.min(c,100);for(let r=0;r<a;r++){const r=e+Math.floor(Math.random()*c);try{return await new Promise((o,n)=>{const e=t();e.once("error",n),e.listen(r,()=>{e.close(()=>o())})}),r}catch{continue}}try{return await new Promise((r,o)=>{const e=t();e.once("error",o),e.listen(n,()=>{e.close(()=>r())})}),n}catch{throw new Error("No available ports for OAuth redirect")}}
@@ -1 +1 @@
1
- import{logForDebugging as e}from"src/utils/debug.js";import{z as t}from"zod/v4";import{lazySchema as o}from"../../utils/lazySchema.js";import{checkStatsigFeatureGate_CACHED_MAY_BE_STALE as n,getFeatureValue_CACHED_MAY_BE_STALE as a}from"../analytics/growthbook.js";import{logEvent as i}from"../analytics/index.js";export const LogEventNotificationSchema=o(()=>t.object({method:t.literal("log_event"),params:t.object({eventName:t.string(),eventData:t.object({}).passthrough()})}));let c=null;export function notifyVscodeFileUpdated(t,o,n){"ant"===process.env.USER_TYPE&&c&&c.client.notification({method:"file_updated",params:{filePath:t,oldContent:o,newContent:n}}).catch(t=>{e(`[VSCode] Failed to send file_updated notification: ${t.message}`)})}export function setupVscodeSdkMcp(e){const t=e.find(e=>"claude-vscode"===e.name);if(t&&"connected"===t.type){c=t,t.client.setNotificationHandler(LogEventNotificationSchema(),async e=>{const{eventName:t,eventData:o}=e.params;i(`tengu_vscode_${t}`,o)});const e={tengu_vscode_review_upsell:n("tengu_vscode_review_upsell"),tengu_vscode_onboarding:n("tengu_vscode_onboarding"),tengu_quiet_fern:a("tengu_quiet_fern",!1),tengu_vscode_cc_auth:a("tengu_vscode_cc_auth",!1)},o=function(){const e=a("tengu_auto_mode_config",{})?.enabled;return"enabled"===e||"disabled"===e||"opt-in"===e?e:void 0}();void 0!==o&&(e.tengu_auto_mode_state=o),t.client.notification({method:"experiment_gates",params:{gates:e}})}}
1
+ import{logForDebugging as e}from"../../utils/debug.js";import{z as t}from"zod/v4";import{lazySchema as o}from"../../utils/lazySchema.js";import{checkStatsigFeatureGate_CACHED_MAY_BE_STALE as n,getFeatureValue_CACHED_MAY_BE_STALE as i}from"../analytics/growthbook.js";import{logEvent as a}from"../analytics/index.js";export const LogEventNotificationSchema=o(()=>t.object({method:t.literal("log_event"),params:t.object({eventName:t.string(),eventData:t.object({}).passthrough()})}));let c=null;export function notifyVscodeFileUpdated(t,o,n){"ant"===process.env.USER_TYPE&&c&&c.client.notification({method:"file_updated",params:{filePath:t,oldContent:o,newContent:n}}).catch(t=>{e(`[VSCode] Failed to send file_updated notification: ${t.message}`)})}export function setupVscodeSdkMcp(e){const t=e.find(e=>"claude-vscode"===e.name);if(t&&"connected"===t.type){c=t,t.client.setNotificationHandler(LogEventNotificationSchema(),async e=>{const{eventName:t,eventData:o}=e.params;a(`tengu_vscode_${t}`,o)});const e={tengu_vscode_review_upsell:n("tengu_vscode_review_upsell"),tengu_vscode_onboarding:n("tengu_vscode_onboarding"),tengu_quiet_fern:i("tengu_quiet_fern",!1),tengu_vscode_cc_auth:i("tengu_vscode_cc_auth",!1)},o=function(){const e=i("tengu_auto_mode_config",{})?.enabled;return"enabled"===e||"disabled"===e||"opt-in"===e?e:void 0}();void 0!==o&&(e.tengu_auto_mode_state=o),t.client.notification({method:"experiment_gates",params:{gates:e}})}}