@iaforged/context-code 2.1.6 → 2.1.7

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 (409) hide show
  1. package/dist/src/Task.js +1 -1
  2. package/dist/src/commands/add-dir/add-dir.js +1 -1
  3. package/dist/src/commands/add-dir/validation.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/providerModels.js +1 -1
  222. package/dist/src/utils/model/providerProfiles.js +1 -1
  223. package/dist/src/utils/model/providerProfilesDb.js +1 -1
  224. package/dist/src/utils/model/providerSwitch.js +1 -1
  225. package/dist/src/utils/model/providers.js +1 -1
  226. package/dist/src/utils/modelCost.js +1 -1
  227. package/dist/src/utils/modifiers.js +1 -1
  228. package/dist/src/utils/mtls.js +1 -1
  229. package/dist/src/utils/nativeInstaller/download.js +1 -1
  230. package/dist/src/utils/nativeInstaller/installer.js +1 -1
  231. package/dist/src/utils/nativeInstaller/packageManagers.js +1 -1
  232. package/dist/src/utils/nativeInstaller/pidLock.js +1 -1
  233. package/dist/src/utils/notebook.js +1 -1
  234. package/dist/src/utils/pasteStore.js +1 -1
  235. package/dist/src/utils/path.js +1 -1
  236. package/dist/src/utils/permissions/PermissionMode.js +1 -1
  237. package/dist/src/utils/permissions/PermissionPromptToolResultSchema.js +1 -1
  238. package/dist/src/utils/permissions/PermissionUpdate.js +1 -1
  239. package/dist/src/utils/permissions/PermissionUpdateSchema.js +1 -1
  240. package/dist/src/utils/permissions/autoModeState.js +1 -1
  241. package/dist/src/utils/permissions/bypassPermissionsKillswitch.js +1 -1
  242. package/dist/src/utils/permissions/filesystem.js +1 -1
  243. package/dist/src/utils/permissions/getNextPermissionMode.js +1 -1
  244. package/dist/src/utils/permissions/pathValidation.js +1 -1
  245. package/dist/src/utils/permissions/permissionRuleParser.js +1 -1
  246. package/dist/src/utils/permissions/permissionsDb.js +1 -1
  247. package/dist/src/utils/permissions/permissionsLoader.js +1 -1
  248. package/dist/src/utils/permissions/shellRuleMatching.js +1 -1
  249. package/dist/src/utils/planModeV2.js +1 -1
  250. package/dist/src/utils/plans.js +1 -1
  251. package/dist/src/utils/platform.js +1 -1
  252. package/dist/src/utils/plugins/addDirPluginSettings.js +1 -1
  253. package/dist/src/utils/plugins/cacheUtils.js +1 -1
  254. package/dist/src/utils/plugins/dependencyResolver.js +1 -1
  255. package/dist/src/utils/plugins/fetchTelemetry.js +1 -1
  256. package/dist/src/utils/plugins/gitAvailability.js +1 -1
  257. package/dist/src/utils/plugins/hintRecommendation.js +1 -1
  258. package/dist/src/utils/plugins/installedPluginsManager.js +1 -1
  259. package/dist/src/utils/plugins/loadPluginAgents.js +1 -1
  260. package/dist/src/utils/plugins/loadPluginCommands.js +1 -1
  261. package/dist/src/utils/plugins/loadPluginHooks.js +1 -1
  262. package/dist/src/utils/plugins/loadPluginOutputStyles.js +1 -1
  263. package/dist/src/utils/plugins/lspPluginIntegration.js +1 -1
  264. package/dist/src/utils/plugins/lspRecommendation.js +1 -1
  265. package/dist/src/utils/plugins/managedPlugins.js +1 -1
  266. package/dist/src/utils/plugins/marketplaceHelpers.js +1 -1
  267. package/dist/src/utils/plugins/marketplaceManager.js +1 -1
  268. package/dist/src/utils/plugins/mcpPluginIntegration.js +1 -1
  269. package/dist/src/utils/plugins/mcpbHandler.js +1 -1
  270. package/dist/src/utils/plugins/officialMarketplaceGcs.js +1 -1
  271. package/dist/src/utils/plugins/officialMarketplaceStartupCheck.js +1 -1
  272. package/dist/src/utils/plugins/orphanedPluginFilter.js +1 -1
  273. package/dist/src/utils/plugins/performStartupChecks.js +1 -1
  274. package/dist/src/utils/plugins/pluginAutoupdate.js +1 -1
  275. package/dist/src/utils/plugins/pluginBlocklist.js +1 -1
  276. package/dist/src/utils/plugins/pluginDirectories.js +1 -1
  277. package/dist/src/utils/plugins/pluginFlagging.js +1 -1
  278. package/dist/src/utils/plugins/pluginInstallationHelpers.js +1 -1
  279. package/dist/src/utils/plugins/pluginLoader.js +1 -1
  280. package/dist/src/utils/plugins/pluginOptionsStorage.js +1 -1
  281. package/dist/src/utils/plugins/pluginPolicy.js +1 -1
  282. package/dist/src/utils/plugins/pluginStartupCheck.js +1 -1
  283. package/dist/src/utils/plugins/pluginVersioning.js +1 -1
  284. package/dist/src/utils/plugins/reconciler.js +1 -1
  285. package/dist/src/utils/plugins/refresh.js +1 -1
  286. package/dist/src/utils/plugins/schemas.js +1 -1
  287. package/dist/src/utils/plugins/walkPluginMarkdown.js +1 -1
  288. package/dist/src/utils/plugins/zipCache.js +1 -1
  289. package/dist/src/utils/powershell/parser.js +1 -1
  290. package/dist/src/utils/processUserInput/processBashCommand.js +1 -1
  291. package/dist/src/utils/processUserInput/processSlashCommand.js +1 -1
  292. package/dist/src/utils/processUserInput/processTextPrompt.js +1 -1
  293. package/dist/src/utils/processUserInput/processUserInput.js +1 -1
  294. package/dist/src/utils/profilerBase.js +1 -1
  295. package/dist/src/utils/promptCategory.js +1 -1
  296. package/dist/src/utils/promptEditor.js +1 -1
  297. package/dist/src/utils/promptShellExecution.js +1 -1
  298. package/dist/src/utils/proxy.js +1 -1
  299. package/dist/src/utils/queryHelpers.js +1 -1
  300. package/dist/src/utils/queryProfiler.js +1 -1
  301. package/dist/src/utils/queueProcessor.js +1 -1
  302. package/dist/src/utils/readFileInRange.js +1 -1
  303. package/dist/src/utils/releaseNotes.js +1 -1
  304. package/dist/src/utils/renderOptions.js +1 -1
  305. package/dist/src/utils/ripgrep.js +1 -1
  306. package/dist/src/utils/sandbox/sandbox-adapter.js +1 -1
  307. package/dist/src/utils/sdkEventQueue.js +1 -1
  308. package/dist/src/utils/secureStorage/index.js +1 -1
  309. package/dist/src/utils/secureStorage/macOsKeychainHelpers.js +1 -1
  310. package/dist/src/utils/secureStorage/macOsKeychainStorage.js +1 -1
  311. package/dist/src/utils/secureStorage/plainTextStorage.js +1 -1
  312. package/dist/src/utils/secureStorage/sqliteStorage.js +1 -1
  313. package/dist/src/utils/sessionEnvironment.js +1 -1
  314. package/dist/src/utils/sessionIngressAuth.js +1 -1
  315. package/dist/src/utils/sessionRestore.js +1 -1
  316. package/dist/src/utils/sessionStart.js +1 -1
  317. package/dist/src/utils/sessionTitle.js +1 -1
  318. package/dist/src/utils/settings/managedPath.js +1 -1
  319. package/dist/src/utils/settings/mdm/rawRead.js +1 -1
  320. package/dist/src/utils/settings/mdm/settings.js +1 -1
  321. package/dist/src/utils/settings/permissionValidation.js +1 -1
  322. package/dist/src/utils/settings/pluginOnlyPolicy.js +1 -1
  323. package/dist/src/utils/settings/schemaOutput.js +1 -1
  324. package/dist/src/utils/settings/settings.js +1 -1
  325. package/dist/src/utils/settings/types.js +1 -1
  326. package/dist/src/utils/settings/validateEditTool.js +1 -1
  327. package/dist/src/utils/settings/validation.js +1 -1
  328. package/dist/src/utils/shell/bashProvider.js +1 -1
  329. package/dist/src/utils/shell/powershellDetection.js +1 -1
  330. package/dist/src/utils/shell/powershellProvider.js +1 -1
  331. package/dist/src/utils/shell/readOnlyCommandValidation.js +1 -1
  332. package/dist/src/utils/shell/resolveDefaultShell.js +1 -1
  333. package/dist/src/utils/shell/shellToolUtils.js +1 -1
  334. package/dist/src/utils/shell/specPrefix.js +1 -1
  335. package/dist/src/utils/shellConfig.js +1 -1
  336. package/dist/src/utils/sideQuestion.js +1 -1
  337. package/dist/src/utils/skills/skillChangeDetector.js +1 -1
  338. package/dist/src/utils/slashCommandParsing.js +1 -1
  339. package/dist/src/utils/sliceAnsi.js +1 -1
  340. package/dist/src/utils/slowOperations.js +1 -1
  341. package/dist/src/utils/standaloneAgent.js +1 -1
  342. package/dist/src/utils/startupProfiler.js +1 -1
  343. package/dist/src/utils/staticRender.js +1 -1
  344. package/dist/src/utils/status.js +1 -1
  345. package/dist/src/utils/statusNoticeDefinitions.js +1 -1
  346. package/dist/src/utils/suggestions/commandSuggestions.js +1 -1
  347. package/dist/src/utils/suggestions/directoryCompletion.js +1 -1
  348. package/dist/src/utils/suggestions/shellHistoryCompletion.js +1 -1
  349. package/dist/src/utils/suggestions/skillUsageTracking.js +1 -1
  350. package/dist/src/utils/suggestions/slackChannelSuggestions.js +1 -1
  351. package/dist/src/utils/swarm/backends/detection.js +1 -1
  352. package/dist/src/utils/swarm/permissionSync.js +1 -1
  353. package/dist/src/utils/swarm/reconnection.js +1 -1
  354. package/dist/src/utils/swarm/spawnUtils.js +91 -1
  355. package/dist/src/utils/swarm/teammateInit.js +1 -1
  356. package/dist/src/utils/systemDirectories.js +1 -1
  357. package/dist/src/utils/systemPrompt.js +1 -1
  358. package/dist/src/utils/systemTheme.js +1 -1
  359. package/dist/src/utils/task/TaskOutput.js +1 -1
  360. package/dist/src/utils/task/diskOutput.js +1 -1
  361. package/dist/src/utils/tasks.js +1 -1
  362. package/dist/src/utils/teamDiscovery.js +1 -1
  363. package/dist/src/utils/teamMemoryOps.js +1 -1
  364. package/dist/src/utils/teammateMailbox.js +1 -1
  365. package/dist/src/utils/telemetry/betaSessionTracing.js +1 -1
  366. package/dist/src/utils/telemetry/bigqueryExporter.js +1 -1
  367. package/dist/src/utils/telemetry/events.js +1 -1
  368. package/dist/src/utils/telemetry/instrumentation.js +1 -1
  369. package/dist/src/utils/telemetry/logger.js +1 -1
  370. package/dist/src/utils/telemetry/perfettoTracing.js +1 -1
  371. package/dist/src/utils/telemetry/pluginTelemetry.js +1 -1
  372. package/dist/src/utils/telemetry/sessionTracing.js +1 -1
  373. package/dist/src/utils/telemetryAttributes.js +1 -1
  374. package/dist/src/utils/teleport/api.js +1 -1
  375. package/dist/src/utils/teleport/environments.js +1 -1
  376. package/dist/src/utils/teleport/gitBundle.js +1 -1
  377. package/dist/src/utils/teleport.js +1 -1
  378. package/dist/src/utils/tempfile.js +1 -1
  379. package/dist/src/utils/terminal.js +1 -1
  380. package/dist/src/utils/terminalPanel.js +1 -1
  381. package/dist/src/utils/textHighlighting.js +1 -1
  382. package/dist/src/utils/theme.js +1 -1
  383. package/dist/src/utils/themes/bootstrap.js +1 -1
  384. package/dist/src/utils/themes/loader.js +1 -1
  385. package/dist/src/utils/thinking.js +1 -1
  386. package/dist/src/utils/tmuxSocket.js +1 -1
  387. package/dist/src/utils/tokens.js +1 -1
  388. package/dist/src/utils/toolPool.js +1 -1
  389. package/dist/src/utils/toolResultStorage.js +1 -1
  390. package/dist/src/utils/transcriptSearch.js +1 -1
  391. package/dist/src/utils/truncate.js +1 -1
  392. package/dist/src/utils/ultraplan/keyword.js +1 -1
  393. package/dist/src/utils/unaryLogging.js +1 -1
  394. package/dist/src/utils/undercover.js +1 -1
  395. package/dist/src/utils/user.js +1 -1
  396. package/dist/src/utils/userPromptKeywords.js +1 -1
  397. package/dist/src/utils/which.js +1 -1
  398. package/dist/src/utils/windowsPaths.js +1 -1
  399. package/dist/src/utils/worktree.js +1 -1
  400. package/dist/src/utils/zodToJsonSchema.js +1 -1
  401. package/dist/src/vim/operators.js +1 -1
  402. package/dist/src/vim/textObjects.js +1 -1
  403. package/dist/src/vim/transitions.js +1 -1
  404. package/dist/src/voice/voiceModeEnabled.js +1 -1
  405. package/dist/src/webapp/auth.js +1 -1
  406. package/dist/src/webapp/tunnel.js +1 -1
  407. package/dist/src/whatsapp/bridge.js +1 -1
  408. package/dist/src/whatsapp/mirror.js +1 -1
  409. package/package.json +1 -1
@@ -1 +1 @@
1
- import{feature as e}from"../recovery/bunBundleShim.js";import{randomBytes as t}from"crypto";import{execa as i}from"execa";import{basename as a,extname as o,isAbsolute as r,join as s}from"path";import{IMAGE_MAX_HEIGHT as n,IMAGE_MAX_WIDTH as l,IMAGE_TARGET_RAW_SIZE as m}from"../constants/apiLimits.js";import{getFeatureValue_CACHED_MAY_BE_STALE as p}from"../services/analytics/growthbook.js";import{getImageProcessor as c}from"../tools/FileReadTool/imageProcessor.js";import{logForDebugging as g}from"./debug.js";import{execFileNoThrowWithCwd as d}from"./execFileNoThrow.js";import{getFsImplementation as h}from"./fsOperations.js";import{detectImageFormatFromBase64 as u,maybeResizeAndDownsampleImageBuffer as f}from"./imageResizer.js";import{logError as w}from"./log.js";export const PASTE_THRESHOLD=800;function getClipboardCommands(){const e=process.platform,t=process.env.CONTEXT_CODE_TMPDIR||process.env.CLAUDE_CODE_TMPDIR||("win32"===e?process.env.TEMP||"C:\\Temp":"/tmp"),i="claude_cli_latest_screenshot.png",a={darwin:s(t,i),linux:s(t,i),win32:s(t,i)},o=a[e]||a.linux,r=o.replace(/'/g,"''"),n={darwin:{checkImage:"osascript -e 'the clipboard as «class PNGf»'",saveImage:`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${o}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:"osascript -e 'get POSIX path of (the clipboard as «class furl»)'",deleteFile:`rm -f "${o}"`},linux:{checkImage:'xclip -selection clipboard -t TARGETS -o 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)" || wl-paste -l 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)"',saveImage:`xclip -selection clipboard -t image/png -o > "${o}" 2>/dev/null || wl-paste --type image/png > "${o}" 2>/dev/null || xclip -selection clipboard -t image/bmp -o > "${o}" 2>/dev/null || wl-paste --type image/bmp > "${o}"`,getPath:"xclip -selection clipboard -t text/plain -o 2>/dev/null || wl-paste 2>/dev/null",deleteFile:`rm -f "${o}"`},win32:{checkImage:'powershell -NoProfile -STA -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::ContainsImage()"',saveImage:`powershell -NoProfile -STA -Command "Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img -ne $null) { $img.Save('${r}', [System.Drawing.Imaging.ImageFormat]::Png) } else { exit 1 }"`,getPath:'powershell -NoProfile -Command "Get-Clipboard -Raw"',deleteFile:`powershell -NoProfile -Command "Remove-Item -LiteralPath '${r}' -Force -ErrorAction SilentlyContinue"`}};return{commands:n[e]||n.linux,screenshotPath:o}}export async function hasImageInClipboard(){if("darwin"!==process.platform){const{commands:e}=getClipboardCommands(),t=await i(e.checkImage,{shell:!0,reject:!1});return 0===t.exitCode&&"false"!==t.stdout.trim().toLowerCase()}if(e("NATIVE_CLIPBOARD_IMAGE")&&p("tengu_collage_kaleidoscope",!0))try{const{getNativeModule:e}=await import("image-processor-napi"),t=e()?.hasClipboardImage;if(t)return t()}catch(e){w(e)}return 0===(await d("osascript",["-e","the clipboard as «class PNGf»"])).code}export async function getImageFromClipboard(){if(e("NATIVE_CLIPBOARD_IMAGE")&&"darwin"===process.platform&&p("tengu_collage_kaleidoscope",!0))try{const{getNativeModule:e}=await import("image-processor-napi"),t=e()?.readClipboardImage;if(!t)throw new Error("native clipboard reader unavailable");const i=t(l,n);if(!i)return null;const a=i.png;if(a.length>m){const e=await f(a,a.length,"png");return{base64:e.buffer.toString("base64"),mediaType:`image/${e.mediaType}`,dimensions:{originalWidth:i.originalWidth,originalHeight:i.originalHeight,displayWidth:e.dimensions?.displayWidth??i.width,displayHeight:e.dimensions?.displayHeight??i.height}}}return{base64:a.toString("base64"),mediaType:"image/png",dimensions:{originalWidth:i.originalWidth,originalHeight:i.originalHeight,displayWidth:i.width,displayHeight:i.height}}}catch(e){w(e)}const{commands:t,screenshotPath:a}=getClipboardCommands();try{if(0!==(await i(t.checkImage,{shell:!0,reject:!1})).exitCode)return null;if(0!==(await i(t.saveImage,{shell:!0,reject:!1})).exitCode)return null;let e=h().readFileBytesSync(a);if(e.length>=2&&66===e[0]&&77===e[1]){const t=await c();e=await t(e).png().toBuffer()}const o=await f(e,e.length,"png"),r=o.buffer.toString("base64"),s=u(r);return i(t.deleteFile,{shell:!0,reject:!1}),{base64:r,mediaType:s,dimensions:o.dimensions}}catch{return null}}export async function getImagePathFromClipboard(){const{commands:e}=getClipboardCommands();try{const t=await i(e.getPath,{shell:!0,reject:!1});return 0===t.exitCode&&t.stdout?t.stdout.trim():null}catch(e){return w(e),null}}export const IMAGE_EXTENSION_REGEX=/\.(png|jpe?g|gif|webp)$/i;function removeOuterQuotes(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function stripBackslashEscapes(e){if("win32"===process.platform)return e;const i=`__DOUBLE_BACKSLASH_${t(8).toString("hex")}__`;return e.replace(/\\\\/g,i).replace(/\\(.)/g,"$1").replace(new RegExp(i,"g"),"\\")}export function isImageFilePath(e){const t=stripBackslashEscapes(removeOuterQuotes(e.trim()));return IMAGE_EXTENSION_REGEX.test(t)}export function asImageFilePath(e){const t=stripBackslashEscapes(removeOuterQuotes(e.trim()));return IMAGE_EXTENSION_REGEX.test(t)?t:null}export async function tryReadImageFromPath(e){const t=asImageFilePath(e);if(!t)return null;const i=t;let s;try{if(r(i))s=h().readFileBytesSync(i);else{const e=await getImagePathFromClipboard();e&&i===a(e)&&(s=h().readFileBytesSync(e))}}catch(e){return w(e),null}if(!s)return null;if(0===s.length)return g(`Image file is empty: ${i}`,{level:"warn"}),null;if(s.length>=2&&66===s[0]&&77===s[1]){const e=await c();s=await e(s).png().toBuffer()}const n=o(i).slice(1).toLowerCase()||"png",l=await f(s,s.length,n),m=l.buffer.toString("base64");return{path:i,base64:m,mediaType:u(m),dimensions:l.dimensions}}
1
+ import{feature as e}from"bun:bundle";import{randomBytes as t}from"crypto";import{execa as a}from"execa";import{basename as i,extname as s,isAbsolute as o,join as r}from"path";import{IMAGE_MAX_HEIGHT as n,IMAGE_MAX_WIDTH as l,IMAGE_TARGET_RAW_SIZE as m}from"../constants/apiLimits.js";import{getFeatureValue_CACHED_MAY_BE_STALE as p}from"../services/analytics/growthbook.js";import{getImageProcessor as c}from"../tools/FileReadTool/imageProcessor.js";import{logForDebugging as g}from"./debug.js";import{execFileNoThrowWithCwd as d}from"./execFileNoThrow.js";import{getFsImplementation as u}from"./fsOperations.js";import{detectImageFormatFromBase64 as h,maybeResizeAndDownsampleImageBuffer as f}from"./imageResizer.js";import{logError as w}from"./log.js";export const PASTE_THRESHOLD=800;function getClipboardCommands(){const e=process.platform,t=process.env.CONTEXT_CODE_TMPDIR||process.env.CLAUDE_CODE_TMPDIR||("win32"===e?process.env.TEMP||"C:\\Temp":"/tmp"),a="claude_cli_latest_screenshot.png",i={darwin:r(t,a),linux:r(t,a),win32:r(t,a)},s=i[e]||i.linux,o=s.replace(/'/g,"''"),n={darwin:{checkImage:"osascript -e 'the clipboard as «class PNGf»'",saveImage:`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${s}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:"osascript -e 'get POSIX path of (the clipboard as «class furl»)'",deleteFile:`rm -f "${s}"`},linux:{checkImage:'xclip -selection clipboard -t TARGETS -o 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)" || wl-paste -l 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)"',saveImage:`xclip -selection clipboard -t image/png -o > "${s}" 2>/dev/null || wl-paste --type image/png > "${s}" 2>/dev/null || xclip -selection clipboard -t image/bmp -o > "${s}" 2>/dev/null || wl-paste --type image/bmp > "${s}"`,getPath:"xclip -selection clipboard -t text/plain -o 2>/dev/null || wl-paste 2>/dev/null",deleteFile:`rm -f "${s}"`},win32:{checkImage:'powershell -NoProfile -STA -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::ContainsImage()"',saveImage:`powershell -NoProfile -STA -Command "Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img -ne $null) { $img.Save('${o}', [System.Drawing.Imaging.ImageFormat]::Png) } else { exit 1 }"`,getPath:'powershell -NoProfile -Command "Get-Clipboard -Raw"',deleteFile:`powershell -NoProfile -Command "Remove-Item -LiteralPath '${o}' -Force -ErrorAction SilentlyContinue"`}};return{commands:n[e]||n.linux,screenshotPath:s}}export async function hasImageInClipboard(){if("darwin"!==process.platform){const{commands:e}=getClipboardCommands(),t=await a(e.checkImage,{shell:!0,reject:!1});return 0===t.exitCode&&"false"!==t.stdout.trim().toLowerCase()}if(e("NATIVE_CLIPBOARD_IMAGE")&&p("tengu_collage_kaleidoscope",!0))try{const{getNativeModule:e}=await import("image-processor-napi"),t=e()?.hasClipboardImage;if(t)return t()}catch(e){w(e)}return 0===(await d("osascript",["-e","the clipboard as «class PNGf»"])).code}export async function getImageFromClipboard(){if(e("NATIVE_CLIPBOARD_IMAGE")&&"darwin"===process.platform&&p("tengu_collage_kaleidoscope",!0))try{const{getNativeModule:e}=await import("image-processor-napi"),t=e()?.readClipboardImage;if(!t)throw new Error("native clipboard reader unavailable");const a=t(l,n);if(!a)return null;const i=a.png;if(i.length>m){const e=await f(i,i.length,"png");return{base64:e.buffer.toString("base64"),mediaType:`image/${e.mediaType}`,dimensions:{originalWidth:a.originalWidth,originalHeight:a.originalHeight,displayWidth:e.dimensions?.displayWidth??a.width,displayHeight:e.dimensions?.displayHeight??a.height}}}return{base64:i.toString("base64"),mediaType:"image/png",dimensions:{originalWidth:a.originalWidth,originalHeight:a.originalHeight,displayWidth:a.width,displayHeight:a.height}}}catch(e){w(e)}const{commands:t,screenshotPath:i}=getClipboardCommands();try{if(0!==(await a(t.checkImage,{shell:!0,reject:!1})).exitCode)return null;if(0!==(await a(t.saveImage,{shell:!0,reject:!1})).exitCode)return null;let e=u().readFileBytesSync(i);if(e.length>=2&&66===e[0]&&77===e[1]){const t=await c();e=await t(e).png().toBuffer()}const s=await f(e,e.length,"png"),o=s.buffer.toString("base64"),r=h(o);return a(t.deleteFile,{shell:!0,reject:!1}),{base64:o,mediaType:r,dimensions:s.dimensions}}catch{return null}}export async function getImagePathFromClipboard(){const{commands:e}=getClipboardCommands();try{const t=await a(e.getPath,{shell:!0,reject:!1});return 0===t.exitCode&&t.stdout?t.stdout.trim():null}catch(e){return w(e),null}}export const IMAGE_EXTENSION_REGEX=/\.(png|jpe?g|gif|webp)$/i;function removeOuterQuotes(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function stripBackslashEscapes(e){if("win32"===process.platform)return e;const a=`__DOUBLE_BACKSLASH_${t(8).toString("hex")}__`;return e.replace(/\\\\/g,a).replace(/\\(.)/g,"$1").replace(new RegExp(a,"g"),"\\")}export function isImageFilePath(e){const t=stripBackslashEscapes(removeOuterQuotes(e.trim()));return IMAGE_EXTENSION_REGEX.test(t)}export function asImageFilePath(e){const t=stripBackslashEscapes(removeOuterQuotes(e.trim()));return IMAGE_EXTENSION_REGEX.test(t)?t:null}export async function tryReadImageFromPath(e){const t=asImageFilePath(e);if(!t)return null;const a=t;let r;try{if(o(a))r=u().readFileBytesSync(a);else{const e=await getImagePathFromClipboard();e&&a===i(e)&&(r=u().readFileBytesSync(e))}}catch(e){return w(e),null}if(!r)return null;if(0===r.length)return g(`Image file is empty: ${a}`,{level:"warn"}),null;if(r.length>=2&&66===r[0]&&77===r[1]){const e=await c();r=await e(r).png().toBuffer()}const n=s(a).slice(1).toLowerCase()||"png",l=await f(r,r.length,n),m=l.buffer.toString("base64");return{path:a,base64:m,mediaType:h(m),dimensions:l.dimensions}}
@@ -1 +1 @@
1
- import{API_IMAGE_MAX_BASE64_SIZE as e,IMAGE_MAX_HEIGHT as i,IMAGE_MAX_WIDTH as t,IMAGE_TARGET_RAW_SIZE as r}from"../constants/apiLimits.js";import{logEvent as a}from"../services/analytics/index.js";import{getImageProcessor as n}from"../tools/FileReadTool/imageProcessor.js";import{logForDebugging as s}from"./debug.js";import{errorMessage as o}from"./errors.js";import{formatFileSize as m}from"./format.js";import{logError as l}from"./log.js";export class ImageResizeError extends Error{constructor(e){super(e),this.name="ImageResizeError"}}function classifyImageError(e){if(e instanceof Error){const i=e;if("MODULE_NOT_FOUND"===i.code||"ERR_MODULE_NOT_FOUND"===i.code||"ERR_DLOPEN_FAILED"===i.code)return 1;if("EACCES"===i.code||"EPERM"===i.code)return 8;if("ENOMEM"===i.code)return 5}const i=o(e);return i.includes("Native image processor module not available")?1:i.includes("unsupported image format")||i.includes("Input buffer")||i.includes("Input file is missing")||i.includes("Input file has corrupt header")||i.includes("corrupt header")||i.includes("corrupt image")||i.includes("premature end")||i.includes("zlib: data error")||i.includes("zero width")||i.includes("zero height")?2:i.includes("pixel limit")||i.includes("too many pixels")||i.includes("exceeds pixel")||i.includes("image dimensions")?4:i.includes("out of memory")||i.includes("Cannot allocate")||i.includes("memory allocation")?5:i.includes("timeout")||i.includes("timed out")?6:i.includes("Vips")?7:3}function hashString(e){let i=5381;for(let t=0;t<e.length;t++)i=(i<<5)+i+e.charCodeAt(t)|0;return i>>>0}export async function maybeResizeAndDownsampleImageBuffer(g,u,f){if(0===g.length)throw new ImageResizeError("Image file is empty (0 bytes)");try{const e=await n(),a=e(g),o=await a.metadata(),m=o.format??f,l="jpg"===m?"jpeg":m;if(!o.width||!o.height){if(u>r){return{buffer:await e(g).jpeg({quality:80}).toBuffer(),mediaType:"jpeg"}}return{buffer:g,mediaType:l}}const c=o.width,d=o.height;let p=c,h=d;if(u<=r&&p<=t&&h<=i)return{buffer:g,mediaType:l,dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}};const y="png"===l;if(!(p>t||h>i)&&u>r){if(y){const i=await e(g).png({compressionLevel:9,palette:!0}).toBuffer();if(i.length<=r)return{buffer:i,mediaType:"png",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}for(const i of[80,60,40,20]){const t=await e(g).jpeg({quality:i}).toBuffer();if(t.length<=r)return{buffer:t,mediaType:"jpeg",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}}p>t&&(h=Math.round(h*t/p),p=t),h>i&&(p=Math.round(p*i/h),h=i),s(`Resizing to ${p}x${h}`);const b=await e(g).resize(p,h,{fit:"inside",withoutEnlargement:!0}).toBuffer();if(b.length>r){if(y){const i=await e(g).resize(p,h,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:9,palette:!0}).toBuffer();if(i.length<=r)return{buffer:i,mediaType:"png",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}for(const i of[80,60,40,20]){const t=await e(g).resize(p,h,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:i}).toBuffer();if(t.length<=r)return{buffer:t,mediaType:"jpeg",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}const i=Math.min(p,1e3),t=Math.round(h*i/Math.max(p,1));s("Still too large, compressing with JPEG");const a=await e(g).resize(i,t,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:20}).toBuffer();return s(`JPEG compressed buffer size: ${a.length}`),{buffer:a,mediaType:"jpeg",dimensions:{originalWidth:c,originalHeight:d,displayWidth:i,displayHeight:t}}}return{buffer:b,mediaType:l,dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}catch(r){l(r);const n=classifyImageError(r),s=o(r);a("tengu_image_resize_failed",{original_size_bytes:u,error_type:n,error_message_hash:hashString(s)});const f=detectImageFormatFromBuffer(g).slice(6),c=Math.ceil(4*u/3),d=g.length>=24&&137===g[0]&&80===g[1]&&78===g[2]&&71===g[3]&&(g.readUInt32BE(16)>t||g.readUInt32BE(20)>i);if(c<=e&&!d)return a("tengu_image_resize_fallback",{original_size_bytes:u,base64_size_bytes:c,error_type:n}),{buffer:g,mediaType:f};throw new ImageResizeError(d?`Unable to resize image — dimensions exceed the ${t}x${i}px limit and image processing failed. Please resize the image to reduce its pixel dimensions.`:`Unable to resize image (${m(u)} raw, ${m(c)} base64). The image exceeds the 5MB API limit and compression failed. Please resize the image manually or use a smaller image.`)}}export async function maybeResizeAndDownsampleImageBlock(e){if("base64"!==e.source.type)return{block:e};const i=Buffer.from(e.source.data,"base64"),t=i.length,r=e.source.media_type,a=r?.split("/")[1]||"png",n=await maybeResizeAndDownsampleImageBuffer(i,t,a);return{block:{type:"image",source:{type:"base64",media_type:`image/${n.mediaType}`,data:n.buffer.toString("base64")}},dimensions:n.dimensions}}export async function compressImageBuffer(e,i=r,t){const s=t?.split("/")[1]||"jpeg",g="jpg"===s?"jpeg":s;try{const t=await n(),r=await t(e).metadata(),a=r.format||g,s=e.length,o={imageBuffer:e,metadata:r,format:a,maxBytes:i,originalSize:s};if(s<=i)return createCompressedImageResult(e,a,s);const m=await async function(e,i){const t=[1,.75,.5,.25];for(const r of t){const t=Math.round((e.metadata.width||2e3)*r),a=Math.round((e.metadata.height||2e3)*r);let n=i(e.imageBuffer).resize(t,a,{fit:"inside",withoutEnlargement:!0});n=applyFormatOptimizations(n,e.format);const s=await n.toBuffer();if(s.length<=e.maxBytes)return createCompressedImageResult(s,e.format,e.originalSize)}return null}(o,t);if(m)return m;if("png"===a){const e=await async function(e,i){const t=await i(e.imageBuffer).resize(800,800,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:9,palette:!0,colors:64}).toBuffer();if(t.length<=e.maxBytes)return createCompressedImageResult(t,"png",e.originalSize);return null}(o,t);if(e)return e}const l=await async function(e,i,t){const r=await t(e.imageBuffer).resize(600,600,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:i}).toBuffer();if(r.length<=e.maxBytes)return createCompressedImageResult(r,"jpeg",e.originalSize);return null}(o,50,t);return l||await async function(e,i){const t=await i(e.imageBuffer).resize(400,400,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:20}).toBuffer();return createCompressedImageResult(t,"jpeg",e.originalSize)}(o,t)}catch(t){l(t);const r=classifyImageError(t),n=o(t);if(a("tengu_image_compress_failed",{original_size_bytes:e.length,max_bytes:i,error_type:r,error_message_hash:hashString(n)}),e.length<=i){const i=detectImageFormatFromBuffer(e);return{base64:e.toString("base64"),mediaType:i,originalSize:e.length}}throw new ImageResizeError(`Unable to compress image (${m(e.length)}) to fit within ${m(i)}. Please use a smaller image.`)}}export async function compressImageBufferWithTokenLimit(e,i,t){const r=Math.floor(i/.125);return compressImageBuffer(e,Math.floor(.75*r),t)}export async function compressImageBlock(e,i=r){if("base64"!==e.source.type)return e;const t=Buffer.from(e.source.data,"base64");if(t.length<=i)return e;const a=await compressImageBuffer(t,i);return{type:"image",source:{type:"base64",media_type:a.mediaType,data:a.base64}}}function createCompressedImageResult(e,i,t){const r="jpg"===i?"jpeg":i;return{base64:e.toString("base64"),mediaType:`image/${r}`,originalSize:t}}function applyFormatOptimizations(e,i){switch(i){case"png":return e.png({compressionLevel:9,palette:!0});case"jpeg":case"jpg":return e.jpeg({quality:80});case"webp":return e.webp({quality:80});default:return e}}export function detectImageFormatFromBuffer(e){return e.length<4||137===e[0]&&80===e[1]&&78===e[2]&&71===e[3]?"image/png":255===e[0]&&216===e[1]&&255===e[2]?"image/jpeg":71===e[0]&&73===e[1]&&70===e[2]?"image/gif":82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]&&e.length>=12&&87===e[8]&&69===e[9]&&66===e[10]&&80===e[11]?"image/webp":"image/png"}export function detectImageFormatFromBase64(e){try{return detectImageFormatFromBuffer(Buffer.from(e,"base64"))}catch{return"image/png"}}export function createImageMetadataText(e,i){const{originalWidth:t,originalHeight:r,displayWidth:a,displayHeight:n}=e;if(!t||!r||!a||!n||a<=0||n<=0)return i?`[Image source: ${i}]`:null;const s=t!==a||r!==n;if(!s&&!i)return null;const o=[];if(i&&o.push(`source: ${i}`),s){const e=t/a;o.push(`original ${t}x${r}, displayed at ${a}x${n}. Multiply coordinates by ${e.toFixed(2)} to map to original image.`)}return`[Image: ${o.join(", ")}]`}
1
+ import{API_IMAGE_MAX_BASE64_SIZE as e,IMAGE_MAX_HEIGHT as i,IMAGE_MAX_WIDTH as t,IMAGE_TARGET_RAW_SIZE as r}from"../constants/apiLimits.js";import{logEvent as a}from"../services/analytics/index.js";import{getImageProcessor as n}from"../tools/FileReadTool/imageProcessor.js";import{logForDebugging as s}from"./debug.js";import{errorMessage as o}from"./errors.js";import{formatFileSize as g}from"./format.js";import{logError as l}from"./log.js";export class ImageResizeError extends Error{constructor(e){super(e),this.name="ImageResizeError"}}function classifyImageError(e){if(e instanceof Error){const i=e;if("MODULE_NOT_FOUND"===i.code||"ERR_MODULE_NOT_FOUND"===i.code||"ERR_DLOPEN_FAILED"===i.code)return 1;if("EACCES"===i.code||"EPERM"===i.code)return 8;if("ENOMEM"===i.code)return 5}const i=o(e);return i.includes("Native image processor module not available")?1:i.includes("unsupported image format")||i.includes("Input buffer")||i.includes("Input file is missing")||i.includes("Input file has corrupt header")||i.includes("corrupt header")||i.includes("corrupt image")||i.includes("premature end")||i.includes("zlib: data error")||i.includes("zero width")||i.includes("zero height")?2:i.includes("pixel limit")||i.includes("too many pixels")||i.includes("exceeds pixel")||i.includes("image dimensions")?4:i.includes("out of memory")||i.includes("Cannot allocate")||i.includes("memory allocation")?5:i.includes("timeout")||i.includes("timed out")?6:i.includes("Vips")?7:3}function hashString(e){let i=5381;for(let t=0;t<e.length;t++)i=(i<<5)+i+e.charCodeAt(t)|0;return i>>>0}export async function maybeResizeAndDownsampleImageBuffer(m,u,f){if(0===m.length)throw new ImageResizeError("Image file is empty (0 bytes)");try{const e=await n(),a=e(m),o=await a.metadata(),g=o.format??f,l="jpg"===g?"jpeg":g;if(!o.width||!o.height)return u>r?{buffer:await e(m).jpeg({quality:80}).toBuffer(),mediaType:"jpeg"}:{buffer:m,mediaType:l};const c=o.width,d=o.height;let p=c,h=d;if(u<=r&&p<=t&&h<=i)return{buffer:m,mediaType:l,dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}};const y="png"===l;if(!(p>t||h>i)&&u>r){if(y){const i=await e(m).png({compressionLevel:9,palette:!0}).toBuffer();if(i.length<=r)return{buffer:i,mediaType:"png",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}for(const i of[80,60,40,20]){const t=await e(m).jpeg({quality:i}).toBuffer();if(t.length<=r)return{buffer:t,mediaType:"jpeg",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}}p>t&&(h=Math.round(h*t/p),p=t),h>i&&(p=Math.round(p*i/h),h=i),s(`Resizing to ${p}x${h}`);const b=await e(m).resize(p,h,{fit:"inside",withoutEnlargement:!0}).toBuffer();if(b.length>r){if(y){const i=await e(m).resize(p,h,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:9,palette:!0}).toBuffer();if(i.length<=r)return{buffer:i,mediaType:"png",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}for(const i of[80,60,40,20]){const t=await e(m).resize(p,h,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:i}).toBuffer();if(t.length<=r)return{buffer:t,mediaType:"jpeg",dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}const i=Math.min(p,1e3),t=Math.round(h*i/Math.max(p,1));s("Still too large, compressing with JPEG");const a=await e(m).resize(i,t,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:20}).toBuffer();return s(`JPEG compressed buffer size: ${a.length}`),{buffer:a,mediaType:"jpeg",dimensions:{originalWidth:c,originalHeight:d,displayWidth:i,displayHeight:t}}}return{buffer:b,mediaType:l,dimensions:{originalWidth:c,originalHeight:d,displayWidth:p,displayHeight:h}}}catch(r){l(r);const n=classifyImageError(r),s=o(r);a("tengu_image_resize_failed",{original_size_bytes:u,error_type:n,error_message_hash:hashString(s)});const f=detectImageFormatFromBuffer(m).slice(6),c=Math.ceil(4*u/3),d=m.length>=24&&137===m[0]&&80===m[1]&&78===m[2]&&71===m[3]&&(m.readUInt32BE(16)>t||m.readUInt32BE(20)>i);if(c<=e&&!d)return a("tengu_image_resize_fallback",{original_size_bytes:u,base64_size_bytes:c,error_type:n}),{buffer:m,mediaType:f};throw new ImageResizeError(d?`Unable to resize image — dimensions exceed the ${t}x${i}px limit and image processing failed. Please resize the image to reduce its pixel dimensions.`:`Unable to resize image (${g(u)} raw, ${g(c)} base64). The image exceeds the 5MB API limit and compression failed. Please resize the image manually or use a smaller image.`)}}export async function maybeResizeAndDownsampleImageBlock(e){if("base64"!==e.source.type)return{block:e};const i=Buffer.from(e.source.data,"base64"),t=i.length,r=e.source.media_type,a=r?.split("/")[1]||"png",n=await maybeResizeAndDownsampleImageBuffer(i,t,a);return{block:{type:"image",source:{type:"base64",media_type:`image/${n.mediaType}`,data:n.buffer.toString("base64")}},dimensions:n.dimensions}}export async function compressImageBuffer(e,i=r,t){const s=t?.split("/")[1]||"jpeg",m="jpg"===s?"jpeg":s;try{const t=await n(),r=await t(e).metadata(),a=r.format||m,s=e.length,o={imageBuffer:e,metadata:r,format:a,maxBytes:i,originalSize:s};if(s<=i)return createCompressedImageResult(e,a,s);const g=await async function(e,i){const t=[1,.75,.5,.25];for(const r of t){const t=Math.round((e.metadata.width||2e3)*r),a=Math.round((e.metadata.height||2e3)*r);let n=i(e.imageBuffer).resize(t,a,{fit:"inside",withoutEnlargement:!0});n=applyFormatOptimizations(n,e.format);const s=await n.toBuffer();if(s.length<=e.maxBytes)return createCompressedImageResult(s,e.format,e.originalSize)}return null}(o,t);if(g)return g;if("png"===a){const e=await async function(e,i){const t=await i(e.imageBuffer).resize(800,800,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:9,palette:!0,colors:64}).toBuffer();return t.length<=e.maxBytes?createCompressedImageResult(t,"png",e.originalSize):null}(o,t);if(e)return e}const l=await async function(e,i,t){const r=await t(e.imageBuffer).resize(600,600,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:50}).toBuffer();return r.length<=e.maxBytes?createCompressedImageResult(r,"jpeg",e.originalSize):null}(o,0,t);return l||await async function(e,i){return createCompressedImageResult(await i(e.imageBuffer).resize(400,400,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:20}).toBuffer(),"jpeg",e.originalSize)}(o,t)}catch(t){l(t);const r=classifyImageError(t),n=o(t);if(a("tengu_image_compress_failed",{original_size_bytes:e.length,max_bytes:i,error_type:r,error_message_hash:hashString(n)}),e.length<=i){const i=detectImageFormatFromBuffer(e);return{base64:e.toString("base64"),mediaType:i,originalSize:e.length}}throw new ImageResizeError(`Unable to compress image (${g(e.length)}) to fit within ${g(i)}. Please use a smaller image.`)}}export async function compressImageBufferWithTokenLimit(e,i,t){const r=Math.floor(i/.125);return compressImageBuffer(e,Math.floor(.75*r),t)}export async function compressImageBlock(e,i=r){if("base64"!==e.source.type)return e;const t=Buffer.from(e.source.data,"base64");if(t.length<=i)return e;const a=await compressImageBuffer(t,i);return{type:"image",source:{type:"base64",media_type:a.mediaType,data:a.base64}}}function createCompressedImageResult(e,i,t){const r="jpg"===i?"jpeg":i;return{base64:e.toString("base64"),mediaType:`image/${r}`,originalSize:t}}function applyFormatOptimizations(e,i){switch(i){case"png":return e.png({compressionLevel:9,palette:!0});case"jpeg":case"jpg":return e.jpeg({quality:80});case"webp":return e.webp({quality:80});default:return e}}export function detectImageFormatFromBuffer(e){return e.length<4||137===e[0]&&80===e[1]&&78===e[2]&&71===e[3]?"image/png":255===e[0]&&216===e[1]&&255===e[2]?"image/jpeg":71===e[0]&&73===e[1]&&70===e[2]?"image/gif":82===e[0]&&73===e[1]&&70===e[2]&&70===e[3]&&e.length>=12&&87===e[8]&&69===e[9]&&66===e[10]&&80===e[11]?"image/webp":"image/png"}export function detectImageFormatFromBase64(e){try{return detectImageFormatFromBuffer(Buffer.from(e,"base64"))}catch{return"image/png"}}export function createImageMetadataText(e,i){const{originalWidth:t,originalHeight:r,displayWidth:a,displayHeight:n}=e;if(!t||!r||!a||!n||a<=0||n<=0)return i?`[Image source: ${i}]`:null;const s=t!==a||r!==n;if(!s&&!i)return null;const o=[];if(i&&o.push(`source: ${i}`),s){const e=t/a;o.push(`original ${t}x${r}, displayed at ${a}x${n}. Multiply coordinates by ${e.toFixed(2)} to map to original image.`)}return`[Image: ${o.join(", ")}]`}
@@ -1 +1 @@
1
- import{mkdir as t,open as e}from"fs/promises";import{join as a}from"path";import{getSessionId as r}from"../bootstrap/state.js";import{logForDebugging as i}from"./debug.js";import{getClaudeConfigHomeDir as n}from"./envUtils.js";import{getFsImplementation as o}from"./fsOperations.js";const c="image-cache",s=new Map;function getImageStoreDir(){return a(n(),c,r())}function getImagePath(t,e){const r=e.split("/")[1]||"png";return a(getImageStoreDir(),`${t}.${r}`)}export function cacheImagePath(t){if("image"!==t.type)return null;const e=getImagePath(t.id,t.mediaType||"image/png");return evictOldestIfAtCap(),s.set(t.id,e),e}export async function storeImage(a){if("image"!==a.type)return null;try{await async function(){const e=getImageStoreDir();await t(e,{recursive:!0})}();const r=getImagePath(a.id,a.mediaType||"image/png"),n=await e(r,"w",384);try{await n.writeFile(a.content,{encoding:"base64"}),await n.datasync()}finally{await n.close()}return evictOldestIfAtCap(),s.set(a.id,r),i(`Stored image ${a.id} to ${r}`),r}catch(t){return i(`Failed to store image: ${t}`),null}}export async function storeImages(t){const e=new Map;for(const[a,r]of Object.entries(t))if("image"===r.type){const t=await storeImage(r);t&&e.set(Number(a),t)}return e}export function getStoredImagePath(t){return s.get(t)??null}export function clearStoredImagePaths(){s.clear()}function evictOldestIfAtCap(){for(;s.size>=200;){const t=s.keys().next().value;if(void 0===t)break;s.delete(t)}}export async function cleanupOldImageCaches(){const t=o(),e=a(n(),c),s=r();try{let r;try{r=await t.readdir(e)}catch{return}for(const n of r){if(n.name===s)continue;const r=a(e,n.name);try{await t.rm(r,{recursive:!0,force:!0}),i(`Cleaned up old image cache: ${r}`)}catch{}}try{0===(await t.readdir(e)).length&&await t.rmdir(e)}catch{}}catch{}}
1
+ import{mkdir as t,open as e}from"fs/promises";import{join as a}from"path";import{getSessionId as r}from"../bootstrap/state.js";import{logForDebugging as i}from"./debug.js";import{getClaudeConfigHomeDir as n}from"./envUtils.js";import{getFsImplementation as o}from"./fsOperations.js";const s="image-cache",c=new Map;function getImageStoreDir(){return a(n(),s,r())}function getImagePath(t,e){const r=e.split("/")[1]||"png";return a(getImageStoreDir(),`${t}.${r}`)}export function cacheImagePath(t){if("image"!==t.type)return null;const e=getImagePath(t.id,t.mediaType||"image/png");return evictOldestIfAtCap(),c.set(t.id,e),e}export async function storeImage(a){if("image"!==a.type)return null;try{await async function(){const e=getImageStoreDir();await t(e,{recursive:!0})}();const r=getImagePath(a.id,a.mediaType||"image/png"),n=await e(r,"w",384);try{await n.writeFile(a.content,{encoding:"base64"}),await n.datasync()}finally{await n.close()}return evictOldestIfAtCap(),c.set(a.id,r),i(`Stored image ${a.id} to ${r}`),r}catch(t){return i(`Failed to store image: ${t}`),null}}export async function storeImages(t){const e=new Map;for(const[a,r]of Object.entries(t))if("image"===r.type){const t=await storeImage(r);t&&e.set(Number(a),t)}return e}export function getStoredImagePath(t){return c.get(t)??null}export function clearStoredImagePaths(){c.clear()}function evictOldestIfAtCap(){for(;c.size>=200;){const t=c.keys().next().value;if(void 0===t)break;c.delete(t)}}export async function cleanupOldImageCaches(){const t=o(),e=a(n(),s),c=r();try{let r;try{r=await t.readdir(e)}catch{return}for(const n of r){if(n.name===c)continue;const r=a(e,n.name);try{await t.rm(r,{recursive:!0,force:!0}),i(`Cleaned up old image cache: ${r}`)}catch{}}try{0===(await t.readdir(e)).length&&await t.rmdir(e)}catch{}}catch{}}
@@ -1 +1 @@
1
- import{isInProcessTeammateTask as t}from"../tasks/InProcessTeammateTask/types.js";import{updateTaskState as e}from"./task/framework.js";import{isPermissionResponse as a,isSandboxPermissionResponse as o}from"./teammateMailbox.js";export function findInProcessTeammateTaskId(e,a){for(const o of Object.values(a.tasks))if(t(o)&&o.identity.agentName===e)return o.id}export function setAwaitingPlanApproval(t,a,o){e(t,a,t=>({...t,awaitingPlanApproval:o}))}export function handlePlanApprovalResponse(t,e,a){setAwaitingPlanApproval(t,a,!1)}export function isPermissionRelatedResponse(t){return!!a(t)||!!o(t)}
1
+ import{isInProcessTeammateTask as s}from"../tasks/InProcessTeammateTask/types.js";import{updateTaskState as e}from"./task/framework.js";import{isPermissionResponse as a,isSandboxPermissionResponse as t}from"./teammateMailbox.js";export function findInProcessTeammateTaskId(e,a){for(const t of Object.values(a.tasks))if(s(t)&&t.identity.agentName===e)return t.id}export function setAwaitingPlanApproval(s,a,t){e(s,a,s=>({...s,awaitingPlanApproval:t}))}export function handlePlanApprovalResponse(s,e,a){setAwaitingPlanApproval(s,a,!1)}export function isPermissionRelatedResponse(s){return!!a(s)||!!t(s)}
@@ -1 +1 @@
1
- import{AGENT_COLOR_TO_THEME_COLOR as o}from"../tools/AgentTool/agentColorManager.js";export function toInkColor(n){if(!n)return"cyan_FOR_SUBAGENTS_ONLY";const r=o[n];return r||`ansi:${n}`}
1
+ import{AGENT_COLOR_TO_THEME_COLOR as o}from"../tools/AgentTool/agentColorManager.js";export function toInkColor(n){if(!n)return"cyan_FOR_SUBAGENTS_ONLY";return o[n]||`ansi:${n}`}
@@ -1 +1 @@
1
- import{homedir as t,platform as e}from"os";import{join as n}from"path";import{getFsImplementation as o}from"./fsOperations.js";const i={pycharm:["PyCharm"],intellij:["IntelliJIdea","IdeaIC"],webstorm:["WebStorm"],phpstorm:["PhpStorm"],rubymine:["RubyMine"],clion:["CLion"],goland:["GoLand"],rider:["Rider"],datagrip:["DataGrip"],appcode:["AppCode"],dataspell:["DataSpell"],aqua:["Aqua"],gateway:["Gateway"],fleet:["Fleet"],androidstudio:["AndroidStudio"]};async function detectPluginDirectories(r){const a=[],s=o(),c=function(o){const r=t(),a=[],s=i[o.toLowerCase()];if(!s)return a;const c=process.env.APPDATA||n(r,"AppData","Roaming"),p=process.env.LOCALAPPDATA||n(r,"AppData","Local");switch(e()){case"darwin":a.push(n(r,"Library","Application Support","JetBrains"),n(r,"Library","Application Support")),"androidstudio"===o.toLowerCase()&&a.push(n(r,"Library","Application Support","Google"));break;case"win32":a.push(n(c,"JetBrains"),n(p,"JetBrains"),n(c)),"androidstudio"===o.toLowerCase()&&a.push(n(p,"Google"));break;case"linux":a.push(n(r,".config","JetBrains"),n(r,".local","share","JetBrains"));for(const t of s)a.push(n(r,"."+t));"androidstudio"===o.toLowerCase()&&a.push(n(r,".config","Google"))}return a}(r),p=i[r.toLowerCase()];if(!p)return a;const u=p.map(t=>new RegExp("^"+t));for(const t of c)try{const o=await s.readdir(t);for(const i of u)for(const r of o){if(!i.test(r.name))continue;if(!r.isDirectory()&&!r.isSymbolicLink())continue;const o=n(t,r.name);if("linux"===e()){a.push(o);continue}const c=n(o,"plugins");try{await s.stat(c),a.push(c)}catch{}}}catch{continue}return a.filter((t,e)=>a.indexOf(t)===e)}export async function isJetBrainsPluginInstalled(t){const e=await detectPluginDirectories(t);for(const t of e){const e=n(t,"claude-code-jetbrains-plugin");try{return await o().stat(e),!0}catch{}}return!1}const r=new Map,a=new Map;export async function isJetBrainsPluginInstalledCached(t,e=!1){return e&&(r.delete(t),a.delete(t)),async function(t,e=!1){if(!e){const e=a.get(t);if(e)return e}const n=isJetBrainsPluginInstalled(t).then(e=>(r.set(t,e),e));return a.set(t,n),n}(t,e)}export function isJetBrainsPluginInstalledCachedSync(t){return r.get(t)??!1}
1
+ import{homedir as t,platform as e}from"os";import{join as n}from"path";import{getFsImplementation as o}from"./fsOperations.js";const i={pycharm:["PyCharm"],intellij:["IntelliJIdea","IdeaIC"],webstorm:["WebStorm"],phpstorm:["PhpStorm"],rubymine:["RubyMine"],clion:["CLion"],goland:["GoLand"],rider:["Rider"],datagrip:["DataGrip"],appcode:["AppCode"],dataspell:["DataSpell"],aqua:["Aqua"],gateway:["Gateway"],fleet:["Fleet"],androidstudio:["AndroidStudio"]};async function detectPluginDirectories(a){const r=[],s=o(),c=function(o){const a=t(),r=[],s=i[o.toLowerCase()];if(!s)return r;const c=process.env.APPDATA||n(a,"AppData","Roaming"),p=process.env.LOCALAPPDATA||n(a,"AppData","Local");switch(e()){case"darwin":r.push(n(a,"Library","Application Support","JetBrains"),n(a,"Library","Application Support")),"androidstudio"===o.toLowerCase()&&r.push(n(a,"Library","Application Support","Google"));break;case"win32":r.push(n(c,"JetBrains"),n(p,"JetBrains"),n(c)),"androidstudio"===o.toLowerCase()&&r.push(n(p,"Google"));break;case"linux":r.push(n(a,".config","JetBrains"),n(a,".local","share","JetBrains"));for(const t of s)r.push(n(a,"."+t));"androidstudio"===o.toLowerCase()&&r.push(n(a,".config","Google"))}return r}(a),p=i[a.toLowerCase()];if(!p)return r;const u=p.map(t=>new RegExp("^"+t));for(const t of c)try{const o=await s.readdir(t);for(const i of u)for(const a of o){if(!i.test(a.name))continue;if(!a.isDirectory()&&!a.isSymbolicLink())continue;const o=n(t,a.name);if("linux"===e()){r.push(o);continue}const c=n(o,"plugins");try{await s.stat(c),r.push(c)}catch{}}}catch{continue}return r.filter((t,e)=>r.indexOf(t)===e)}export async function isJetBrainsPluginInstalled(t){const e=await detectPluginDirectories(t);for(const t of e){const e=n(t,"claude-code-jetbrains-plugin");try{return await o().stat(e),!0}catch{}}return!1}const a=new Map,r=new Map;export async function isJetBrainsPluginInstalledCached(t,e=!1){return e&&(a.delete(t),r.delete(t)),async function(t,e=!1){if(!e){const e=r.get(t);if(e)return e}const n=isJetBrainsPluginInstalled(t).then(e=>(a.set(t,e),e));return r.set(t,n),n}(t,e)}export function isJetBrainsPluginInstalledCachedSync(t){return a.get(t)??!1}
@@ -1 +1 @@
1
- var r=this&&this.__addDisposableResource||function(r,e,t){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var n,o;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(r){return Promise.reject(r)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},e=this&&this.__disposeResources||function(r){return function(e){function fail(t){e.error=e.hasError?new r(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var t,n=0;return function next(){for(;t=e.stack.pop();)try{if(!t.async&&1===n)return n=0,e.stack.push(t),Promise.resolve().then(next);if(t.dispose){var r=t.dispose.call(t.value);if(t.async)return n|=2,Promise.resolve(r).then(next,function(r){return fail(r),next()})}else n|=1}catch(r){fail(r)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});import{open as t,readFile as n,stat as o}from"fs/promises";import{applyEdits as s,modify as i,parse as a}from"jsonc-parser";import{stripBOM as c}from"./jsonRead.js";import{logError as u}from"./log.js";import{memoizeWithLRU as f}from"./memoize.js";import{jsonStringify as p}from"./slowOperations.js";function parseJSONUncached(r,e){try{return{ok:!0,value:JSON.parse(c(r))}}catch(r){return e&&u(r),{ok:!1}}}const l=f(parseJSONUncached,r=>r,50);export const safeParseJSON=Object.assign(function(r,e=!0){if(!r)return null;const t=r.length>8192?parseJSONUncached(r,e):l(r,e);return t.ok?t.value:null},{cache:l.cache});export function safeParseJSONC(r){if(!r)return null;try{return a(c(r))}catch(r){return u(r),null}}const d=(()=>{if("undefined"==typeof Bun)return!1;const r=Bun.JSONL;return!!r?.parseChunk&&r.parseChunk})();export function parseJSONL(r){return d?function(r){const e=d,t=r.length,n=e(r);if(!n.error||n.done||n.read>=t)return n.values;let o=n.values,s=n.read;for(;s<t;){const n="string"==typeof r?r.indexOf("\n",s):r.indexOf(10,s);if(-1===n)break;s=n+1;const i=e(r,s);if(i.values.length>0&&(o=o.concat(i.values)),!i.error||i.done||i.read>=t)break;s=i.read}return o}(r):"string"==typeof r?function(r){const e=c(r),t=e.length;let n=0;const o=[];for(;n<t;){let r=e.indexOf("\n",n);-1===r&&(r=t);const s=e.substring(n,r).trim();if(n=r+1,s)try{o.push(JSON.parse(s))}catch{}}return o}(r):function(r){const e=r.length;let t=0;239===r[0]&&187===r[1]&&191===r[2]&&(t=3);const n=[];for(;t<e;){let o=r.indexOf(10,t);-1===o&&(o=e);const s=r.toString("utf8",t,o).trim();if(t=o+1,s)try{n.push(JSON.parse(s))}catch{}}return n}(r)}const h=104857600;export async function readJSONLFile(s){const i={stack:[],error:void 0,hasError:!1};try{const{size:e}=await o(s);if(e<=h)return parseJSONL(await n(s));const a=r(i,await t(s,"r"),!0),c=Buffer.allocUnsafe(h);let u=0;const f=e-h;for(;u<h;){const{bytesRead:r}=await a.read(c,u,h-u,f+u);if(0===r)break;u+=r}const p=c.indexOf(10);return parseJSONL(-1!==p&&p<u-1?c.subarray(p+1,u):c.subarray(0,u))}catch(r){i.error=r,i.hasError=!0}finally{const r=e(i);r&&await r}}export function addItemToJSONCArray(r,e){try{if(!r||""===r.trim())return p([e],null,4);const t=c(r),n=a(t);if(Array.isArray(n)){const r=n.length,o=i(t,0===r?[0]:[r],e,{formattingOptions:{insertSpaces:!0,tabSize:4},isArrayInsertion:!0});if(!o||0===o.length){const r=[...n,e];return p(r,null,4)}return s(t,o)}return p([e],null,4)}catch(r){return u(r),p([e],null,4)}}
1
+ var r=this&&this.__addDisposableResource||function(r,e,t){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var n,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],t&&(s=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(r){return Promise.reject(r)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},e=this&&this.__disposeResources||function(r){return function(e){function fail(t){e.error=e.hasError?new r(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var t,n=0;return function next(){for(;t=e.stack.pop();)try{if(!t.async&&1===n)return n=0,e.stack.push(t),Promise.resolve().then(next);if(t.dispose){var r=t.dispose.call(t.value);if(t.async)return n|=2,Promise.resolve(r).then(next,function(r){return fail(r),next()})}else n|=1}catch(r){fail(r)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});import{open as t,readFile as n,stat as s}from"fs/promises";import{applyEdits as o,modify as a,parse as i}from"jsonc-parser";import{stripBOM as c}from"./jsonRead.js";import{logError as u}from"./log.js";import{memoizeWithLRU as f}from"./memoize.js";import{jsonStringify as p}from"./slowOperations.js";function parseJSONUncached(r,e){try{return{ok:!0,value:JSON.parse(c(r))}}catch(r){return e&&u(r),{ok:!1}}}const l=f(parseJSONUncached,r=>r,50);export const safeParseJSON=Object.assign(function(r,e=!0){if(!r)return null;const t=r.length>8192?parseJSONUncached(r,e):l(r,e);return t.ok?t.value:null},{cache:l.cache});export function safeParseJSONC(r){if(!r)return null;try{return i(c(r))}catch(r){return u(r),null}}const d=(()=>{if("undefined"==typeof Bun)return!1;const r=Bun.JSONL;return!!r?.parseChunk&&r.parseChunk})();export function parseJSONL(r){return d?function(r){const e=d,t=r.length,n=e(r);if(!n.error||n.done||n.read>=t)return n.values;let s=n.values,o=n.read;for(;o<t;){const n="string"==typeof r?r.indexOf("\n",o):r.indexOf(10,o);if(-1===n)break;o=n+1;const a=e(r,o);if(a.values.length>0&&(s=s.concat(a.values)),!a.error||a.done||a.read>=t)break;o=a.read}return s}(r):"string"==typeof r?function(r){const e=c(r),t=e.length;let n=0;const s=[];for(;n<t;){let r=e.indexOf("\n",n);-1===r&&(r=t);const o=e.substring(n,r).trim();if(n=r+1,o)try{s.push(JSON.parse(o))}catch{}}return s}(r):function(r){const e=r.length;let t=0;239===r[0]&&187===r[1]&&191===r[2]&&(t=3);const n=[];for(;t<e;){let s=r.indexOf(10,t);-1===s&&(s=e);const o=r.toString("utf8",t,s).trim();if(t=s+1,o)try{n.push(JSON.parse(o))}catch{}}return n}(r)}const h=104857600;export async function readJSONLFile(o){const a={stack:[],error:void 0,hasError:!1};try{const{size:e}=await s(o);if(e<=h)return parseJSONL(await n(o));const i=r(a,await t(o,"r"),!0),c=Buffer.allocUnsafe(h);let u=0;const f=e-h;for(;u<h;){const{bytesRead:r}=await i.read(c,u,h-u,f+u);if(0===r)break;u+=r}const p=c.indexOf(10);return parseJSONL(-1!==p&&p<u-1?c.subarray(p+1,u):c.subarray(0,u))}catch(r){a.error=r,a.hasError=!0}finally{const r=e(a);r&&await r}}export function addItemToJSONCArray(r,e){try{if(!r||""===r.trim())return p([e],null,4);const t=c(r),n=i(t);if(Array.isArray(n)){const r=n.length,s=a(t,0===r?[0]:[r],e,{formattingOptions:{insertSpaces:!0,tabSize:4},isArrayInsertion:!0});if(!s||0===s.length){const r=[...n,e];return p(r,null,4)}return o(t,s)}return p([e],null,4)}catch(r){return u(r),p([e],null,4)}}
@@ -1 +1 @@
1
- import{readdir as t,stat as e}from"fs/promises";import{basename as i,join as s}from"path";import{getWorktreePathsPortable as n}from"./getWorktreePathsPortable.js";import{canonicalizePath as a,extractFirstPromptFromHead as o,extractJsonStringField as r,extractLastJsonStringField as l,findProjectDir as c,getProjectsDir as d,MAX_SANITIZED_LENGTH as f,readSessionLite as m,sanitizePath as u,validateUuid as p}from"./sessionStoragePortable.js";export function parseSessionInfoFromLite(t,e,i){const{head:s,tail:n,mtime:a,size:c}=e,d=s.indexOf("\n"),f=d>=0?s.slice(0,d):s;if(f.includes('"isSidechain":true')||f.includes('"isSidechain": true'))return null;const m=l(n,"customTitle")||l(s,"customTitle")||l(n,"aiTitle")||l(s,"aiTitle")||void 0,u=o(s)||void 0,p=r(s,"timestamp");let h;if(p){const t=Date.parse(p);Number.isNaN(t)||(h=t)}const w=m||l(n,"lastPrompt")||l(n,"summary")||u;if(!w)return null;const y=l(n,"gitBranch")||r(s,"gitBranch")||void 0,g=r(s,"cwd")||i||void 0,I=n.split("\n").findLast(t=>t.startsWith('{"type":"tag"'));return{sessionId:t,summary:w,lastModified:a,fileSize:c,customTitle:m,firstPrompt:u,gitBranch:y,cwd:g,tag:I&&l(I,"tag")||void 0,createdAt:h}}export async function listCandidates(i,n,a){let o;try{o=await t(i)}catch{return[]}return(await Promise.all(o.map(async t=>{if(!t.endsWith(".jsonl"))return null;const o=p(t.slice(0,-6));if(!o)return null;const r=s(i,t);if(!n)return{sessionId:o,filePath:r,mtime:0,projectPath:a};try{return{sessionId:o,filePath:r,mtime:(await e(r)).mtime.getTime(),projectPath:a}}catch{return null}}))).filter(t=>null!==t)}async function readCandidate(t){const e=await m(t.filePath);if(!e)return null;const i=parseSessionInfoFromLite(t.sessionId,e,t.projectPath);return i?(t.mtime&&(i.lastModified=t.mtime),i):null}function compareDesc(t,e){return e.mtime!==t.mtime?e.mtime-t.mtime:e.sessionId<t.sessionId?-1:e.sessionId>t.sessionId?1:0}export async function listSessionsImpl(e){const{dir:o,limit:r,offset:l,includeWorktrees:m}=e??{},p=l??0,h=void 0!==r&&r>0||p>0,w=o?await async function(e,o,r){const l=await a(e);let m;if(o)try{m=await n(l)}catch{m=[]}else m=[];if(m.length<=1){const t=await c(l);return t?listCandidates(t,r,l):[]}const p=d(),h="win32"===process.platform,w=m.map(t=>{const e=u(t);return{path:t,prefix:h?e.toLowerCase():e}});let y;w.sort((t,e)=>e.prefix.length-t.prefix.length);try{y=await t(p,{withFileTypes:!0})}catch{const t=await c(l);return t?listCandidates(t,r,l):[]}const g=[],I=new Set,P=await c(l);if(P){const t=i(P);I.add(h?t.toLowerCase():t),g.push(...await listCandidates(P,r,l))}for(const t of y){if(!t.isDirectory())continue;const e=h?t.name.toLowerCase():t.name;if(!I.has(e))for(const{path:i,prefix:n}of w)if(e===n||n.length>=f&&e.startsWith(n+"-")){I.add(e),g.push(...await listCandidates(s(p,t.name),r,i));break}}return g}(o,m??!0,h):await async function(e){const i=d();let n;try{n=await t(i,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(t=>t.isDirectory()).map(t=>listCandidates(s(i,t.name),e)))).flat()}(h);return h?async function(t,e,i){t.sort(compareDesc);const s=[],n=e&&e>0?e:1/0;let a=0;const o=new Set;for(let e=0;e<t.length&&s.length<n;){const r=Math.min(e+32,t.length),l=t.slice(e,r),c=await Promise.all(l.map(readCandidate));for(let t=0;t<c.length&&s.length<n;t++){e++;const n=c[t];n&&(o.has(n.sessionId)||(o.add(n.sessionId),a<i?a++:s.push(n)))}}return s}(w,r,p):async function(t){const e=await Promise.all(t.map(readCandidate)),i=new Map;for(const t of e){if(!t)continue;const e=i.get(t.sessionId);(!e||t.lastModified>e.lastModified)&&i.set(t.sessionId,t)}const s=[...i.values()];return s.sort((t,e)=>e.lastModified!==t.lastModified?e.lastModified-t.lastModified:e.sessionId<t.sessionId?-1:e.sessionId>t.sessionId?1:0),s}(w)}
1
+ import{readdir as t,stat as e}from"fs/promises";import{basename as s,join as i}from"path";import{getWorktreePathsPortable as a}from"./getWorktreePathsPortable.js";import{canonicalizePath as n,extractFirstPromptFromHead as o,extractJsonStringField as r,extractLastJsonStringField as c,findProjectDir as l,getProjectsDir as d,MAX_SANITIZED_LENGTH as m,readSessionLite as f,sanitizePath as u,validateUuid as h}from"./sessionStoragePortable.js";export function parseSessionInfoFromLite(t,e,s){const{head:i,tail:a,mtime:n,size:l}=e,d=i.indexOf("\n"),m=d>=0?i.slice(0,d):i;if(m.includes('"isSidechain":true')||m.includes('"isSidechain": true'))return null;const f=c(a,"customTitle")||c(i,"customTitle")||c(a,"aiTitle")||c(i,"aiTitle")||void 0,u=o(i)||void 0,h=r(i,"timestamp");let p;if(h){const t=Date.parse(h);Number.isNaN(t)||(p=t)}const w=f||c(a,"lastPrompt")||c(a,"summary")||u;if(!w)return null;const g=c(a,"gitBranch")||r(i,"gitBranch")||void 0,P=r(i,"cwd")||s||void 0,I=a.split("\n").findLast(t=>t.startsWith('{"type":"tag"'));return{sessionId:t,summary:w,lastModified:n,fileSize:l,customTitle:f,firstPrompt:u,gitBranch:g,cwd:P,tag:I&&c(I,"tag")||void 0,createdAt:p}}export async function listCandidates(s,a,n){let o;try{o=await t(s)}catch{return[]}return(await Promise.all(o.map(async t=>{if(!t.endsWith(".jsonl"))return null;const o=h(t.slice(0,-6));if(!o)return null;const r=i(s,t);if(!a)return{sessionId:o,filePath:r,mtime:0,projectPath:n};try{return{sessionId:o,filePath:r,mtime:(await e(r)).mtime.getTime(),projectPath:n}}catch{return null}}))).filter(t=>null!==t)}async function readCandidate(t){const e=await f(t.filePath);if(!e)return null;const s=parseSessionInfoFromLite(t.sessionId,e,t.projectPath);return s?(t.mtime&&(s.lastModified=t.mtime),s):null}function compareDesc(t,e){return e.mtime!==t.mtime?e.mtime-t.mtime:e.sessionId<t.sessionId?-1:e.sessionId>t.sessionId?1:0}export async function listSessionsImpl(e){const{dir:o,limit:r,offset:c,includeWorktrees:f}=e??{},h=c??0,p=void 0!==r&&r>0||h>0,w=o?await async function(e,o,r){const c=await n(e);let f;if(o)try{f=await a(c)}catch{f=[]}else f=[];if(f.length<=1){const t=await l(c);return t?listCandidates(t,r,c):[]}const h=d(),p="win32"===process.platform,w=f.map(t=>{const e=u(t);return{path:t,prefix:p?e.toLowerCase():e}});let g;w.sort((t,e)=>e.prefix.length-t.prefix.length);try{g=await t(h,{withFileTypes:!0})}catch{const t=await l(c);return t?listCandidates(t,r,c):[]}const P=[],I=new Set,y=await l(c);if(y){const t=s(y);I.add(p?t.toLowerCase():t),P.push(...await listCandidates(y,r,c))}for(const t of g){if(!t.isDirectory())continue;const e=p?t.name.toLowerCase():t.name;if(!I.has(e))for(const{path:s,prefix:a}of w)if(e===a||a.length>=m&&e.startsWith(a+"-")){I.add(e),P.push(...await listCandidates(i(h,t.name),r,s));break}}return P}(o,f??!0,p):await async function(e){const s=d();let a;try{a=await t(s,{withFileTypes:!0})}catch{return[]}return(await Promise.all(a.filter(t=>t.isDirectory()).map(t=>listCandidates(i(s,t.name),e)))).flat()}(p);return p?async function(t,e,s){t.sort(compareDesc);const i=[],a=e&&e>0?e:1/0;let n=0;const o=new Set;for(let e=0;e<t.length&&i.length<a;){const r=Math.min(e+32,t.length),c=t.slice(e,r),l=await Promise.all(c.map(readCandidate));for(let t=0;t<l.length&&i.length<a;t++){e++;const a=l[t];a&&(o.has(a.sessionId)||(o.add(a.sessionId),n<s?n++:i.push(a)))}}return i}(w,r,h):async function(t){const e=await Promise.all(t.map(readCandidate)),s=new Map;for(const t of e){if(!t)continue;const e=s.get(t.sessionId);(!e||t.lastModified>e.lastModified)&&s.set(t.sessionId,t)}const i=[...s.values()];return i.sort((t,e)=>e.lastModified!==t.lastModified?e.lastModified-t.lastModified:e.sessionId<t.sessionId?-1:e.sessionId>t.sessionId?1:0),i}(w)}
@@ -1 +1 @@
1
- import{MACRO as t}from"../recovery/bunBundleShim.js";import{access as e,chmod as n,writeFile as r}from"fs/promises";import{join as a}from"path";import{saveGlobalConfig as o}from"./config.js";import{getClaudeConfigHomeDir as i}from"./envUtils.js";import{getErrnoCode as l}from"./errors.js";import{execFileNoThrowWithCwd as s}from"./execFileNoThrow.js";import{getFsImplementation as c}from"./fsOperations.js";import{logError as u}from"./log.js";import{jsonStringify as f}from"./slowOperations.js";function getLocalInstallDir(){return a(i(),"local")}export function getLocalClaudePath(){return a(getLocalInstallDir(),"claude")}export function isRunningFromLocalInstallation(){return(process.argv[1]||"").includes("/.claude/local/node_modules/")}async function writeIfMissing(t,e,n){try{return await r(t,e,{encoding:"utf8",flag:"wx",mode:n}),!0}catch(t){if("EEXIST"===l(t))return!1;throw t}}export async function ensureLocalPackageEnvironment(){try{const t=getLocalInstallDir();await c().mkdir(t),await writeIfMissing(a(t,"package.json"),f({name:"claude-local",version:"0.0.1",private:!0},null,2));const e=a(t,"claude");return await writeIfMissing(e,`#!/bin/sh\nexec "${t}/node_modules/.bin/claude" "$@"`,493)&&await n(e,493),!0}catch(t){return u(t),!1}}export async function installOrUpdateClaudePackage(e,n){try{if(!await ensureLocalPackageEnvironment())return"install_failed";const r=n||("stable"===e?"stable":"latest"),a=await s("npm",["install",`${t.PACKAGE_URL}@${r}`],{cwd:getLocalInstallDir(),maxBuffer:1e6});if(0!==a.code){const t=new Error(`Failed to install Claude CLI package: ${a.stderr}`);return u(t),190===a.code?"in_progress":"install_failed"}return o(t=>({...t,installMethod:"local"})),"success"}catch(t){return u(t),"install_failed"}}export async function localInstallationExists(){try{return await e(a(getLocalInstallDir(),"node_modules",".bin","claude")),!0}catch{return!1}}export function getShellType(){const t=process.env.SHELL||"";return t.includes("zsh")?"zsh":t.includes("bash")?"bash":t.includes("fish")?"fish":"unknown"}
1
+ import{MACRO as e}from"../recovery/bunBundleShim.js";import{access as t,chmod as a,writeFile as n}from"fs/promises";import{join as r}from"path";import{saveGlobalConfig as o}from"./config.js";import{getClaudeConfigHomeDir as s}from"./envUtils.js";import{getErrnoCode as i}from"./errors.js";import{execFileNoThrowWithCwd as l}from"./execFileNoThrow.js";import{getFsImplementation as c}from"./fsOperations.js";import{logError as u}from"./log.js";import{jsonStringify as f}from"./slowOperations.js";function getLocalInstallDir(){return r(s(),"local")}export function getLocalClaudePath(){return r(getLocalInstallDir(),"claude")}export function isRunningFromLocalInstallation(){return(process.argv[1]||"").includes("/.claude/local/node_modules/")}async function writeIfMissing(e,t,a){try{return await n(e,t,{encoding:"utf8",flag:"wx",mode:a}),!0}catch(e){if("EEXIST"===i(e))return!1;throw e}}export async function ensureLocalPackageEnvironment(){try{const e=getLocalInstallDir();await c().mkdir(e),await writeIfMissing(r(e,"package.json"),f({name:"claude-local",version:"0.0.1",private:!0},null,2));const t=r(e,"claude");return await writeIfMissing(t,`#!/bin/sh\nexec "${e}/node_modules/.bin/claude" "$@"`,493)&&await a(t,493),!0}catch(e){return u(e),!1}}export async function installOrUpdateClaudePackage(t,a){try{if(!await ensureLocalPackageEnvironment())return"install_failed";const n=a||("stable"===t?"stable":"latest"),r=await l("npm",["install",`${e.PACKAGE_URL}@${n}`],{cwd:getLocalInstallDir(),maxBuffer:1e6});if(0!==r.code){const e=new Error(`Failed to install Claude CLI package: ${r.stderr}`);return u(e),190===r.code?"in_progress":"install_failed"}return o(e=>({...e,installMethod:"local"})),"success"}catch(t){return u(t),"install_failed"}}export async function localInstallationExists(){try{return await t(r(getLocalInstallDir(),"node_modules",".bin","claude")),!0}catch{return!1}}export function getShellType(){const e=process.env.SHELL||"";return e.includes("zsh")?"zsh":e.includes("bash")?"bash":e.includes("fish")?"fish":"unknown"}
@@ -1 +1 @@
1
- import{createRequire as o}from"module";const e=o(import.meta.url);let c;function getLockfile(){return c||(c=e("proper-lockfile")),c}export function lock(o,e){return getLockfile().lock(o,e)}export function lockSync(o,e){return getLockfile().lockSync(o,e)}export function unlock(o,e){return getLockfile().unlock(o,e)}export function check(o,e){return getLockfile().check(o,e)}
1
+ import{createRequire as e}from"module";const o=e(import.meta.url);let c;function getLockfile(){return c||(c=o("proper-lockfile")),c}export function lock(e,o){return getLockfile().lock(e,o)}export function lockSync(e,o){return getLockfile().lockSync(e,o)}export function unlock(e,o){return getLockfile().unlock(e,o)}export function check(e,o){return getLockfile().check(e,o)}
@@ -1 +1 @@
1
- import{MACRO as t}from"../recovery/bunBundleShim.js";import{getDirectConnectServerUrl as e,getSessionId as r}from"../bootstrap/state.js";import{stringWidth as n}from"../ink/stringWidth.js";import{getSubscriptionName as o,isClaudeAISubscriber as i}from"./auth.js";import{getCwd as s}from"./cwd.js";import{getDisplayPath as a}from"./file.js";import{getAPIProvider as c}from"./model/providers.js";import{getActiveProviderProfile as u}from"./model/providerProfiles.js";import{getStoredActiveProviderPreference as l}from"./model/providerProfilesDb.js";import{truncate as m,truncateToWidth as f,truncateToWidthNoEllipsis as p}from"./format.js";import{getStoredChangelogFromMemory as d,parseChangelog as h}from"./releaseNotes.js";import{gt as g}from"./semver.js";import{loadMessageLogs as $}from"./sessionStorage.js";import{getInitialSettings as x}from"./settings/settings.js";function getProviderAccountLabel(){switch(function(){const t=l();if(t)return t;const e=c();return"firstParty"===e?"claude":e}()){case"claude":return"Context";case"openai":return"OpenAI";case"openrouter":return"OpenRouter";case"ollama":return"Ollama";case"ollama-cloud":return"Ollama Cloud";case"zai":return"Z.AI";case"minimax":return"MiniMax Code Plan";default:return i()?o():"Context API"}}export function getLayoutMode(t){return t>=110?"horizontal":"compact"}export function calculateLayoutDimensions(t,e,r){if("horizontal"===e){const e=r,n=t-(7+e);let o=Math.max(30,n);const i=Math.min(e+o+1+2,t-4);return i<e+o+1+2&&(o=i-e-1-2),{leftWidth:e,rightWidth:o,totalWidth:i}}const n=Math.min(t-4,70);return{leftWidth:n,rightWidth:n,totalWidth:n}}export function calculateOptimalLeftWidth(t,e,r){const o=Math.max(n(t),n(e),n(r),20);return Math.min(o+4,50)}export function formatWelcomeMessage(t){return!t||t.length>20?"¡Bienvenido de nuevo!":`¡Bienvenido de nuevo ${t}!`}export function truncatePath(t,e){if(n(t)<=e)return t;const r="/",o="…",i=t.split(r),s=i[0]||"",a=i[i.length-1]||"",c=n(s),u=n(a);if(1===i.length)return f(t,e);if(""===s&&2+u>=e)return`${r}${f(a,Math.max(1,e-1))}`;if(""!==s&&3+u>=e)return`${o}${r}${f(a,Math.max(1,e-1-1))}`;if(2===i.length){return`${p(s,e-1-1-u)}${o}${r}${a}`}let l=e-c-u-1-2;if(l<=0){const t=Math.max(0,e-u-1-2);return`${p(s,t)}${r}${o}${r}${a}`}const m=[];for(let t=i.length-2;t>0;t--){const e=i[t];if(!(e&&n(e)+1<=l))break;m.unshift(e),l-=n(e)+1}return 0===m.length?`${s}${r}${o}${r}${a}`:`${s}${r}${o}${r}${m.join(r)}${r}${a}`}let M=[],v=null;export async function getRecentActivity(){if(v)return v;const t=r();return v=$(10).then(e=>(M=e.filter(e=>{if(e.isSidechain)return!1;if(e.sessionId===t)return!1;if(e.summary?.includes("I apologize"))return!1;const r=e.summary&&"No prompt"!==e.summary,n=e.firstPrompt&&"No prompt"!==e.firstPrompt;return r||n}).slice(0,3),M)).catch(()=>(M=[],M)),v}export function getRecentActivitySync(){return M}export function formatReleaseNoteForDisplay(t,e){return m(t,e)}export function getLogoDisplayData(){const r=process.env.DEMO_VERSION??t.VERSION,n=e(),o=process.env.DEMO_VERSION?"/code/claude":a(s());return{version:r,cwd:n?`${o} in ${n.replace(/^https?:\/\//,"")}`:o,billingType:getProviderAccountLabel(),agentName:u()?.agentName??x().agent}}export function formatModelAndBilling(t,e,r){return n(t)+3+n(e)>r?{shouldSplit:!0,truncatedModel:m(t,r),truncatedBilling:m(e,r)}:{shouldSplit:!1,truncatedModel:m(t,Math.max(r-n(e)-3,10)),truncatedBilling:e}}export function getRecentReleaseNotesSync(e){if("ant"===process.env.USER_TYPE){const r=t.VERSION_CHANGELOG;if(r){return r.trim().split("\n").filter(Boolean).slice(0,e)}return[]}const r=d();if(!r)return[];let n;try{n=h(r)}catch{return[]}const o=[],i=Object.keys(n).sort((t,e)=>g(t,e)?-1:1).slice(0,3);for(const t of i){const e=n[t];e&&o.push(...e)}return o.slice(0,e)}
1
+ import{MACRO as t}from"../recovery/bunBundleShim.js";import{getDirectConnectServerUrl as e,getSessionId as r}from"../bootstrap/state.js";import{stringWidth as o}from"../ink/stringWidth.js";import{getSubscriptionName as n,isClaudeAISubscriber as i}from"./auth.js";import{getCwd as s}from"./cwd.js";import{getDisplayPath as a}from"./file.js";import{getAPIProvider as c}from"./model/providers.js";import{getActiveProviderProfile as l}from"./model/providerProfiles.js";import{getStoredActiveProviderPreference as u}from"./model/providerProfilesDb.js";import{truncate as m,truncateToWidth as f,truncateToWidthNoEllipsis as p}from"./format.js";import{getStoredChangelogFromMemory as d,parseChangelog as g}from"./releaseNotes.js";import{gt as h}from"./semver.js";import{loadMessageLogs as $}from"./sessionStorage.js";import{getInitialSettings as v}from"./settings/settings.js";function getProviderAccountLabel(){switch(function(){const t=u();if(t)return t;const e=c();return"firstParty"===e?"claude":e}()){case"claude":return"Context";case"openai":return"OpenAI";case"openrouter":return"OpenRouter";case"ollama":return"Ollama";case"ollama-cloud":return"Ollama Cloud";case"zai":return"Z.AI";case"minimax":return"MiniMax Code Plan";default:return i()?n():"Context API"}}export function getLayoutMode(t){return t>=110?"horizontal":"compact"}export function calculateLayoutDimensions(t,e,r){if("horizontal"===e){const e=r,o=t-(7+e);let n=Math.max(30,o);const i=Math.min(e+n+1+2,t-4);return i<e+n+1+2&&(n=i-e-1-2),{leftWidth:e,rightWidth:n,totalWidth:i}}const o=Math.min(t-4,70);return{leftWidth:o,rightWidth:o,totalWidth:o}}export function calculateOptimalLeftWidth(t,e,r){const n=Math.max(o(t),o(e),o(r),20);return Math.min(n+4,50)}export function formatWelcomeMessage(t){return!t||t.length>20?"¡Bienvenido de nuevo!":`¡Bienvenido de nuevo ${t}!`}export function truncatePath(t,e){if(o(t)<=e)return t;const r="/",n="…",i=t.split(r),s=i[0]||"",a=i[i.length-1]||"",c=o(s),l=o(a);if(1===i.length)return f(t,e);if(""===s&&2+l>=e)return`${r}${f(a,Math.max(1,e-1))}`;if(""!==s&&3+l>=e)return`${n}${r}${f(a,Math.max(1,e-1-1))}`;if(2===i.length)return`${p(s,e-1-1-l)}${n}${r}${a}`;let u=e-c-l-1-2;if(u<=0){const t=Math.max(0,e-l-1-2);return`${p(s,t)}${r}${n}${r}${a}`}const m=[];for(let t=i.length-2;t>0;t--){const e=i[t];if(!(e&&o(e)+1<=u))break;m.unshift(e),u-=o(e)+1}return 0===m.length?`${s}${r}${n}${r}${a}`:`${s}${r}${n}${r}${m.join(r)}${r}${a}`}let x=[],M=null;export async function getRecentActivity(){if(M)return M;const t=r();return M=$(10).then(e=>(x=e.filter(e=>{if(e.isSidechain)return!1;if(e.sessionId===t)return!1;if(e.summary?.includes("I apologize"))return!1;const r=e.summary&&"No prompt"!==e.summary,o=e.firstPrompt&&"No prompt"!==e.firstPrompt;return r||o}).slice(0,3),x)).catch(()=>(x=[],x)),M}export function getRecentActivitySync(){return x}export function formatReleaseNoteForDisplay(t,e){return m(t,e)}export function getLogoDisplayData(){const r=process.env.DEMO_VERSION??t.VERSION,o=e(),n=process.env.DEMO_VERSION?"/code/claude":a(s());return{version:r,cwd:o?`${n} in ${o.replace(/^https?:\/\//,"")}`:n,billingType:getProviderAccountLabel(),agentName:l()?.agentName??v().agent}}export function formatModelAndBilling(t,e,r){return o(t)+3+o(e)>r?{shouldSplit:!0,truncatedModel:m(t,r),truncatedBilling:m(e,r)}:{shouldSplit:!1,truncatedModel:m(t,Math.max(r-o(e)-3,10)),truncatedBilling:e}}export function getRecentReleaseNotesSync(e){if("ant"===process.env.USER_TYPE){const r=t.VERSION_CHANGELOG;return r?r.trim().split("\n").filter(Boolean).slice(0,e):[]}const r=d();if(!r)return[];let o;try{o=g(r)}catch{return[]}const n=[],i=Object.keys(o).sort((t,e)=>h(t,e)?-1:1).slice(0,3);for(const t of i){const e=o[t];e&&n.push(...e)}return n.slice(0,e)}
@@ -1 +1 @@
1
- import e from"chalk";import{marked as t}from"marked";import n from"strip-ansi";import{color as r}from"../components/design-system/color.js";import{BLOCKQUOTE_BAR as o}from"../constants/figures.js";import{stringWidth as a}from"../ink/stringWidth.js";import{supportsHyperlinks as s}from"../ink/supports-hyperlinks.js";import{logForDebugging as l}from"./debug.js";import{createHyperlink as i}from"./hyperlink.js";import{stripPromptXMLTags as u}from"./messages.js";const c="\n";let m=!1;export function configureMarked(){m||(m=!0,t.use({tokenizer:{del(){}}}))}export function applyMarkdown(e,n,r=null){return configureMarked(),t.lexer(u(e)).map(e=>formatToken(e,n,0,null,null,r)).join("").trim()}export function formatToken(t,s,u=0,m=null,p=null,k=null){switch(t.type){case"blockquote":{const g=(t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join(""),h=e.dim(o);return g.split(c).map(t=>n(t).trim()?`${h} ${e.italic(t)}`:t).join(c)}case"code":{if(!k)return t.text+c;let d="plaintext";return t.lang&&(k.supportsLanguage(t.lang)?d=t.lang:l(`Language not supported while highlighting code, falling back to plaintext: ${t.lang}`)),k.highlight(t.text,{language:d})+c}case"codespan":return r("permission",s)(t.text);case"em":return e.italic((t.tokens??[]).map(e=>formatToken(e,s,0,null,p,k)).join(""));case"strong":return e.bold((t.tokens??[]).map(e=>formatToken(e,s,0,null,p,k)).join(""));case"heading":return 1===t.depth?e.bold.italic.underline((t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join(""))+c+c:e.bold((t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join(""))+c+c;case"hr":return"---";case"image":return t.href;case"link":{if(t.href.startsWith("mailto:")){return t.href.replace(/^mailto:/,"")}const x=(t.tokens??[]).map(e=>formatToken(e,s,0,null,t,k)).join(""),j=n(x);return j&&j!==t.href?i(t.href,x):i(t.href)}case"list":return t.items.map((e,n)=>formatToken(e,s,u,t.ordered?t.start+n:null,t,k)).join("");case"list_item":return(t.tokens??[]).map(e=>`${" ".repeat(u)}${formatToken(e,s,u+1,m,t,k)}`).join("");case"paragraph":return(t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join("")+c;case"space":case"br":return c;case"text":return"link"===p?.type?t.text:"list_item"===p?.type?`${null===m?"-":function(e,t){switch(e){case 0:case 1:default:return t.toString();case 2:return function(e){let t="";for(;e>0;)e--,t=String.fromCharCode(97+e%26)+t,e=Math.floor(e/26);return t}(t);case 3:return function(e){let t="";for(const[n,r]of f)for(;e>=n;)t+=r,e-=n;return t}(t)}}(u,m)+"."} ${t.tokens?t.tokens.map(e=>formatToken(e,s,u,m,t,k)).join(""):linkifyIssueReferences(t.text)}${c}`:linkifyIssueReferences(t.text);case"table":{const T=t;function getDisplayText(e){return n(e?.map(e=>formatToken(e,s,0,null,null,k)).join("")??"")}const y=T.header.map((e,t)=>{let n=a(getDisplayText(e.tokens));for(const e of T.rows){const r=a(getDisplayText(e[t]?.tokens));n=Math.max(n,r)}return Math.max(n,3)});let $="| ";return T.header.forEach((e,t)=>{const n=e.tokens?.map(e=>formatToken(e,s,0,null,null,k)).join("")??"",r=getDisplayText(e.tokens),o=y[t],l=T.align?.[t];$+=padAligned(n,a(r),o,l)+" | "}),$=$.trimEnd()+c,$+="|",y.forEach(e=>{const t="-".repeat(e+2);$+=t+"|"}),$+=c,T.rows.forEach(e=>{$+="| ",e.forEach((e,t)=>{const n=e.tokens?.map(e=>formatToken(e,s,0,null,null,k)).join("")??"",r=getDisplayText(e.tokens),o=y[t],l=T.align?.[t];$+=padAligned(n,a(r),o,l)+" | "}),$=$.trimEnd()+c}),$+c}case"escape":return t.text;case"def":case"del":case"html":return""}return""}const p=/(^|[^\w./-])([A-Za-z0-9][\w-]*\/[A-Za-z0-9][\w.-]*)#(\d+)\b/g;function linkifyIssueReferences(e){return s()?e.replace(p,(e,t,n,r)=>t+i(`https://github.com/${n}/issues/${r}`,`${n}#${r}`)):e}const f=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]];export function padAligned(e,t,n,r){const o=Math.max(0,n-t);if("center"===r){const t=Math.floor(o/2);return" ".repeat(t)+e+" ".repeat(o-t)}return"right"===r?" ".repeat(o)+e:e+" ".repeat(o)}
1
+ import e from"chalk";import{marked as t}from"marked";import n from"strip-ansi";import{color as r}from"../components/design-system/color.js";import{BLOCKQUOTE_BAR as o}from"../constants/figures.js";import{stringWidth as a}from"../ink/stringWidth.js";import{supportsHyperlinks as s}from"../ink/supports-hyperlinks.js";import{logForDebugging as i}from"./debug.js";import{createHyperlink as l}from"./hyperlink.js";import{stripPromptXMLTags as u}from"./messages.js";const c="\n";let m=!1;export function configureMarked(){m||(m=!0,t.use({tokenizer:{del(){}}}))}export function applyMarkdown(e,n,r=null){return configureMarked(),t.lexer(u(e)).map(e=>formatToken(e,n,0,null,null,r)).join("").trim()}export function formatToken(t,s,u=0,m=null,p=null,k=null){switch(t.type){case"blockquote":{const g=(t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join(""),h=e.dim(o);return g.split(c).map(t=>n(t).trim()?`${h} ${e.italic(t)}`:t).join(c)}case"code":{if(!k)return t.text+c;let d="plaintext";return t.lang&&(k.supportsLanguage(t.lang)?d=t.lang:i(`Language not supported while highlighting code, falling back to plaintext: ${t.lang}`)),k.highlight(t.text,{language:d})+c}case"codespan":return r("permission",s)(t.text);case"em":return e.italic((t.tokens??[]).map(e=>formatToken(e,s,0,null,p,k)).join(""));case"strong":return e.bold((t.tokens??[]).map(e=>formatToken(e,s,0,null,p,k)).join(""));case"heading":return 1===t.depth?e.bold.italic.underline((t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join(""))+c+c:e.bold((t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join(""))+c+c;case"hr":return"---";case"image":return t.href;case"link":{if(t.href.startsWith("mailto:"))return t.href.replace(/^mailto:/,"");const x=(t.tokens??[]).map(e=>formatToken(e,s,0,null,t,k)).join(""),j=n(x);return j&&j!==t.href?l(t.href,x):l(t.href)}case"list":return t.items.map((e,n)=>formatToken(e,s,u,t.ordered?t.start+n:null,t,k)).join("");case"list_item":return(t.tokens??[]).map(e=>`${" ".repeat(u)}${formatToken(e,s,u+1,m,t,k)}`).join("");case"paragraph":return(t.tokens??[]).map(e=>formatToken(e,s,0,null,null,k)).join("")+c;case"space":case"br":return c;case"text":return"link"===p?.type?t.text:"list_item"===p?.type?`${null===m?"-":function(e,t){switch(e){case 0:case 1:default:return t.toString();case 2:return function(e){let t="";for(;e>0;)e--,t=String.fromCharCode(97+e%26)+t,e=Math.floor(e/26);return t}(t);case 3:return function(e){let t="";for(const[n,r]of f)for(;e>=n;)t+=r,e-=n;return t}(t)}}(u,m)+"."} ${t.tokens?t.tokens.map(e=>formatToken(e,s,u,m,t,k)).join(""):linkifyIssueReferences(t.text)}${c}`:linkifyIssueReferences(t.text);case"table":{const T=t;function getDisplayText(e){return n(e?.map(e=>formatToken(e,s,0,null,null,k)).join("")??"")}const y=T.header.map((e,t)=>{let n=a(getDisplayText(e.tokens));for(const e of T.rows){const r=a(getDisplayText(e[t]?.tokens));n=Math.max(n,r)}return Math.max(n,3)});let $="| ";return T.header.forEach((e,t)=>{const n=e.tokens?.map(e=>formatToken(e,s,0,null,null,k)).join("")??"",r=getDisplayText(e.tokens),o=y[t],i=T.align?.[t];$+=padAligned(n,a(r),o,i)+" | "}),$=$.trimEnd()+c,$+="|",y.forEach(e=>{const t="-".repeat(e+2);$+=t+"|"}),$+=c,T.rows.forEach(e=>{$+="| ",e.forEach((e,t)=>{const n=e.tokens?.map(e=>formatToken(e,s,0,null,null,k)).join("")??"",r=getDisplayText(e.tokens),o=y[t],i=T.align?.[t];$+=padAligned(n,a(r),o,i)+" | "}),$=$.trimEnd()+c}),$+c}case"escape":return t.text;case"def":case"del":case"html":return""}return""}const p=/(^|[^\w./-])([A-Za-z0-9][\w-]*\/[A-Za-z0-9][\w.-]*)#(\d+)\b/g;function linkifyIssueReferences(e){return s()?e.replace(p,(e,t,n,r)=>t+l(`https://github.com/${n}/issues/${r}`,`${n}#${r}`)):e}const f=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]];export function padAligned(e,t,n,r){const o=Math.max(0,n-t);if("center"===r){const t=Math.floor(o/2);return" ".repeat(t)+e+" ".repeat(o-t)}return"right"===r?" ".repeat(o)+e:e+" ".repeat(o)}
@@ -1 +1 @@
1
- import{queryHaiku as t}from"../../services/api/claude.js";import{logError as e}from"../log.js";import{extractTextContent as a}from"../messages.js";import{asSystemPrompt as n}from"../systemPromptType.js";export async function parseNaturalLanguageDateTime(o,r,s){const i=new Date,m=i.toISOString(),u=-i.getTimezoneOffset(),p=Math.floor(Math.abs(u)/60),l=Math.abs(u)%60,d=`${u>=0?"+":"-"}${String(p).padStart(2,"0")}:${String(l).padStart(2,"0")}`,c=i.toLocaleDateString("en-US",{weekday:"long"}),f=n(["You are a date/time parser that converts natural language into ISO 8601 format.","You MUST respond with ONLY the ISO 8601 formatted string, with no explanation or additional text.","If the input is ambiguous, prefer future dates over past dates.","For times without dates, use today's date.","For dates without times, do not include a time component.",'If the input is incomplete or you cannot confidently parse it into a valid date, respond with exactly "INVALID" (nothing else).','Examples of INVALID input: partial dates like "2025-01-", lone numbers like "13", gibberish.','Examples of valid natural language: "tomorrow", "next Monday", "jan 1st 2025", "in 2 hours", "yesterday".']),g=`Current context:\n- Current date and time: ${m} (UTC)\n- Local timezone: ${d}\n- Day of week: ${c}\n\nUser input: "${o}"\n\nOutput format: ${"date"===r?"YYYY-MM-DD (date only, no time)":`YYYY-MM-DDTHH:MM:SS${d} (full date-time with timezone)`}\n\nParse the user's input into ISO 8601 format. Return ONLY the formatted string, or "INVALID" if the input is incomplete or unparseable.`;try{const e=await t({systemPrompt:f,userPrompt:g,signal:s,options:{querySource:"mcp_datetime_parse",agents:[],isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,mcpTools:[],enablePromptCaching:!1}}),n=a(e.message.content).trim();return n&&"INVALID"!==n&&/^\d{4}/.test(n)?{success:!0,value:n}:{success:!1,error:"Unable to parse date/time from input"}}catch(t){return e(t),{success:!1,error:"Unable to parse date/time. Please enter in ISO 8601 format manually."}}}export function looksLikeISO8601(t){return/^\d{4}-\d{2}-\d{2}(T|$)/.test(t.trim())}
1
+ import{queryHaiku as t}from"../../services/api/claude.js";import{logError as e}from"../log.js";import{extractTextContent as a}from"../messages.js";import{asSystemPrompt as o}from"../systemPromptType.js";export async function parseNaturalLanguageDateTime(r,n,s){const i=new Date,m=i.toISOString(),u=-i.getTimezoneOffset(),p=Math.floor(Math.abs(u)/60),l=Math.abs(u)%60,d=`${u>=0?"+":"-"}${String(p).padStart(2,"0")}:${String(l).padStart(2,"0")}`,c=i.toLocaleDateString("en-US",{weekday:"long"}),f=o(["You are a date/time parser that converts natural language into ISO 8601 format.","You MUST respond with ONLY the ISO 8601 formatted string, with no explanation or additional text.","If the input is ambiguous, prefer future dates over past dates.","For times without dates, use today's date.","For dates without times, do not include a time component.",'If the input is incomplete or you cannot confidently parse it into a valid date, respond with exactly "INVALID" (nothing else).','Examples of INVALID input: partial dates like "2025-01-", lone numbers like "13", gibberish.','Examples of valid natural language: "tomorrow", "next Monday", "jan 1st 2025", "in 2 hours", "yesterday".']),g=`Current context:\n- Current date and time: ${m} (UTC)\n- Local timezone: ${d}\n- Day of week: ${c}\n\nUser input: "${r}"\n\nOutput format: ${"date"===n?"YYYY-MM-DD (date only, no time)":`YYYY-MM-DDTHH:MM:SS${d} (full date-time with timezone)`}\n\nParse the user's input into ISO 8601 format. Return ONLY the formatted string, or "INVALID" if the input is incomplete or unparseable.`;try{const e=await t({systemPrompt:f,userPrompt:g,signal:s,options:{querySource:"mcp_datetime_parse",agents:[],isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,mcpTools:[],enablePromptCaching:!1}}),o=a(e.message.content).trim();return o&&"INVALID"!==o&&/^\d{4}/.test(o)?{success:!0,value:o}:{success:!1,error:"Unable to parse date/time from input"}}catch(t){return e(t),{success:!1,error:"Unable to parse date/time. Please enter in ISO 8601 format manually."}}}export function looksLikeISO8601(t){return/^\d{4}-\d{2}-\d{2}(T|$)/.test(t.trim())}
@@ -1 +1 @@
1
- import{writeFile as e}from"fs/promises";import{join as t}from"path";import{logEvent as n}from"../services/analytics/index.js";import{toError as r}from"./errors.js";import{formatFileSize as o}from"./format.js";import{logError as i}from"./log.js";import{ensureToolResultsDir as a,getToolResultsDir as s}from"./toolResultStorage.js";export function getFormatDescription(e,t){switch(e){case"toolResult":return"Plain text";case"structuredContent":return t?`JSON with schema: ${t}`:"JSON";case"contentArray":return t?`JSON array with schema: ${t}`:"JSON array"}}export function getLargeOutputInstructions(e,t,n,r){return`Error: result (${t.toLocaleString()} characters) exceeds maximum allowed tokens. Output has been saved to ${e}.\nFormat: ${n}\nUse offset and limit parameters to read specific portions of the file, search within it for specific content, and jq to make structured queries.\nREQUIREMENTS FOR SUMMARIZATION/ANALYSIS/REVIEW:\n- You MUST read the content from the file at ${e} in sequential chunks until 100% of the content has been read.\n`+(r?`- If you receive truncation warnings when reading the file ("[N lines truncated]"), reduce the chunk size until you have read 100% of the content without truncation ***DO NOT PROCEED UNTIL YOU HAVE DONE THIS***. Bash output is limited to ${r.toLocaleString()} chars.\n`:"- If you receive truncation warnings when reading the file, reduce the chunk size until you have read 100% of the content without truncation.\n")+"- Before producing ANY summary or analysis, you MUST explicitly describe what portion of the content you have read. ***If you did not read the entire content, you MUST explicitly state this.***\n"}export function extensionForMimeType(e){if(!e)return"bin";switch((e.split(";")[0]??"").trim().toLowerCase()){case"application/pdf":return"pdf";case"application/json":return"json";case"text/csv":return"csv";case"text/plain":return"txt";case"text/html":return"html";case"text/markdown":return"md";case"application/zip":return"zip";case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return"docx";case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return"xlsx";case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return"pptx";case"application/msword":return"doc";case"application/vnd.ms-excel":return"xls";case"audio/mpeg":return"mp3";case"audio/wav":return"wav";case"audio/ogg":return"ogg";case"video/mp4":return"mp4";case"video/webm":return"webm";case"image/png":return"png";case"image/jpeg":return"jpg";case"image/gif":return"gif";case"image/webp":return"webp";case"image/svg+xml":return"svg";default:return"bin"}}export function isBinaryContentType(e){if(!e)return!1;const t=(e.split(";")[0]??"").trim().toLowerCase();return!t.startsWith("text/")&&(!t.endsWith("+json")&&"application/json"!==t&&(!t.endsWith("+xml")&&"application/xml"!==t&&(!t.startsWith("application/javascript")&&"application/x-www-form-urlencoded"!==t)))}export async function persistBinaryContent(o,c,u){await a();const p=extensionForMimeType(c),m=t(s(),`${u}.${p}`);try{await e(m,o)}catch(e){const t=r(e);return i(t),{error:t.message}}return n("tengu_binary_content_persisted",{mimeType:c??"unknown",sizeBytes:o.length,ext:p}),{filepath:m,size:o.length,ext:p}}export function getBinaryBlobSavedMessage(e,t,n,r){return`${r}Binary content (${t||"unknown type"}, ${o(n)}) saved to ${e}`}
1
+ import{writeFile as e}from"fs/promises";import{join as t}from"path";import{logEvent as r}from"../services/analytics/index.js";import{toError as n}from"./errors.js";import{formatFileSize as o}from"./format.js";import{logError as i}from"./log.js";import{ensureToolResultsDir as a,getToolResultsDir as s}from"./toolResultStorage.js";export function getFormatDescription(e,t){switch(e){case"toolResult":return"Plain text";case"structuredContent":return t?`JSON with schema: ${t}`:"JSON";case"contentArray":return t?`JSON array with schema: ${t}`:"JSON array"}}export function getLargeOutputInstructions(e,t,r,n){return`Error: result (${t.toLocaleString()} characters) exceeds maximum allowed tokens. Output has been saved to ${e}.\nFormat: ${r}\nUse offset and limit parameters to read specific portions of the file, search within it for specific content, and jq to make structured queries.\nREQUIREMENTS FOR SUMMARIZATION/ANALYSIS/REVIEW:\n- You MUST read the content from the file at ${e} in sequential chunks until 100% of the content has been read.\n`+(n?`- If you receive truncation warnings when reading the file ("[N lines truncated]"), reduce the chunk size until you have read 100% of the content without truncation ***DO NOT PROCEED UNTIL YOU HAVE DONE THIS***. Bash output is limited to ${n.toLocaleString()} chars.\n`:"- If you receive truncation warnings when reading the file, reduce the chunk size until you have read 100% of the content without truncation.\n")+"- Before producing ANY summary or analysis, you MUST explicitly describe what portion of the content you have read. ***If you did not read the entire content, you MUST explicitly state this.***\n"}export function extensionForMimeType(e){if(!e)return"bin";switch((e.split(";")[0]??"").trim().toLowerCase()){case"application/pdf":return"pdf";case"application/json":return"json";case"text/csv":return"csv";case"text/plain":return"txt";case"text/html":return"html";case"text/markdown":return"md";case"application/zip":return"zip";case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return"docx";case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return"xlsx";case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return"pptx";case"application/msword":return"doc";case"application/vnd.ms-excel":return"xls";case"audio/mpeg":return"mp3";case"audio/wav":return"wav";case"audio/ogg":return"ogg";case"video/mp4":return"mp4";case"video/webm":return"webm";case"image/png":return"png";case"image/jpeg":return"jpg";case"image/gif":return"gif";case"image/webp":return"webp";case"image/svg+xml":return"svg";default:return"bin"}}export function isBinaryContentType(e){if(!e)return!1;const t=(e.split(";")[0]??"").trim().toLowerCase();return!(t.startsWith("text/")||t.endsWith("+json")||"application/json"===t||t.endsWith("+xml")||"application/xml"===t||t.startsWith("application/javascript")||"application/x-www-form-urlencoded"===t)}export async function persistBinaryContent(o,c,u){await a();const p=extensionForMimeType(c),m=t(s(),`${u}.${p}`);try{await e(m,o)}catch(e){const t=n(e);return i(t),{error:t.message}}return r("tengu_binary_content_persisted",{mimeType:c??"unknown",sizeBytes:o.length,ext:p}),{filepath:m,size:o.length,ext:p}}export function getBinaryBlobSavedMessage(e,t,r,n){return`${n}Binary content (${t||"unknown type"}, ${o(r)}) saved to ${e}`}
@@ -1 +1 @@
1
- import{getFeatureValue_CACHED_MAY_BE_STALE as t}from"../services/analytics/growthbook.js";import{countMessagesTokensWithAPI as e,roughTokenCountEstimation as n}from"../services/tokenEstimation.js";import{compressImageBlock as o}from"./imageResizer.js";import{logError as r}from"./log.js";export const MCP_TOKEN_COUNT_THRESHOLD_FACTOR=.5;export const IMAGE_TOKEN_ESTIMATE=1600;export function getMaxMcpOutputTokens(){const e=process.env.MAX_MCP_OUTPUT_TOKENS;if(e){const t=parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}const n=t("tengu_satin_quoll",{}),o=n?.mcp_tool;return"number"==typeof o&&Number.isFinite(o)&&o>0?o:25e3}function isTextBlock(t){return"text"===t.type}function isImageBlock(t){return"image"===t.type}export function getContentSizeEstimate(t){return t?"string"==typeof t?n(t):t.reduce((t,e)=>isTextBlock(e)?t+n(e.text):isImageBlock(e)?t+1600:t,0):0}export async function mcpContentNeedsTruncation(t){if(!t)return!1;if(getContentSizeEstimate(t)<=.5*getMaxMcpOutputTokens())return!1;try{const n=[{role:"user",content:t}],o=await e(n,[]);return!!(o&&o>getMaxMcpOutputTokens())}catch(t){return r(t),!1}}export async function truncateMcpContent(t){if(!t)return t;const e=4*getMaxMcpOutputTokens(),n=`\n\n[OUTPUT TRUNCATED - exceeded ${getMaxMcpOutputTokens()} token limit]\n\nThe tool output was truncated. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data. If pagination is not available, inform the user that you are working with truncated output and results may be incomplete.`;if("string"==typeof t)return function(t,e){return t.length<=e?t:t.slice(0,e)}(t,e)+n;{const r=await async function(t,e){const n=[];let r=0;for(const i of t)if(isTextBlock(i)){const t=e-r;if(t<=0)break;if(!(i.text.length<=t)){n.push({type:"text",text:i.text.slice(0,t)});break}n.push(i),r+=i.text.length}else if(isImageBlock(i)){const t=6400;if(r+t<=e)n.push(i),r+=t;else{const s=e-r;if(s>0){const e=Math.floor(.75*s);try{const s=await o(i,e);n.push(s),"base64"===s.source.type?r+=s.source.data.length:r+=t}catch{}}}}else n.push(i);return n}(t,e);return r.push({type:"text",text:n}),r}}export async function truncateMcpContentIfNeeded(t){return await mcpContentNeedsTruncation(t)?await truncateMcpContent(t):t}
1
+ import{getFeatureValue_CACHED_MAY_BE_STALE as t}from"../services/analytics/growthbook.js";import{countMessagesTokensWithAPI as e,roughTokenCountEstimation as n}from"../services/tokenEstimation.js";import{compressImageBlock as o}from"./imageResizer.js";import{logError as r}from"./log.js";export const MCP_TOKEN_COUNT_THRESHOLD_FACTOR=.5;export const IMAGE_TOKEN_ESTIMATE=1600;export function getMaxMcpOutputTokens(){const e=process.env.MAX_MCP_OUTPUT_TOKENS;if(e){const t=parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}const n=t("tengu_satin_quoll",{}),o=n?.mcp_tool;return"number"==typeof o&&Number.isFinite(o)&&o>0?o:25e3}function isTextBlock(t){return"text"===t.type}function isImageBlock(t){return"image"===t.type}export function getContentSizeEstimate(t){return t?"string"==typeof t?n(t):t.reduce((t,e)=>isTextBlock(e)?t+n(e.text):isImageBlock(e)?t+1600:t,0):0}export async function mcpContentNeedsTruncation(t){if(!t)return!1;if(getContentSizeEstimate(t)<=.5*getMaxMcpOutputTokens())return!1;try{const n=[{role:"user",content:t}],o=await e(n,[]);return!!(o&&o>getMaxMcpOutputTokens())}catch(t){return r(t),!1}}export async function truncateMcpContent(t){if(!t)return t;const e=4*getMaxMcpOutputTokens(),n=`\n\n[OUTPUT TRUNCATED - exceeded ${getMaxMcpOutputTokens()} token limit]\n\nThe tool output was truncated. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data. If pagination is not available, inform the user that you are working with truncated output and results may be incomplete.`;if("string"==typeof t)return function(t,e){return t.length<=e?t:t.slice(0,e)}(t,e)+n;{const r=await async function(t,e){const n=[];let r=0;for(const s of t)if(isTextBlock(s)){const t=e-r;if(t<=0)break;if(!(s.text.length<=t)){n.push({type:"text",text:s.text.slice(0,t)});break}n.push(s),r+=s.text.length}else if(isImageBlock(s)){const t=6400;if(r+t<=e)n.push(s),r+=t;else{const i=e-r;if(i>0){const e=Math.floor(.75*i);try{const i=await o(s,e);n.push(i),"base64"===i.source.type?r+=i.source.data.length:r+=t}catch{}}}}else n.push(s);return n}(t,e);return r.push({type:"text",text:n}),r}}export async function truncateMcpContentIfNeeded(t){return await mcpContentNeedsTruncation(t)?await truncateMcpContent(t):t}
@@ -1 +1 @@
1
- import{LRUCache as e}from"lru-cache";import{logError as t}from"./log.js";import{jsonStringify as r}from"./slowOperations.js";export function memoizeWithTTL(e,n=3e5){const s=new Map,memoized=(...a)=>{const i=r(a),o=s.get(i),c=Date.now();if(!o){const t=e(...a);return s.set(i,{value:t,timestamp:c,refreshing:!1}),t}return o&&c-o.timestamp>n&&!o.refreshing?(o.refreshing=!0,Promise.resolve().then(()=>{const t=e(...a);s.get(i)===o&&s.set(i,{value:t,timestamp:Date.now(),refreshing:!1})}).catch(e=>{t(e),s.get(i)===o&&s.delete(i)}),o.value):s.get(i).value};return memoized.cache={clear:()=>s.clear()},memoized}export function memoizeWithTTLAsync(e,n=3e5){const s=new Map,a=new Map,memoized=async(...i)=>{const o=r(i),c=s.get(o),l=Date.now();if(!c){const t=a.get(o);if(t)return t;const r=e(...i);a.set(o,r);try{const e=await r;return a.get(o)===r&&s.set(o,{value:e,timestamp:l,refreshing:!1}),e}finally{a.get(o)===r&&a.delete(o)}}if(c&&l-c.timestamp>n&&!c.refreshing){c.refreshing=!0;const r=c;return e(...i).then(e=>{s.get(o)===r&&s.set(o,{value:e,timestamp:Date.now(),refreshing:!1})}).catch(e=>{t(e),s.get(o)===r&&s.delete(o)}),c.value}return s.get(o).value};return memoized.cache={clear:()=>{s.clear(),a.clear()}},memoized}export function memoizeWithLRU(t,r,n=100){const s=new e({max:n}),memoized=(...e)=>{const n=r(...e),a=s.get(n);if(void 0!==a)return a;const i=t(...e);return s.set(n,i),i};return memoized.cache={clear:()=>s.clear(),size:()=>s.size,delete:e=>s.delete(e),get:e=>s.peek(e),has:e=>s.has(e)},memoized}
1
+ import{LRUCache as e}from"lru-cache";import{logError as t}from"./log.js";import{jsonStringify as r}from"./slowOperations.js";export function memoizeWithTTL(e,n=3e5){const s=new Map,memoized=(...a)=>{const o=r(a),i=s.get(o),c=Date.now();if(!i){const t=e(...a);return s.set(o,{value:t,timestamp:c,refreshing:!1}),t}return i&&c-i.timestamp>n&&!i.refreshing?(i.refreshing=!0,Promise.resolve().then(()=>{const t=e(...a);s.get(o)===i&&s.set(o,{value:t,timestamp:Date.now(),refreshing:!1})}).catch(e=>{t(e),s.get(o)===i&&s.delete(o)}),i.value):s.get(o).value};return memoized.cache={clear:()=>s.clear()},memoized}export function memoizeWithTTLAsync(e,n=3e5){const s=new Map,a=new Map,memoized=async(...o)=>{const i=r(o),c=s.get(i),l=Date.now();if(!c){const t=a.get(i);if(t)return t;const r=e(...o);a.set(i,r);try{const e=await r;return a.get(i)===r&&s.set(i,{value:e,timestamp:l,refreshing:!1}),e}finally{a.get(i)===r&&a.delete(i)}}if(c&&l-c.timestamp>n&&!c.refreshing){c.refreshing=!0;const r=c;return e(...o).then(e=>{s.get(i)===r&&s.set(i,{value:e,timestamp:Date.now(),refreshing:!1})}).catch(e=>{t(e),s.get(i)===r&&s.delete(i)}),c.value}return s.get(i).value};return memoized.cache={clear:()=>{s.clear(),a.clear()}},memoized}export function memoizeWithLRU(t,r,n=100){const s=new e({max:n}),memoized=(...e)=>{const n=r(...e),a=s.get(n);if(void 0!==a)return a;const o=t(...e);return s.set(n,o),o};return memoized.cache={clear:()=>s.clear(),size:()=>s.size,delete:e=>s.delete(e),get:e=>s.peek(e),has:e=>s.has(e)},memoized}
@@ -1 +1 @@
1
- import{feature as e}from"../../recovery/bunBundleShim.js";export const MEMORY_TYPE_VALUES=["User","Project","Local","Managed","AutoMem",...e("TEAMMEM")?["TeamMem"]:[]];
1
+ import{feature as e}from"bun:bundle";export const MEMORY_TYPE_VALUES=["User","Project","Local","Managed","AutoMem",...e("TEAMMEM")?["TeamMem"]:[]];
@@ -1 +1 @@
1
- import{feature as e}from"../recovery/bunBundleShim.js";import{createRequire as o}from"module";const t=o(import.meta.url);import{normalize as r,posix as n,win32 as s}from"path";import{getAutoMemPath as i,getMemoryBaseDir as m,isAutoMemoryEnabled as l,isAutoMemPath as a}from"../memdir/paths.js";import{isAgentMemoryPath as c}from"../tools/AgentTool/agentMemory.js";import{getClaudeConfigHomeDir as u}from"./envUtils.js";import{posixPathToWindowsPath as p,windowsPathToPosixPath as d}from"./windowsPaths.js";const M=e("TEAMMEM")?t("../memdir/teamMemPaths.js"):null,f="win32"===process.platform;function toComparable(e){const o=function(e){return e.split(s.sep).join(n.sep)}(e);return f?o.toLowerCase():o}export function detectSessionFileType(e){const o=u(),t=toComparable(e),r=toComparable(o);return t.startsWith(r)?t.includes("/session-memory/")&&t.endsWith(".md")?"session_memory":t.includes("/projects/")&&t.endsWith(".jsonl")?"session_transcript":null:null}export function detectSessionPatternType(e){const o=e.split(s.sep).join(n.sep);return o.includes("session-memory")&&(o.includes(".md")||o.endsWith("*"))?"session_memory":o.includes(".jsonl")||o.includes("projects")&&o.includes("*.jsonl")?"session_transcript":null}export function isAutoMemFile(e){return!!l()&&a(e)}export function memoryScopeForPath(o){return e("TEAMMEM")&&M.isTeamMemFile(o)?"team":isAutoMemFile(o)?"personal":null}export function isAutoManagedMemoryFile(o){return!!isAutoMemFile(o)||(!(!e("TEAMMEM")||!M.isTeamMemFile(o))||(null!==detectSessionFileType(o)||!!function(e){return!!l()&&c(e)}(o)))}export function isMemoryDirectory(o){const t=r(o),n=toComparable(t);if(l()&&(n.includes("/agent-memory/")||n.includes("/agent-memory-local/")))return!0;if(e("TEAMMEM")&&M.isTeamMemoryEnabled()&&M.isTeamMemPath(t))return!0;if(l()){const e=i(),o=toComparable(e.replace(/[/\\]+$/,"")),t=toComparable(e);if(n===o||n.startsWith(t))return!0}const s=toComparable(u()),a=toComparable(m()),c=n.startsWith(s),p=n.startsWith(a);return!(!c&&!p)&&(!!n.includes("/session-memory/")||(!(!c||!n.includes("/projects/"))||!(!l()||!n.includes("/memory/"))))}export function isShellCommandTargetingMemory(e){const o=u(),t=m(),r=l()?i().replace(/[/\\]+$/,""):"",n=toComparable(e);if(![o,t,r].filter(Boolean).some(e=>!!n.includes(toComparable(e))||!!f&&n.includes(d(e).toLowerCase())))return!1;const s=e.match(/(?:[A-Za-z]:[/\\]|\/)[^\s'"]+/g);if(!s)return!1;for(const e of s){const o=e.replace(/[,;|&>]+$/,""),t=f?p(o):o;if(isAutoManagedMemoryFile(t)||isMemoryDirectory(t))return!0}return!1}export function isAutoManagedMemoryPattern(e){return null!==detectSessionPatternType(e)||!(!l()||!e.replace(/\\/g,"/").includes("agent-memory/")&&!e.replace(/\\/g,"/").includes("agent-memory-local/"))}
1
+ import{createRequire as e}from"module";const o=e(import.meta.url);import{feature as t}from"bun:bundle";import{normalize as s,posix as r,win32 as n}from"path";import{getAutoMemPath as i,getMemoryBaseDir as a,isAutoMemoryEnabled as m,isAutoMemPath as l}from"../memdir/paths.js";import{isAgentMemoryPath as u}from"../tools/AgentTool/agentMemory.js";import{getClaudeConfigHomeDir as c}from"./envUtils.js";import{posixPathToWindowsPath as p,windowsPathToPosixPath as d}from"./windowsPaths.js";const M=t("TEAMMEM")?o("../memdir/teamMemPaths.js"):null,f="win32"===process.platform;function toComparable(e){const o=function(e){return e.split(n.sep).join(r.sep)}(e);return f?o.toLowerCase():o}export function detectSessionFileType(e){const o=c(),t=toComparable(e),s=toComparable(o);return t.startsWith(s)?t.includes("/session-memory/")&&t.endsWith(".md")?"session_memory":t.includes("/projects/")&&t.endsWith(".jsonl")?"session_transcript":null:null}export function detectSessionPatternType(e){const o=e.split(n.sep).join(r.sep);return o.includes("session-memory")&&(o.includes(".md")||o.endsWith("*"))?"session_memory":o.includes(".jsonl")||o.includes("projects")&&o.includes("*.jsonl")?"session_transcript":null}export function isAutoMemFile(e){return!!m()&&l(e)}export function memoryScopeForPath(e){return t("TEAMMEM")&&M.isTeamMemFile(e)?"team":isAutoMemFile(e)?"personal":null}export function isAutoManagedMemoryFile(e){return!!isAutoMemFile(e)||!(!t("TEAMMEM")||!M.isTeamMemFile(e))||null!==detectSessionFileType(e)||!!function(e){return!!m()&&u(e)}(e)}export function isMemoryDirectory(e){const o=s(e),r=toComparable(o);if(m()&&(r.includes("/agent-memory/")||r.includes("/agent-memory-local/")))return!0;if(t("TEAMMEM")&&M.isTeamMemoryEnabled()&&M.isTeamMemPath(o))return!0;if(m()){const e=i(),o=toComparable(e.replace(/[/\\]+$/,"")),t=toComparable(e);if(r===o||r.startsWith(t))return!0}const n=toComparable(c()),l=toComparable(a()),u=r.startsWith(n),p=r.startsWith(l);return!!((u||p)&&(r.includes("/session-memory/")||u&&r.includes("/projects/")||m()&&r.includes("/memory/")))}export function isShellCommandTargetingMemory(e){const o=c(),t=a(),s=m()?i().replace(/[/\\]+$/,""):"",r=toComparable(e);if(![o,t,s].filter(Boolean).some(e=>!!r.includes(toComparable(e))||!!f&&r.includes(d(e).toLowerCase())))return!1;const n=e.match(/(?:[A-Za-z]:[/\\]|\/)[^\s'"]+/g);if(!n)return!1;for(const e of n){const o=e.replace(/[,;|&>]+$/,""),t=f?p(o):o;if(isAutoManagedMemoryFile(t)||isMemoryDirectory(t))return!0}return!1}export function isAutoManagedMemoryPattern(e){return null!==detectSessionPatternType(e)||!(!m()||!e.replace(/\\/g,"/").includes("agent-memory/")&&!e.replace(/\\/g,"/").includes("agent-memory-local/"))}
@@ -1 +1 @@
1
- import{feature as e}from"../recovery/bunBundleShim.js";import{getSessionId as t}from"../bootstrap/state.js";import{extractTextContent as n}from"./messages.js";import{objectGroupBy as o}from"./objectGroupBy.js";import{recordQueueOperation as r}from"./sessionStorage.js";import{createSignal as i}from"./signal.js";function logOperation(e,n){const o=t(),i={type:"queue-operation",operation:e,timestamp:(new Date).toISOString(),sessionId:o,...void 0!==n&&{content:n}};r(i)}const u=[];let s=Object.freeze([]);const c=i();function notifySubscribers(){s=Object.freeze([...u]),c.emit()}export const subscribeToCommandQueue=c.subscribe;export function getCommandQueueSnapshot(){return s}export function getCommandQueue(){return[...u]}export function getCommandQueueLength(){return u.length}export function hasCommandsInQueue(){return u.length>0}export function recheckCommandQueue(){u.length>0&&notifySubscribers()}export function enqueue(e){u.push({...e,priority:e.priority??"next"}),notifySubscribers(),logOperation("enqueue","string"==typeof e.value?e.value:void 0)}export function enqueuePendingNotification(e){u.push({...e,priority:e.priority??"later"}),notifySubscribers(),logOperation("enqueue","string"==typeof e.value?e.value:void 0)}const a={now:0,next:1,later:2};export function dequeue(e){if(0===u.length)return;let t=-1,n=1/0;for(let o=0;o<u.length;o++){const r=u[o];if(e&&!e(r))continue;const i=a[r.priority??"next"];i<n&&(t=o,n=i)}if(-1===t)return;const[o]=u.splice(t,1);return notifySubscribers(),logOperation("dequeue"),o}export function dequeueAll(){if(0===u.length)return[];const e=[...u];u.length=0,notifySubscribers();for(const t of e)logOperation("dequeue");return e}export function peek(e){if(0===u.length)return;let t=-1,n=1/0;for(let o=0;o<u.length;o++){const r=u[o];if(e&&!e(r))continue;const i=a[r.priority??"next"];i<n&&(t=o,n=i)}return-1!==t?u[t]:void 0}export function dequeueAllMatching(e){const t=[],n=[];for(const o of u)e(o)?t.push(o):n.push(o);if(0===t.length)return[];u.length=0,u.push(...n),notifySubscribers();for(const e of t)logOperation("dequeue");return t}export function remove(e){if(0===e.length)return;const t=u.length;for(let t=u.length-1;t>=0;t--)e.includes(u[t])&&u.splice(t,1);u.length!==t&&notifySubscribers();for(const t of e)logOperation("remove")}export function removeByFilter(e){const t=[];for(let n=u.length-1;n>=0;n--)e(u[n])&&t.unshift(u.splice(n,1)[0]);if(t.length>0){notifySubscribers();for(const e of t)logOperation("remove")}return t}export function clearCommandQueue(){0!==u.length&&(u.length=0,notifySubscribers())}export function resetCommandQueue(){u.length=0,s=Object.freeze([])}const f=new Set(["task-notification"]);export function isPromptInputModeEditable(e){return!f.has(e)}export function isQueuedCommandEditable(e){return isPromptInputModeEditable(e.mode)&&!e.isMeta}export function isQueuedCommandVisible(t){return!(!e("KAIROS")&&!e("KAIROS_CHANNELS")||"channel"!==t.origin?.kind)||isQueuedCommandEditable(t)}function extractImagesFromValue(e,t){if("string"==typeof e)return[];const n=[];let o=0;for(const r of e)"image"===r.type&&"base64"===r.source.type&&(n.push({id:t+o,type:"image",content:r.source.data,mediaType:r.source.media_type,filename:`image${o+1}`}),o++);return n}export function popAllEditable(e,t){if(0===u.length)return;const{editable:r=[],nonEditable:i=[]}=o([...u],e=>isQueuedCommandEditable(e)?"editable":"nonEditable");if(0===r.length)return;const s=r.map(e=>{return"string"==typeof(t=e.value)?t:n(t,"\n");var t}),c=[...s,e].filter(Boolean).join("\n"),a=s.join("\n").length+1+t,f=[];let p=Date.now();for(const e of r){if(e.pastedContents)for(const t of Object.values(e.pastedContents))"image"===t.type&&f.push(t);const t=extractImagesFromValue(e.value,p);f.push(...t),p+=t.length}for(const e of r)logOperation("popAll","string"==typeof e.value?e.value:void 0);return u.length=0,u.push(...i),notifySubscribers(),{text:c,cursorOffset:a,images:f}}export const subscribeToPendingNotifications=subscribeToCommandQueue;export function getPendingNotificationsSnapshot(){return s}export const hasPendingNotifications=hasCommandsInQueue;export const getPendingNotificationsCount=getCommandQueueLength;export const recheckPendingNotifications=recheckCommandQueue;export function dequeuePendingNotification(){return dequeue()}export const resetPendingNotifications=resetCommandQueue;export const clearPendingNotifications=clearCommandQueue;export function getCommandsByMaxPriority(e){const t=a[e];return u.filter(e=>a[e.priority??"next"]<=t)}export function isSlashCommand(e){return"string"==typeof e.value&&e.value.trim().startsWith("/")&&!e.skipSlashCommands}
1
+ import{feature as e}from"bun:bundle";import{getSessionId as t}from"../bootstrap/state.js";import{extractTextContent as n}from"./messages.js";import{objectGroupBy as o}from"./objectGroupBy.js";import{recordQueueOperation as r}from"./sessionStorage.js";import{createSignal as i}from"./signal.js";function logOperation(e,n){const o=t(),i={type:"queue-operation",operation:e,timestamp:(new Date).toISOString(),sessionId:o,...void 0!==n&&{content:n}};r(i)}const u=[];let s=Object.freeze([]);const a=i();function notifySubscribers(){s=Object.freeze([...u]),a.emit()}export const subscribeToCommandQueue=a.subscribe;export function getCommandQueueSnapshot(){return s}export function getCommandQueue(){return[...u]}export function getCommandQueueLength(){return u.length}export function hasCommandsInQueue(){return u.length>0}export function recheckCommandQueue(){u.length>0&&notifySubscribers()}export function enqueue(e){u.push({...e,priority:e.priority??"next"}),notifySubscribers(),logOperation("enqueue","string"==typeof e.value?e.value:void 0)}export function enqueuePendingNotification(e){u.push({...e,priority:e.priority??"later"}),notifySubscribers(),logOperation("enqueue","string"==typeof e.value?e.value:void 0)}const c={now:0,next:1,later:2};export function dequeue(e){if(0===u.length)return;let t=-1,n=1/0;for(let o=0;o<u.length;o++){const r=u[o];if(e&&!e(r))continue;const i=c[r.priority??"next"];i<n&&(t=o,n=i)}if(-1===t)return;const[o]=u.splice(t,1);return notifySubscribers(),logOperation("dequeue"),o}export function dequeueAll(){if(0===u.length)return[];const e=[...u];u.length=0,notifySubscribers();for(const t of e)logOperation("dequeue");return e}export function peek(e){if(0===u.length)return;let t=-1,n=1/0;for(let o=0;o<u.length;o++){const r=u[o];if(e&&!e(r))continue;const i=c[r.priority??"next"];i<n&&(t=o,n=i)}return-1!==t?u[t]:void 0}export function dequeueAllMatching(e){const t=[],n=[];for(const o of u)e(o)?t.push(o):n.push(o);if(0===t.length)return[];u.length=0,u.push(...n),notifySubscribers();for(const e of t)logOperation("dequeue");return t}export function remove(e){if(0===e.length)return;const t=u.length;for(let t=u.length-1;t>=0;t--)e.includes(u[t])&&u.splice(t,1);u.length!==t&&notifySubscribers();for(const t of e)logOperation("remove")}export function removeByFilter(e){const t=[];for(let n=u.length-1;n>=0;n--)e(u[n])&&t.unshift(u.splice(n,1)[0]);if(t.length>0){notifySubscribers();for(const e of t)logOperation("remove")}return t}export function clearCommandQueue(){0!==u.length&&(u.length=0,notifySubscribers())}export function resetCommandQueue(){u.length=0,s=Object.freeze([])}const f=new Set(["task-notification"]);export function isPromptInputModeEditable(e){return!f.has(e)}export function isQueuedCommandEditable(e){return isPromptInputModeEditable(e.mode)&&!e.isMeta}export function isQueuedCommandVisible(t){return!(!e("KAIROS")&&!e("KAIROS_CHANNELS")||"channel"!==t.origin?.kind)||isQueuedCommandEditable(t)}function extractImagesFromValue(e,t){if("string"==typeof e)return[];const n=[];let o=0;for(const r of e)"image"===r.type&&"base64"===r.source.type&&(n.push({id:t+o,type:"image",content:r.source.data,mediaType:r.source.media_type,filename:`image${o+1}`}),o++);return n}export function popAllEditable(e,t){if(0===u.length)return;const{editable:r=[],nonEditable:i=[]}=o([...u],e=>isQueuedCommandEditable(e)?"editable":"nonEditable");if(0===r.length)return;const s=r.map(e=>{return"string"==typeof(t=e.value)?t:n(t,"\n");var t}),a=[...s,e].filter(Boolean).join("\n"),c=s.join("\n").length+1+t,f=[];let p=Date.now();for(const e of r){if(e.pastedContents)for(const t of Object.values(e.pastedContents))"image"===t.type&&f.push(t);const t=extractImagesFromValue(e.value,p);f.push(...t),p+=t.length}for(const e of r)logOperation("popAll","string"==typeof e.value?e.value:void 0);return u.length=0,u.push(...i),notifySubscribers(),{text:a,cursorOffset:c,images:f}}export const subscribeToPendingNotifications=subscribeToCommandQueue;export function getPendingNotificationsSnapshot(){return s}export const hasPendingNotifications=hasCommandsInQueue;export const getPendingNotificationsCount=getCommandQueueLength;export const recheckPendingNotifications=recheckCommandQueue;export function dequeuePendingNotification(){return dequeue()}export const resetPendingNotifications=resetCommandQueue;export const clearPendingNotifications=clearCommandQueue;export function getCommandsByMaxPriority(e){const t=c[e];return u.filter(e=>c[e.priority??"next"]<=t)}export function isSlashCommand(e){return"string"==typeof e.value&&e.value.trim().startsWith("/")&&!e.skipSlashCommands}
@@ -1 +1 @@
1
- import{randomUUID as t}from"crypto";import{getSessionId as e}from"../../bootstrap/state.js";import{LOCAL_COMMAND_STDERR_TAG as s,LOCAL_COMMAND_STDOUT_TAG as a}from"../../constants/xml.js";import{EXIT_PLAN_MODE_V2_TOOL_NAME as o}from"../../tools/ExitPlanModeTool/constants.js";import r from"strip-ansi";import{createAssistantMessage as i}from"../messages.js";import{getPlan as n}from"../plans.js";export function toInternalMessages(e){return e.flatMap(e=>{switch(e.type){case"assistant":return[{type:"assistant",message:e.message,uuid:e.uuid,requestId:void 0,timestamp:(new Date).toISOString()}];case"user":return[{type:"user",message:e.message,uuid:e.uuid??t(),timestamp:e.timestamp??(new Date).toISOString(),isMeta:e.isSynthetic}];case"system":if("compact_boundary"===e.subtype){return[{type:"system",content:"Conversation compacted",level:"info",subtype:"compact_boundary",compactMetadata:fromSDKCompactMetadata(e.compact_metadata),uuid:e.uuid,timestamp:(new Date).toISOString()}]}return[];default:return[]}})}export function toSDKCompactMetadata(t){const e=t.preservedSegment;return{trigger:t.trigger,pre_tokens:t.preTokens,...e&&{preserved_segment:{head_uuid:e.headUuid,anchor_uuid:e.anchorUuid,tail_uuid:e.tailUuid}}}}export function fromSDKCompactMetadata(t){const e=t.preserved_segment;return{trigger:t.trigger,preTokens:t.pre_tokens,...e&&{preservedSegment:{headUuid:e.head_uuid,anchorUuid:e.anchor_uuid,tailUuid:e.tail_uuid}}}}export function toSDKMessages(t){return t.flatMap(t=>{switch(t.type){case"assistant":return[{type:"assistant",message:normalizeAssistantMessageForSDK(t),session_id:e(),parent_tool_use_id:null,uuid:t.uuid,error:t.error}];case"user":return[{type:"user",message:t.message,session_id:e(),parent_tool_use_id:null,uuid:t.uuid,timestamp:t.timestamp,isSynthetic:t.isMeta||t.isVisibleInTranscriptOnly,...void 0!==t.toolUseResult?{tool_use_result:t.toolUseResult}:{}}];case"system":return"compact_boundary"===t.subtype&&t.compactMetadata?[{type:"system",subtype:"compact_boundary",session_id:e(),uuid:t.uuid,compact_metadata:toSDKCompactMetadata(t.compactMetadata)}]:"local_command"===t.subtype&&(t.content.includes(`<${a}>`)||t.content.includes(`<${s}>`))?[localCommandOutputToSDKAssistantMessage(t.content,t.uuid)]:[];default:return[]}})}export function localCommandOutputToSDKAssistantMessage(t,s){const a=r(t).replace(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/,"$1").replace(/<local-command-stderr>([\s\S]*?)<\/local-command-stderr>/,"$1").trim();return{type:"assistant",message:i({content:a}).message,parent_tool_use_id:null,session_id:e(),uuid:s}}export function toSDKRateLimitInfo(t){if(t)return{status:t.status,...void 0!==t.resetsAt&&{resetsAt:t.resetsAt},...void 0!==t.rateLimitType&&{rateLimitType:t.rateLimitType},...void 0!==t.utilization&&{utilization:t.utilization},...void 0!==t.overageStatus&&{overageStatus:t.overageStatus},...void 0!==t.overageResetsAt&&{overageResetsAt:t.overageResetsAt},...void 0!==t.overageDisabledReason&&{overageDisabledReason:t.overageDisabledReason},...void 0!==t.isUsingOverage&&{isUsingOverage:t.isUsingOverage},...void 0!==t.surpassedThreshold&&{surpassedThreshold:t.surpassedThreshold}}}function normalizeAssistantMessageForSDK(t){const e=t.message.content;if(!Array.isArray(e))return t.message;const s=e.map(t=>{if("tool_use"!==t.type)return t;if(t.name===o){const e=n();if(e)return{...t,input:{...t.input,plan:e}}}return t});return{...t.message,content:s}}
1
+ import{randomUUID as e}from"crypto";import{getSessionId as t}from"src/bootstrap/state.js";import{LOCAL_COMMAND_STDERR_TAG as s,LOCAL_COMMAND_STDOUT_TAG as a}from"src/constants/xml.js";import{EXIT_PLAN_MODE_V2_TOOL_NAME as o}from"src/tools/ExitPlanModeTool/constants.js";import r from"strip-ansi";import{createAssistantMessage as i}from"../messages.js";import{getPlan as n}from"../plans.js";export function toInternalMessages(t){return t.flatMap(t=>{switch(t.type){case"assistant":return[{type:"assistant",message:t.message,uuid:t.uuid,requestId:void 0,timestamp:(new Date).toISOString()}];case"user":return[{type:"user",message:t.message,uuid:t.uuid??e(),timestamp:t.timestamp??(new Date).toISOString(),isMeta:t.isSynthetic}];case"system":return"compact_boundary"===t.subtype?[{type:"system",content:"Conversation compacted",level:"info",subtype:"compact_boundary",compactMetadata:fromSDKCompactMetadata(t.compact_metadata),uuid:t.uuid,timestamp:(new Date).toISOString()}]:[];default:return[]}})}export function toSDKCompactMetadata(e){const t=e.preservedSegment;return{trigger:e.trigger,pre_tokens:e.preTokens,...t&&{preserved_segment:{head_uuid:t.headUuid,anchor_uuid:t.anchorUuid,tail_uuid:t.tailUuid}}}}export function fromSDKCompactMetadata(e){const t=e.preserved_segment;return{trigger:e.trigger,preTokens:e.pre_tokens,...t&&{preservedSegment:{headUuid:t.head_uuid,anchorUuid:t.anchor_uuid,tailUuid:t.tail_uuid}}}}export function toSDKMessages(e){return e.flatMap(e=>{switch(e.type){case"assistant":return[{type:"assistant",message:normalizeAssistantMessageForSDK(e),session_id:t(),parent_tool_use_id:null,uuid:e.uuid,error:e.error}];case"user":return[{type:"user",message:e.message,session_id:t(),parent_tool_use_id:null,uuid:e.uuid,timestamp:e.timestamp,isSynthetic:e.isMeta||e.isVisibleInTranscriptOnly,...void 0!==e.toolUseResult?{tool_use_result:e.toolUseResult}:{}}];case"system":return"compact_boundary"===e.subtype&&e.compactMetadata?[{type:"system",subtype:"compact_boundary",session_id:t(),uuid:e.uuid,compact_metadata:toSDKCompactMetadata(e.compactMetadata)}]:"local_command"===e.subtype&&(e.content.includes(`<${a}>`)||e.content.includes(`<${s}>`))?[localCommandOutputToSDKAssistantMessage(e.content,e.uuid)]:[];default:return[]}})}export function localCommandOutputToSDKAssistantMessage(e,s){const a=r(e).replace(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/,"$1").replace(/<local-command-stderr>([\s\S]*?)<\/local-command-stderr>/,"$1").trim();return{type:"assistant",message:i({content:a}).message,parent_tool_use_id:null,session_id:t(),uuid:s}}export function toSDKRateLimitInfo(e){if(e)return{status:e.status,...void 0!==e.resetsAt&&{resetsAt:e.resetsAt},...void 0!==e.rateLimitType&&{rateLimitType:e.rateLimitType},...void 0!==e.utilization&&{utilization:e.utilization},...void 0!==e.overageStatus&&{overageStatus:e.overageStatus},...void 0!==e.overageResetsAt&&{overageResetsAt:e.overageResetsAt},...void 0!==e.overageDisabledReason&&{overageDisabledReason:e.overageDisabledReason},...void 0!==e.isUsingOverage&&{isUsingOverage:e.isUsingOverage},...void 0!==e.surpassedThreshold&&{surpassedThreshold:e.surpassedThreshold}}}function normalizeAssistantMessageForSDK(e){const t=e.message.content;if(!Array.isArray(t))return e.message;const s=t.map(e=>{if("tool_use"!==e.type)return e;if(e.name===o){const t=n();if(t)return{...e,input:{...e.input,plan:t}}}return e});return{...e.message,content:s}}
@@ -1 +1 @@
1
- import{MACRO as s,feature as t}from"../../recovery/bunBundleShim.js";import{createRequire as o}from"module";const e=o(import.meta.url);import{randomUUID as m}from"crypto";import{getSdkBetas as a,getSessionId as r}from"../../bootstrap/state.js";import{DEFAULT_OUTPUT_STYLE_NAME as n}from"../../constants/outputStyles.js";import{AGENT_TOOL_NAME as p,LEGACY_AGENT_TOOL_NAME as i}from"../../tools/AgentTool/constants.js";import{getAnthropicApiKeyWithSource as u}from"../auth.js";import{getCwd as l}from"../cwd.js";import{getFastModeState as c}from"../fastMode.js";import{getSettings_DEPRECATED as d}from"../settings/settings.js";export function sdkCompatToolName(s){return s===p?i:s}export function buildSystemInitMessage(o){const p=d(),i=p?.outputStyle??n,f={type:"system",subtype:"init",cwd:l(),session_id:r(),tools:o.tools.map(s=>sdkCompatToolName(s.name)),mcp_servers:o.mcpClients.map(s=>({name:s.name,status:s.type})),model:o.model,permissionMode:o.permissionMode,slash_commands:o.commands.filter(s=>!1!==s.userInvocable).map(s=>s.name),apiKeySource:u().source,betas:a(),claude_code_version:s.VERSION,output_style:i,agents:o.agents.map(s=>s.agentType),skills:o.skills.filter(s=>!1!==s.userInvocable).map(s=>s.name),plugins:o.plugins.map(s=>({name:s.name,path:s.path,source:s.source})),uuid:m()};return t("UDS_INBOX")&&(f.messaging_socket_path=e("../udsMessaging.js").getUdsMessagingSocketPath()),f.fast_mode_state=c(o.model,o.fastMode),f}
1
+ import{MACRO as s}from"../../recovery/bunBundleShim.js";import{createRequire as t}from"module";const e=t(import.meta.url);import{feature as o}from"bun:bundle";import{randomUUID as a}from"crypto";import{getSdkBetas as m,getSessionId as r}from"src/bootstrap/state.js";import{DEFAULT_OUTPUT_STYLE_NAME as n}from"src/constants/outputStyles.js";import{AGENT_TOOL_NAME as i,LEGACY_AGENT_TOOL_NAME as p}from"src/tools/AgentTool/constants.js";import{getAnthropicApiKeyWithSource as u}from"../auth.js";import{getCwd as c}from"../cwd.js";import{getFastModeState as l}from"../fastMode.js";import{getSettings_DEPRECATED as d}from"../settings/settings.js";export function sdkCompatToolName(s){return s===i?p:s}export function buildSystemInitMessage(t){const i=d(),p=i?.outputStyle??n,g={type:"system",subtype:"init",cwd:c(),session_id:r(),tools:t.tools.map(s=>sdkCompatToolName(s.name)),mcp_servers:t.mcpClients.map(s=>({name:s.name,status:s.type})),model:t.model,permissionMode:t.permissionMode,slash_commands:t.commands.filter(s=>!1!==s.userInvocable).map(s=>s.name),apiKeySource:u().source,betas:m(),claude_code_version:s.VERSION,output_style:p,agents:t.agents.map(s=>s.agentType),skills:t.skills.filter(s=>!1!==s.userInvocable).map(s=>s.name),plugins:t.plugins.map(s=>({name:s.name,path:s.path,source:s.source})),uuid:a()};return o("UDS_INBOX")&&(g.messaging_socket_path=e("../udsMessaging.js").getUdsMessagingSocketPath()),g.fast_mode_state=l(t.model,t.fastMode),g}
@@ -1 +1 @@
1
- import{getFeatureValue_CACHED_MAY_BE_STALE as e}from"../../services/analytics/growthbook.js";export function getAntModelOverrideConfig(){return"ant"!==process.env.USER_TYPE?null:e("tengu_ant_model_override",null)}export function getAntModels(){return"ant"!==process.env.USER_TYPE?[]:getAntModelOverrideConfig()?.antModels??[]}export function resolveAntModel(e){if("ant"!==process.env.USER_TYPE)return;if(void 0===e)return;const n=e.toLowerCase();return getAntModels().find(o=>o.alias===e||n.includes(o.model.toLowerCase()))}
1
+ import{getFeatureValue_CACHED_MAY_BE_STALE as e}from"src/services/analytics/growthbook.js";export function getAntModelOverrideConfig(){return"ant"!==process.env.USER_TYPE?null:e("tengu_ant_model_override",null)}export function getAntModels(){return"ant"!==process.env.USER_TYPE?[]:getAntModelOverrideConfig()?.antModels??[]}export function resolveAntModel(e){if("ant"!==process.env.USER_TYPE)return;if(void 0===e)return;const t=e.toLowerCase();return getAntModels().find(n=>n.alias===e||t.includes(n.model.toLowerCase()))}
@@ -1 +1 @@
1
- import{isClaudeAISubscriber as e}from"../auth.js";import{getGlobalConfig as t}from"../config.js";import{is1mContextDisabled as n}from"../context.js";function isExtraUsageEnabled(){const e=t().cachedExtraUsageDisabledReason;return void 0!==e&&(null===e||"out_of_credits"===e)}export function checkOpus1mAccess(){return!n()&&(!e()||isExtraUsageEnabled())}export function checkSonnet1mAccess(){return!n()&&(!e()||isExtraUsageEnabled())}
1
+ import{isClaudeAISubscriber as e}from"../auth.js";import{getGlobalConfig as s}from"../config.js";import{is1mContextDisabled as t}from"../context.js";function isExtraUsageEnabled(){const e=s().cachedExtraUsageDisabledReason;return void 0!==e&&(null===e||"out_of_credits"===e)}export function checkOpus1mAccess(){return!t()&&(!e()||isExtraUsageEnabled())}export function checkSonnet1mAccess(){return!t()&&(!e()||isExtraUsageEnabled())}
@@ -1 +1 @@
1
- import{checkOpus1mAccess as e,checkSonnet1mAccess as n}from"./check1mAccess.js";import{getUserSpecifiedModelSetting as t}from"./model.js";export function getUpgradeMessage(r){const s=function(){const r=t();return"opus"===r&&e()?{alias:"opus[1m]",name:"Opus 1M",multiplier:5}:"sonnet"===r&&n()?{alias:"sonnet[1m]",name:"Sonnet 1M",multiplier:5}:null}();if(!s)return null;switch(r){case"warning":return`/model ${s.alias}`;case"tip":return`Tip: You have access to ${s.name} with ${s.multiplier}x more context`;default:return null}}
1
+ import{checkOpus1mAccess as e,checkSonnet1mAccess as s}from"./check1mAccess.js";import{getUserSpecifiedModelSetting as t}from"./model.js";export function getUpgradeMessage(n){const c=function(){const n=t();return"opus"===n&&e()?{alias:"opus[1m]",name:"Opus 1M",multiplier:5}:"sonnet"===n&&s()?{alias:"sonnet[1m]",name:"Sonnet 1M",multiplier:5}:null}();if(!c)return null;switch(n){case"warning":return`/model ${c.alias}`;case"tip":return`Tip: You have access to ${c.name} with ${c.multiplier}x more context`;default:return null}}
@@ -1 +1 @@
1
- import{getMainLoopModelOverride as e}from"../../bootstrap/state.js";import{getSubscriptionType as t,isClaudeAISubscriber as n,isMaxSubscriber as o,isProSubscriber as r,isTeamPremiumSubscriber as u}from"../auth.js";import{has1mContext as i,is1mContextDisabled as s,modelSupports1M as l}from"../context.js";import{isEnvTruthy as a}from"../envUtils.js";import{getModelStrings as c,resolveOverriddenModel as d}from"./modelStrings.js";import{resolveAntModel as p,getAntModelOverrideConfig as f}from"./antModels.js";export{p as resolveAntModel,f as getAntModelOverrideConfig};import{formatModelPricing as m,getOpus46CostTier as M}from"../modelCost.js";import{getSettings_DEPRECATED as g}from"../settings/settings.js";import{getAPIProvider as O,isOpenAICompatibleProvider as D}from"./providers.js";import{LIGHTNING_BOLT as x}from"../../constants/figures.js";import{isModelAllowed as S}from"./modelAllowlist.js";import{isModelAlias as P}from"./aliases.js";import{capitalize as E}from"../stringUtils.js";export function isOpenAIProvider(){return D(O())}export function isGeminiProvider(){const e=O();return"gemini-api"===e||"gemini-google"===e}export function getSmallFastModel(){return process.env.ANTHROPIC_SMALL_FAST_MODEL||getDefaultHaikuModel()}export function isNonCustomOpusModel(e){return e===c().opus40||e===c().opus41||e===c().opus45||e===c().opus46||e===c().opus47}export function getUserSpecifiedModelSetting(){let t;const n=e();if(void 0!==n)t=n;else{const e=g()||{};t=process.env.ANTHROPIC_MODEL||e.model||void 0}if(!t||S(t))return t}export function getMainLoopModel(){const e=getUserSpecifiedModelSetting();return null!=e?parseUserSpecifiedModel(e):getDefaultMainLoopModel()}export function getBestModel(){return isGeminiProvider()?getDefaultGeminiModel():isOpenAIProvider()?getDefaultOpenAIModel():getDefaultOpusModel()}export function getDefaultOpusModel(){return process.env.ANTHROPIC_DEFAULT_OPUS_MODEL?process.env.ANTHROPIC_DEFAULT_OPUS_MODEL:(O(),c().opus46)}export function getDefaultSonnetModel(){return process.env.ANTHROPIC_DEFAULT_SONNET_MODEL?process.env.ANTHROPIC_DEFAULT_SONNET_MODEL:"firstParty"!==O()?c().sonnet45:c().sonnet46}export function getDefaultHaikuModel(){return process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL?process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL:c().haiku45}export function getDefaultOpenAIModel(){return process.env.OPENAI_DEFAULT_MODEL||"gpt-5.4"}export function getDefaultOpenAIFastModel(){return process.env.OPENAI_DEFAULT_FAST_MODEL||"gpt-5.4-mini"}export function getDefaultGeminiModel(){return process.env.GEMINI_DEFAULT_MODEL||"gemini-3.5-pro"}export function getDefaultGeminiFastModel(){return process.env.GEMINI_DEFAULT_FAST_MODEL||"gemini-3.5-flash"}export function getRuntimeMainLoopModel(e){const{permissionMode:t,mainLoopModel:n,exceeds200kTokens:o=!1}=e;return"opusplan"!==getUserSpecifiedModelSetting()||"plan"!==t||o?"haiku"===getUserSpecifiedModelSetting()&&"plan"===t?getDefaultSonnetModel():n:getDefaultOpusModel()}export function getDefaultMainLoopModelSetting(){return"ant"===process.env.USER_TYPE?f()?.defaultModel??getDefaultOpusModel()+"[1m]":isGeminiProvider()?getDefaultGeminiModel():isOpenAIProvider()?getDefaultOpenAIModel():o()||u()?getDefaultOpusModel()+(isOpus1mMergeEnabled()?"[1m]":""):getDefaultSonnetModel()}export function getDefaultMainLoopModel(){return parseUserSpecifiedModel(getDefaultMainLoopModelSetting())}export function firstPartyNameToCanonical(e){if(!e)return e;if((e=e.toLowerCase()).includes("claude-opus-4-7"))return"claude-opus-4-7";if(e.includes("claude-opus-4-6"))return"claude-opus-4-6";if(e.includes("claude-opus-4-5"))return"claude-opus-4-5";if(e.includes("claude-opus-4-1"))return"claude-opus-4-1";if(e.includes("claude-opus-4"))return"claude-opus-4";if(e.includes("claude-sonnet-4-6"))return"claude-sonnet-4-6";if(e.includes("claude-sonnet-4-5"))return"claude-sonnet-4-5";if(e.includes("claude-sonnet-4"))return"claude-sonnet-4";if(e.includes("claude-haiku-4-5"))return"claude-haiku-4-5";if(e.includes("claude-3-7-sonnet"))return"claude-3-7-sonnet";if(e.includes("claude-3-5-sonnet"))return"claude-3-5-sonnet";if(e.includes("claude-3-5-haiku"))return"claude-3-5-haiku";if(e.includes("claude-3-opus"))return"claude-3-opus";if(e.includes("claude-3-sonnet"))return"claude-3-sonnet";if(e.includes("claude-3-haiku"))return"claude-3-haiku";const t=e.match(/(claude-(\d+-\d+-)?\w+)/);return t&&t[1]?t[1]:e}export function getCanonicalName(e){return firstPartyNameToCanonical(d(e))}export function getClaudeAiUserDefaultModelDescription(e=!1){return o()||u()?isOpus1mMergeEnabled()?`Opus 4.7 con contexto de 1M · El más capaz para tareas complejas${e?getOpus46PricingSuffix(!0):""}`:`Opus 4.7 · El más capaz para tareas complejas${e?getOpus46PricingSuffix(!0):""}`:"Sonnet 4.6 · Lo mejor para tareas cotidianas"}export function renderDefaultModelSetting(e){return"opusplan"===e?"Opus 4.7 en modo plan, de lo contrario Sonnet 4.6":renderModelName(parseUserSpecifiedModel(e))}export function getOpus46PricingSuffix(e){if("firstParty"!==O())return"";const t=m(M(e));return` ·${e?` (${x})`:""} ${t}`}export function isOpus1mMergeEnabled(){return!s()&&!r()&&"firstParty"===O()&&(!n()||null!==t())}export function renderModelSetting(e){return"opusplan"===e?"Plan Opus":P(e)?E(e):renderModelName(e)}export function getPublicModelDisplayName(e){switch(e){case c().opus47:return"Opus 4.7";case c().opus47+"[1m]":return"Opus 4.7 (1M context)";case c().opus46:return"Opus 4.6";case c().opus46+"[1m]":return"Opus 4.6 (1M context)";case c().opus45:return"Opus 4.5";case c().opus41:return"Opus 4.1";case c().opus40:return"Opus 4";case c().sonnet46+"[1m]":return"Sonnet 4.6 (1M context)";case c().sonnet46:return"Sonnet 4.6";case c().sonnet45+"[1m]":return"Sonnet 4.5 (1M context)";case c().sonnet45:return"Sonnet 4.5";case c().sonnet40:return"Sonnet 4";case c().sonnet40+"[1m]":return"Sonnet 4 (1M context)";case c().sonnet37:return"Sonnet 3.7";case c().sonnet35:return"Sonnet 3.5";case c().haiku45:return"Haiku 4.5";case c().haiku35:return"Haiku 3.5";default:return null}}export function renderModelName(e){const t=getPublicModelDisplayName(e);if(t)return t;if("ant"===process.env.USER_TYPE){const t=parseUserSpecifiedModel(e),n=p(e);if(n){const e=function(e){const[t="",...n]=e.split("-");return[t.slice(0,3)+"*".repeat(Math.max(0,t.length-3)),...n].join("-")}(n.model.replace(/\[1m\]$/i,""));return e+(i(t)?"[1m]":"")}return t!==e?`${e} (${t})`:t}return e}export function getPublicModelName(e){const t=getPublicModelDisplayName(e);return t||e}export function parseUserSpecifiedModel(e){const t=getDefaultMainLoopModelSetting(),n=("string"==typeof e&&e.trim().length>0?e:"string"==typeof t&&t.trim().length>0?t:getDefaultOpenAIModel()).trim(),o=n.toLowerCase(),r=i(o),u=r?o.replace(/\[1m]$/i,"").trim():o;if(isOpenAIProvider()&&P(u))return"best"===u?getBestModel():r?n.replace(/\[1m\]$/i,"").trim()+"[1m]":n;if(P(u))switch(u){case"best":return getBestModel();case"opusplan":case"sonnet":return getDefaultSonnetModel()+(r?"[1m]":"");case"haiku":return getDefaultHaikuModel()+(r?"[1m]":"");case"opus":return getDefaultOpusModel()+(r?"[1m]":"")}if("firstParty"===O()&&(s=u,T.includes(s))&&isLegacyModelRemapEnabled())return getDefaultOpusModel()+(r?"[1m]":"");var s;if("ant"===process.env.USER_TYPE){const e=i(o),t=o.replace(/\[1m]$/i,"").trim(),n=p(t);if(n){const t=e?"[1m]":"";return n.model+t}}return r?n.replace(/\[1m\]$/i,"").trim()+"[1m]":n}export function resolveSkillModelOverride(e,t){return i(e)||!i(t)?e:l(parseUserSpecifiedModel(e))?e+"[1m]":e}const T=["claude-opus-4-20250514","claude-opus-4-1-20250805","claude-opus-4-0","claude-opus-4-1"];export function isLegacyModelRemapEnabled(){return!a(process.env.CONTEXT_CODE_DISABLE_LEGACY_MODEL_REMAP)&&!a(process.env.CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP)}export function modelDisplayString(e){if(null===e)return"ant"===process.env.USER_TYPE?`Predeterminado para Ants (${renderDefaultModelSetting(getDefaultMainLoopModelSetting())})`:n()?`Predeterminado (${getClaudeAiUserDefaultModelDescription()})`:`Predeterminado (${renderModelName(getDefaultMainLoopModel())})`;const t=parseUserSpecifiedModel(e);return isOpenAIProvider()?e===t?renderModelName(t):`${e} (${renderModelName(t)})`:e===t?t:`${e} (${t})`}export function getMarketingNameForModel(e){if(!e)return;if("foundry"===O())return;const t=e.toLowerCase().includes("[1m]"),n=getCanonicalName(e);return n.includes("claude-opus-4-7")?t?"Opus 4.7 (with 1M context)":"Opus 4.7":n.includes("claude-opus-4-6")?t?"Opus 4.6 (with 1M context)":"Opus 4.6":n.includes("claude-opus-4-5")?"Opus 4.5":n.includes("claude-opus-4-1")?"Opus 4.1":n.includes("claude-opus-4")?"Opus 4":n.includes("claude-sonnet-4-6")?t?"Sonnet 4.6 (with 1M context)":"Sonnet 4.6":n.includes("claude-sonnet-4-5")?t?"Sonnet 4.5 (with 1M context)":"Sonnet 4.5":n.includes("claude-sonnet-4")?t?"Sonnet 4 (with 1M context)":"Sonnet 4":n.includes("claude-3-7-sonnet")?"3.7 Sonnet":n.includes("claude-3-5-sonnet")?"3.5 Sonnet":n.includes("claude-haiku-4-5")?"Haiku 4.5":n.includes("claude-3-5-haiku")?"3.5 Haiku":n.includes("gpt-5.3-codex")?"GPT-5.3 Codex":n.includes("gpt-5.5-pro")?"GPT-5.5 Pro":n.includes("gpt-5.5")?"GPT-5.5":n.includes("gpt-5.2-codex")?"GPT-5.2 Codex":n.includes("gpt-5.1-codex-max")?"GPT-5.1 Codex Max":n.includes("gpt-5.1-codex-mini")?"GPT-5.1 Codex mini":n.includes("gpt-5.1-codex")?"GPT-5.1 Codex":n.includes("gpt-5.3")?"GPT-5.3":n.includes("gpt-5.2")?"GPT-5.2":n.includes("gpt-5.1")?"GPT-5.1":n.includes("gpt-5-codex")?"GPT-5 Codex":n.includes("gpt-5-chat-latest")?"GPT-5 Chat":n.includes("gpt-5-mini")?"GPT-5 mini":n.includes("gpt-5-nano")?"GPT-5 nano":n.includes("gpt-5-pro")?"GPT-5 Pro":n.includes("gpt-5")?"GPT-5":n.includes("gpt-4o-mini")?"GPT-4o mini":n.includes("gpt-4o")?"GPT-4o":n.includes("codex-mini-latest")?"Codex mini":void 0}export function normalizeModelStringForAPI(e){return e.replace(/\[(1|2)m\]/gi,"")}
1
+ import{getMainLoopModelOverride as e}from"../../bootstrap/state.js";import{getSubscriptionType as t,isClaudeAISubscriber as n,isMaxSubscriber as o,isProSubscriber as r,isTeamPremiumSubscriber as s}from"../auth.js";import{has1mContext as i,is1mContextDisabled as u,modelSupports1M as l}from"../context.js";import{isEnvTruthy as a}from"../envUtils.js";import{getModelStrings as d,resolveOverriddenModel as c}from"./modelStrings.js";import{resolveAntModel as p,getAntModelOverrideConfig as f}from"./antModels.js";export{p as resolveAntModel,f as getAntModelOverrideConfig};import{formatModelPricing as M,getOpus46CostTier as m}from"../modelCost.js";import{getSettings_DEPRECATED as g}from"../settings/settings.js";import{getAPIProvider as O,isOpenAICompatibleProvider as S}from"./providers.js";import{LIGHTNING_BOLT as D}from"../../constants/figures.js";import{isModelAllowed as P}from"./modelAllowlist.js";import{isModelAlias as x}from"./aliases.js";import{capitalize as E}from"../stringUtils.js";export function isOpenAIProvider(){return S(O())}export function isGeminiProvider(){const e=O();return"gemini-api"===e||"gemini-google"===e}export function getSmallFastModel(){return process.env.ANTHROPIC_SMALL_FAST_MODEL||getDefaultHaikuModel()}export function isNonCustomOpusModel(e){return e===d().opus40||e===d().opus41||e===d().opus45||e===d().opus46||e===d().opus47}export function getUserSpecifiedModelSetting(){let t;const n=e();if(void 0!==n)t=n;else{const e=g()||{};t=process.env.ANTHROPIC_MODEL||e.model||void 0}if(!t||P(t))return t}export function getMainLoopModel(){const e=getUserSpecifiedModelSetting();return null!=e?parseUserSpecifiedModel(e):getDefaultMainLoopModel()}export function getBestModel(){return isGeminiProvider()?getDefaultGeminiModel():isOpenAIProvider()?getDefaultOpenAIModel():getDefaultOpusModel()}export function getDefaultOpusModel(){return process.env.ANTHROPIC_DEFAULT_OPUS_MODEL?process.env.ANTHROPIC_DEFAULT_OPUS_MODEL:(O(),d().opus46)}export function getDefaultSonnetModel(){return process.env.ANTHROPIC_DEFAULT_SONNET_MODEL?process.env.ANTHROPIC_DEFAULT_SONNET_MODEL:"firstParty"!==O()?d().sonnet45:d().sonnet46}export function getDefaultHaikuModel(){return process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL?process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL:d().haiku45}export function getDefaultOpenAIModel(){return process.env.OPENAI_DEFAULT_MODEL||"gpt-5.4"}export function getDefaultOpenAIFastModel(){return process.env.OPENAI_DEFAULT_FAST_MODEL||"gpt-5.4-mini"}export function getDefaultGeminiModel(){return process.env.GEMINI_DEFAULT_MODEL||"gemini-3.5-pro"}export function getDefaultGeminiFastModel(){return process.env.GEMINI_DEFAULT_FAST_MODEL||"gemini-3.5-flash"}export function getRuntimeMainLoopModel(e){const{permissionMode:t,mainLoopModel:n,exceeds200kTokens:o=!1}=e;return"opusplan"!==getUserSpecifiedModelSetting()||"plan"!==t||o?"haiku"===getUserSpecifiedModelSetting()&&"plan"===t?getDefaultSonnetModel():n:getDefaultOpusModel()}export function getDefaultMainLoopModelSetting(){return"ant"===process.env.USER_TYPE?f()?.defaultModel??getDefaultOpusModel()+"[1m]":isGeminiProvider()?getDefaultGeminiModel():isOpenAIProvider()?getDefaultOpenAIModel():o()||s()?getDefaultOpusModel()+(isOpus1mMergeEnabled()?"[1m]":""):getDefaultSonnetModel()}export function getDefaultMainLoopModel(){return parseUserSpecifiedModel(getDefaultMainLoopModelSetting())}export function firstPartyNameToCanonical(e){if(!e)return e;if((e=e.toLowerCase()).includes("claude-opus-4-7"))return"claude-opus-4-7";if(e.includes("claude-opus-4-6"))return"claude-opus-4-6";if(e.includes("claude-opus-4-5"))return"claude-opus-4-5";if(e.includes("claude-opus-4-1"))return"claude-opus-4-1";if(e.includes("claude-opus-4"))return"claude-opus-4";if(e.includes("claude-sonnet-4-6"))return"claude-sonnet-4-6";if(e.includes("claude-sonnet-4-5"))return"claude-sonnet-4-5";if(e.includes("claude-sonnet-4"))return"claude-sonnet-4";if(e.includes("claude-haiku-4-5"))return"claude-haiku-4-5";if(e.includes("claude-3-7-sonnet"))return"claude-3-7-sonnet";if(e.includes("claude-3-5-sonnet"))return"claude-3-5-sonnet";if(e.includes("claude-3-5-haiku"))return"claude-3-5-haiku";if(e.includes("claude-3-opus"))return"claude-3-opus";if(e.includes("claude-3-sonnet"))return"claude-3-sonnet";if(e.includes("claude-3-haiku"))return"claude-3-haiku";const t=e.match(/(claude-(\d+-\d+-)?\w+)/);return t&&t[1]?t[1]:e}export function getCanonicalName(e){return firstPartyNameToCanonical(c(e))}export function getClaudeAiUserDefaultModelDescription(e=!1){return o()||s()?isOpus1mMergeEnabled()?`Opus 4.7 con contexto de 1M · El más capaz para tareas complejas${e?getOpus46PricingSuffix(!0):""}`:`Opus 4.7 · El más capaz para tareas complejas${e?getOpus46PricingSuffix(!0):""}`:"Sonnet 4.6 · Lo mejor para tareas cotidianas"}export function renderDefaultModelSetting(e){return"opusplan"===e?"Opus 4.7 en modo plan, de lo contrario Sonnet 4.6":renderModelName(parseUserSpecifiedModel(e))}export function getOpus46PricingSuffix(e){if("firstParty"!==O())return"";const t=M(m(e));return` ·${e?` (${D})`:""} ${t}`}export function isOpus1mMergeEnabled(){return!(u()||r()||"firstParty"!==O()||n()&&null===t())}export function renderModelSetting(e){return"opusplan"===e?"Plan Opus":x(e)?E(e):renderModelName(e)}export function getPublicModelDisplayName(e){switch(e){case d().opus47:return"Opus 4.7";case d().opus47+"[1m]":return"Opus 4.7 (1M context)";case d().opus46:return"Opus 4.6";case d().opus46+"[1m]":return"Opus 4.6 (1M context)";case d().opus45:return"Opus 4.5";case d().opus41:return"Opus 4.1";case d().opus40:return"Opus 4";case d().sonnet46+"[1m]":return"Sonnet 4.6 (1M context)";case d().sonnet46:return"Sonnet 4.6";case d().sonnet45+"[1m]":return"Sonnet 4.5 (1M context)";case d().sonnet45:return"Sonnet 4.5";case d().sonnet40:return"Sonnet 4";case d().sonnet40+"[1m]":return"Sonnet 4 (1M context)";case d().sonnet37:return"Sonnet 3.7";case d().sonnet35:return"Sonnet 3.5";case d().haiku45:return"Haiku 4.5";case d().haiku35:return"Haiku 3.5";default:return null}}export function renderModelName(e){const t=getPublicModelDisplayName(e);if(t)return t;if("ant"===process.env.USER_TYPE){const t=parseUserSpecifiedModel(e),n=p(e);if(n){const e=function(e){const[t="",...n]=e.split("-");return[t.slice(0,3)+"*".repeat(Math.max(0,t.length-3)),...n].join("-")}(n.model.replace(/\[1m\]$/i,""));return e+(i(t)?"[1m]":"")}return t!==e?`${e} (${t})`:t}return e}export function getPublicModelName(e){return getPublicModelDisplayName(e)||e}export function parseUserSpecifiedModel(e){const t=getDefaultMainLoopModelSetting(),n=("string"==typeof e&&e.trim().length>0?e:"string"==typeof t&&t.trim().length>0?t:getDefaultOpenAIModel()).trim(),o=n.toLowerCase(),r=i(o),s=r?o.replace(/\[1m]$/i,"").trim():o;if(isOpenAIProvider()&&x(s))return"best"===s?getBestModel():r?n.replace(/\[1m\]$/i,"").trim()+"[1m]":n;if(x(s))switch(s){case"best":return getBestModel();case"opusplan":case"sonnet":return getDefaultSonnetModel()+(r?"[1m]":"");case"haiku":return getDefaultHaikuModel()+(r?"[1m]":"");case"opus":return getDefaultOpusModel()+(r?"[1m]":"")}if("firstParty"===O()&&(u=s,A.includes(u))&&isLegacyModelRemapEnabled())return getDefaultOpusModel()+(r?"[1m]":"");var u;if("ant"===process.env.USER_TYPE){const e=i(o),t=o.replace(/\[1m]$/i,"").trim(),n=p(t);if(n){const t=e?"[1m]":"";return n.model+t}}return r?n.replace(/\[1m\]$/i,"").trim()+"[1m]":n}export function resolveSkillModelOverride(e,t){return i(e)||!i(t)?e:l(parseUserSpecifiedModel(e))?e+"[1m]":e}const A=["claude-opus-4-20250514","claude-opus-4-1-20250805","claude-opus-4-0","claude-opus-4-1"];export function isLegacyModelRemapEnabled(){return!a(process.env.CONTEXT_CODE_DISABLE_LEGACY_MODEL_REMAP)&&!a(process.env.CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP)}export function modelDisplayString(e){if(null===e)return"ant"===process.env.USER_TYPE?`Predeterminado para Ants (${renderDefaultModelSetting(getDefaultMainLoopModelSetting())})`:n()?`Predeterminado (${getClaudeAiUserDefaultModelDescription()})`:`Predeterminado (${renderModelName(getDefaultMainLoopModel())})`;const t=parseUserSpecifiedModel(e);return isOpenAIProvider()?e===t?renderModelName(t):`${e} (${renderModelName(t)})`:e===t?t:`${e} (${t})`}export function getMarketingNameForModel(e){if(!e)return;if("foundry"===O())return;const t=e.toLowerCase().includes("[1m]"),n=getCanonicalName(e);return n.includes("claude-opus-4-7")?t?"Opus 4.7 (with 1M context)":"Opus 4.7":n.includes("claude-opus-4-6")?t?"Opus 4.6 (with 1M context)":"Opus 4.6":n.includes("claude-opus-4-5")?"Opus 4.5":n.includes("claude-opus-4-1")?"Opus 4.1":n.includes("claude-opus-4")?"Opus 4":n.includes("claude-sonnet-4-6")?t?"Sonnet 4.6 (with 1M context)":"Sonnet 4.6":n.includes("claude-sonnet-4-5")?t?"Sonnet 4.5 (with 1M context)":"Sonnet 4.5":n.includes("claude-sonnet-4")?t?"Sonnet 4 (with 1M context)":"Sonnet 4":n.includes("claude-3-7-sonnet")?"3.7 Sonnet":n.includes("claude-3-5-sonnet")?"3.5 Sonnet":n.includes("claude-haiku-4-5")?"Haiku 4.5":n.includes("claude-3-5-haiku")?"3.5 Haiku":n.includes("gpt-5.3-codex")?"GPT-5.3 Codex":n.includes("gpt-5.5-pro")?"GPT-5.5 Pro":n.includes("gpt-5.5")?"GPT-5.5":n.includes("gpt-5.2-codex")?"GPT-5.2 Codex":n.includes("gpt-5.1-codex-max")?"GPT-5.1 Codex Max":n.includes("gpt-5.1-codex-mini")?"GPT-5.1 Codex mini":n.includes("gpt-5.1-codex")?"GPT-5.1 Codex":n.includes("gpt-5.3")?"GPT-5.3":n.includes("gpt-5.2")?"GPT-5.2":n.includes("gpt-5.1")?"GPT-5.1":n.includes("gpt-5-codex")?"GPT-5 Codex":n.includes("gpt-5-chat-latest")?"GPT-5 Chat":n.includes("gpt-5-mini")?"GPT-5 mini":n.includes("gpt-5-nano")?"GPT-5 nano":n.includes("gpt-5-pro")?"GPT-5 Pro":n.includes("gpt-5")?"GPT-5":n.includes("gpt-4o-mini")?"GPT-4o mini":n.includes("gpt-4o")?"GPT-4o":n.includes("codex-mini-latest")?"Codex mini":void 0}export function normalizeModelStringForAPI(e){return e.replace(/\[(1|2)m\]/gi,"")}
@@ -1 +1 @@
1
- import{getSettings_DEPRECATED as e}from"../settings/settings.js";import{isModelAlias as t,isModelFamilyAlias as o}from"./aliases.js";import{parseUserSpecifiedModel as r}from"./model.js";import{resolveOverriddenModel as i}from"./modelStrings.js";function modelBelongsToFamily(e,o){if(e.includes(o))return!0;if(t(e)){return r(e).toLowerCase().includes(o)}return!1}function prefixMatchesModel(e,t){return!!e.startsWith(t)&&(e.length===t.length||"-"===e[t.length])}function modelMatchesVersionPrefix(e,o){const i=t(e)?r(e).toLowerCase():e;return!!prefixMatchesModel(i,o)||!(o.startsWith("claude-")||!prefixMatchesModel(i,`claude-${o}`))}function familyHasSpecificEntries(e,t){for(const r of t){if(o(r))continue;const t=r.indexOf(e);if(-1===t)continue;const i=t+e.length;if(i===r.length||"-"===r[i])return!0}return!1}export function isModelAllowed(n){const s=e()||{},{availableModels:f}=s;if(!f)return!0;if(0===f.length)return!1;const l=i(n).trim().toLowerCase(),c=f.map(e=>e.trim().toLowerCase());if(c.includes(l)&&(!o(l)||!familyHasSpecificEntries(l,c)))return!0;for(const e of c)if(o(e)&&!familyHasSpecificEntries(e,c)&&modelBelongsToFamily(l,e))return!0;if(t(l)){const e=r(l).toLowerCase();if(c.includes(e))return!0}for(const e of c)if(!o(e)&&t(e)){if(r(e).toLowerCase()===l)return!0}for(const e of c)if(!o(e)&&!t(e)&&modelMatchesVersionPrefix(l,e))return!0;return!1}
1
+ import{getSettings_DEPRECATED as e}from"../settings/settings.js";import{isModelAlias as t,isModelFamilyAlias as o}from"./aliases.js";import{parseUserSpecifiedModel as i}from"./model.js";import{resolveOverriddenModel as r}from"./modelStrings.js";function modelBelongsToFamily(e,o){return!!e.includes(o)||!!t(e)&&i(e).toLowerCase().includes(o)}function prefixMatchesModel(e,t){return!!e.startsWith(t)&&(e.length===t.length||"-"===e[t.length])}function modelMatchesVersionPrefix(e,o){const r=t(e)?i(e).toLowerCase():e;return!!prefixMatchesModel(r,o)||!(o.startsWith("claude-")||!prefixMatchesModel(r,`claude-${o}`))}function familyHasSpecificEntries(e,t){for(const i of t){if(o(i))continue;const t=i.indexOf(e);if(-1===t)continue;const r=t+e.length;if(r===i.length||"-"===i[r])return!0}return!1}export function isModelAllowed(s){const n=e()||{},{availableModels:l}=n;if(!l)return!0;if(0===l.length)return!1;const f=r(s).trim().toLowerCase(),a=l.map(e=>e.trim().toLowerCase());if(a.includes(f)&&(!o(f)||!familyHasSpecificEntries(f,a)))return!0;for(const e of a)if(o(e)&&!familyHasSpecificEntries(e,a)&&modelBelongsToFamily(f,e))return!0;if(t(f)){const e=i(f).toLowerCase();if(a.includes(e))return!0}for(const e of a)if(!o(e)&&t(e)&&i(e).toLowerCase()===f)return!0;for(const e of a)if(!o(e)&&!t(e)&&modelMatchesVersionPrefix(f,e))return!0;return!1}
@@ -1 +1 @@
1
- import{readFileSync as e}from"fs";import{mkdir as t,writeFile as i}from"fs/promises";import o from"lodash-es/isEqual.js";import r from"lodash-es/memoize.js";import{join as s}from"path";import{z as a}from"zod/v4";import{OAUTH_BETA_HEADER as n}from"../../constants/oauth.js";import{getAnthropicClient as m}from"../../services/api/client.js";import{isClaudeAISubscriber as c}from"../auth.js";import{logForDebugging as l}from"../debug.js";import{getClaudeConfigHomeDir as p}from"../envUtils.js";import{safeParseJSON as f}from"../json.js";import{lazySchema as d}from"../lazySchema.js";import{isEssentialTrafficOnly as u}from"../privacyLevel.js";import{jsonStringify as h}from"../slowOperations.js";import{getAPIProvider as g,isFirstPartyAnthropicBaseUrl as b}from"./providers.js";const C=d(()=>a.object({id:a.string(),max_input_tokens:a.number().optional(),max_tokens:a.number().optional()}).strip()),j=d(()=>a.object({models:a.array(C()),timestamp:a.number()}));function getCacheDir(){return s(p(),"cache")}function getCachePath(){return s(getCacheDir(),"model-capabilities.json")}function isModelCapabilitiesEligible(){return"ant"===process.env.USER_TYPE&&("firstParty"===g()&&!!b())}const w=r(t=>{try{const i=e(t,"utf-8"),o=j().safeParse(f(i,!1));return o.success?o.data.models:null}catch{return null}},e=>e);export function getModelCapability(e){if(!isModelCapabilitiesEligible())return;if(!e)return;const t=w(getCachePath());if(!t||0===t.length)return;const i=e.toLowerCase(),o=t.find(e=>e.id.toLowerCase()===i);return o||t.find(e=>i.includes(e.id.toLowerCase()))}export async function refreshModelCapabilities(){if(isModelCapabilitiesEligible()&&!u())try{const e=await m({maxRetries:1}),r=c()?[n]:void 0,s=[];for await(const t of e.models.list({betas:r})){const e=C().safeParse(t);e.success&&s.push(e.data)}if(0===s.length)return;const a=getCachePath(),p=function(e){return[...e].sort((e,t)=>t.id.length-e.id.length||e.id.localeCompare(t.id))}(s);if(o(w(a),p))return void l("[modelCapabilities] cache unchanged, skipping write");await t(getCacheDir(),{recursive:!0}),await i(a,h({models:p,timestamp:Date.now()}),{encoding:"utf-8",mode:384}),w.cache.delete(a),l(`[modelCapabilities] cached ${p.length} models`)}catch(e){l(`[modelCapabilities] fetch failed: ${e instanceof Error?e.message:"unknown"}`)}}
1
+ import{readFileSync as e}from"fs";import{mkdir as i,writeFile as t}from"fs/promises";import s from"lodash-es/isEqual.js";import r from"lodash-es/memoize.js";import{join as o}from"path";import{z as a}from"zod/v4";import{OAUTH_BETA_HEADER as n}from"../../constants/oauth.js";import{getAnthropicClient as l}from"../../services/api/client.js";import{isClaudeAISubscriber as m}from"../auth.js";import{logForDebugging as c}from"../debug.js";import{getClaudeConfigHomeDir as f}from"../envUtils.js";import{safeParseJSON as p}from"../json.js";import{lazySchema as d}from"../lazySchema.js";import{isEssentialTrafficOnly as u}from"../privacyLevel.js";import{jsonStringify as h}from"../slowOperations.js";import{getAPIProvider as g,isFirstPartyAnthropicBaseUrl as b}from"./providers.js";const C=d(()=>a.object({id:a.string(),max_input_tokens:a.number().optional(),max_tokens:a.number().optional()}).strip()),j=d(()=>a.object({models:a.array(C()),timestamp:a.number()}));function getCacheDir(){return o(f(),"cache")}function getCachePath(){return o(getCacheDir(),"model-capabilities.json")}function isModelCapabilitiesEligible(){return"ant"===process.env.USER_TYPE&&"firstParty"===g()&&!!b()}const y=r(i=>{try{const t=e(i,"utf-8"),s=j().safeParse(p(t,!1));return s.success?s.data.models:null}catch{return null}},e=>e);export function getModelCapability(e){if(!isModelCapabilitiesEligible())return;if(!e)return;const i=y(getCachePath());if(!i||0===i.length)return;const t=e.toLowerCase(),s=i.find(e=>e.id.toLowerCase()===t);return s||i.find(e=>t.includes(e.id.toLowerCase()))}export async function refreshModelCapabilities(){if(isModelCapabilitiesEligible()&&!u())try{const e=await l({maxRetries:1}),r=m()?[n]:void 0,o=[];for await(const i of e.models.list({betas:r})){const e=C().safeParse(i);e.success&&o.push(e.data)}if(0===o.length)return;const a=getCachePath(),f=function(e){return[...e].sort((e,i)=>i.id.length-e.id.length||e.id.localeCompare(i.id))}(o);if(s(y(a),f))return void c("[modelCapabilities] cache unchanged, skipping write");await i(getCacheDir(),{recursive:!0}),await t(a,h({models:f,timestamp:Date.now()}),{encoding:"utf-8",mode:384}),y.cache.delete(a),c(`[modelCapabilities] cached ${f.length} models`)}catch(e){c(`[modelCapabilities] fetch failed: ${e instanceof Error?e.message:"unknown"}`)}}