@iaforged/context-code 2.1.7 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (411) hide show
  1. package/dist/src/Task.js +1 -1
  2. package/dist/src/commands/login/login.js +1 -1
  3. package/dist/src/components/ConsoleOAuthFlow.js +1 -1
  4. package/dist/src/constants/oauth.js +1 -1
  5. package/dist/src/context/mailbox.js +1 -1
  6. package/dist/src/context/voice.js +1 -1
  7. package/dist/src/hooks/useTerminalSize.js +1 -1
  8. package/dist/src/ink/Ansi.js +1 -1
  9. package/dist/src/ink/clearTerminal.js +1 -1
  10. package/dist/src/ink/colorize.js +1 -1
  11. package/dist/src/ink/components/App.js +1 -1
  12. package/dist/src/ink/components/Button.js +1 -1
  13. package/dist/src/ink/components/ClockContext.js +1 -1
  14. package/dist/src/ink/components/CursorDeclarationContext.js +1 -1
  15. package/dist/src/ink/components/Link.js +1 -1
  16. package/dist/src/ink/components/StdinContext.js +1 -1
  17. package/dist/src/ink/components/TerminalFocusContext.js +1 -1
  18. package/dist/src/ink/dom.js +1 -1
  19. package/dist/src/ink/events/keyboard-event.js +1 -1
  20. package/dist/src/ink/hit-test.js +1 -1
  21. package/dist/src/ink/hooks/use-animation-frame.js +1 -1
  22. package/dist/src/ink/hooks/use-app.js +1 -1
  23. package/dist/src/ink/hooks/use-input.js +1 -1
  24. package/dist/src/ink/hooks/use-interval.js +1 -1
  25. package/dist/src/ink/hooks/use-selection.js +1 -1
  26. package/dist/src/ink/hooks/use-tab-status.js +1 -1
  27. package/dist/src/ink/hooks/use-terminal-focus.js +1 -1
  28. package/dist/src/ink/hooks/use-terminal-title.js +1 -1
  29. package/dist/src/ink/hooks/use-terminal-viewport.js +1 -1
  30. package/dist/src/ink/ink.js +1 -1
  31. package/dist/src/ink/layout/yoga.js +1 -1
  32. package/dist/src/ink/line-width-cache.js +1 -1
  33. package/dist/src/ink/log-update.js +1 -1
  34. package/dist/src/ink/measure-text.js +1 -1
  35. package/dist/src/ink/output.js +1 -1
  36. package/dist/src/ink/parse-keypress.js +1 -1
  37. package/dist/src/ink/reconciler.js +1 -1
  38. package/dist/src/ink/render-border.js +1 -1
  39. package/dist/src/ink/render-node-to-output.js +1 -1
  40. package/dist/src/ink/render-to-screen.js +1 -1
  41. package/dist/src/ink/renderer.js +1 -1
  42. package/dist/src/ink/root.js +1 -1
  43. package/dist/src/ink/screen.js +1 -1
  44. package/dist/src/ink/searchHighlight.js +1 -1
  45. package/dist/src/ink/selection.js +1 -1
  46. package/dist/src/ink/squash-text-nodes.js +1 -1
  47. package/dist/src/ink/stringWidth.js +1 -1
  48. package/dist/src/ink/tabstops.js +1 -1
  49. package/dist/src/ink/terminal.js +1 -1
  50. package/dist/src/ink/termio/osc.js +1 -1
  51. package/dist/src/ink/termio/parser.js +1 -1
  52. package/dist/src/ink/termio/tokenize.js +1 -1
  53. package/dist/src/ink/useTerminalNotification.js +1 -1
  54. package/dist/src/ink/warn.js +1 -1
  55. package/dist/src/ink/widest-line.js +1 -1
  56. package/dist/src/ink/wrap-text.js +1 -1
  57. package/dist/src/ink/wrapAnsi.js +1 -1
  58. package/dist/src/native-ts/yoga-layout/index.js +1 -1
  59. package/dist/src/schemas/hooks.js +1 -1
  60. package/dist/src/services/SessionMemory/sessionMemoryUtils.js +1 -1
  61. package/dist/src/services/api/client.js +1 -1
  62. package/dist/src/services/api/dumpPrompts.js +1 -1
  63. package/dist/src/services/api/errorUtils.js +1 -1
  64. package/dist/src/services/api/promptCacheBreakDetection.js +1 -1
  65. package/dist/src/services/api/withRetry.js +1 -1
  66. package/dist/src/services/autoDream/consolidationLock.js +1 -1
  67. package/dist/src/services/mcp/elicitationHandler.js +1 -1
  68. package/dist/src/services/mcp/mcpStringUtils.js +1 -1
  69. package/dist/src/services/mcp/oauthPort.js +1 -1
  70. package/dist/src/services/mcp/vscodeSdkMcp.js +1 -1
  71. package/dist/src/services/oauth/client.js +1 -1
  72. package/dist/src/services/oauth/getOauthProfile.js +1 -1
  73. package/dist/src/services/objetivo/types.js +1 -1
  74. package/dist/src/services/rateLimitMocking.js +1 -1
  75. package/dist/src/services/remoteManagedSettings/syncCacheState.js +1 -1
  76. package/dist/src/skills/bundledSkills.js +1 -1
  77. package/dist/src/tasks/DreamTask/DreamTask.js +1 -1
  78. package/dist/src/tools/AgentTool/agentMemory.js +1 -1
  79. package/dist/src/tools/AgentTool/forkSubagent.js +1 -1
  80. package/dist/src/tools/BashTool/BashToolResultMessage.js +1 -1
  81. package/dist/src/tools/BashTool/UI.js +1 -1
  82. package/dist/src/tools/BashTool/sedEditParser.js +1 -1
  83. package/dist/src/tools/BashTool/utils.js +1 -1
  84. package/dist/src/tools/FileReadTool/imageProcessor.js +1 -1
  85. package/dist/src/tools/FileReadTool/prompt.js +1 -1
  86. package/dist/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +1 -1
  87. package/dist/src/tools/ListMcpResourcesTool/UI.js +1 -1
  88. package/dist/src/tools/MCPTool/MCPTool.js +1 -1
  89. package/dist/src/tools/MCPTool/UI.js +1 -1
  90. package/dist/src/tools/McpAuthTool/McpAuthTool.js +1 -1
  91. package/dist/src/tools/NotebookEditTool/prompt.js +1 -1
  92. package/dist/src/tools/PowerShellTool/PowerShellTool.js +1 -1
  93. package/dist/src/tools/PowerShellTool/UI.js +1 -1
  94. package/dist/src/tools/PowerShellTool/gitSafety.js +1 -1
  95. package/dist/src/tools/PowerShellTool/modeValidation.js +1 -1
  96. package/dist/src/tools/PowerShellTool/pathValidation.js +1 -1
  97. package/dist/src/tools/PowerShellTool/powershellPermissions.js +1 -1
  98. package/dist/src/tools/PowerShellTool/powershellSecurity.js +1 -1
  99. package/dist/src/tools/PowerShellTool/prompt.js +1 -1
  100. package/dist/src/tools/PowerShellTool/readOnlyValidation.js +1 -1
  101. package/dist/src/tools/REPLTool/constants.js +1 -1
  102. package/dist/src/tools/REPLTool/primitiveTools.js +1 -1
  103. package/dist/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +1 -1
  104. package/dist/src/tools/ReadMcpResourceTool/UI.js +1 -1
  105. package/dist/src/tools/ScheduleCronTool/prompt.js +1 -1
  106. package/dist/src/tools/SkillTool/prompt.js +1 -1
  107. package/dist/src/tools/TodoWriteTool/TodoWriteTool.js +1 -1
  108. package/dist/src/tools/ToolSearchTool/prompt.js +1 -1
  109. package/dist/src/tools/WebSearchTool/prompt.js +1 -1
  110. package/dist/src/tools/shared/gitOperationTracking.js +1 -1
  111. package/dist/src/types/permissions.js +1 -1
  112. package/dist/src/utils/Cursor.js +1 -1
  113. package/dist/src/utils/QueryGuard.js +1 -1
  114. package/dist/src/utils/Shell.js +1 -1
  115. package/dist/src/utils/ShellCommand.js +1 -1
  116. package/dist/src/utils/activityManager.js +1 -1
  117. package/dist/src/utils/advisor.js +1 -1
  118. package/dist/src/utils/appleTerminalBackup.js +1 -1
  119. package/dist/src/utils/argumentSubstitution.js +1 -1
  120. package/dist/src/utils/authFileDescriptor.js +1 -1
  121. package/dist/src/utils/autoUpdater.js +1 -1
  122. package/dist/src/utils/background/remote/preconditions.js +1 -1
  123. package/dist/src/utils/background/remote/remoteSession.js +1 -1
  124. package/dist/src/utils/bash/ShellSnapshot.js +1 -1
  125. package/dist/src/utils/bash/ast.js +1 -1
  126. package/dist/src/utils/bash/bashParser.js +1 -1
  127. package/dist/src/utils/bash/bashPipeCommand.js +1 -1
  128. package/dist/src/utils/bash/parser.js +1 -1
  129. package/dist/src/utils/bash/shellQuote.js +1 -1
  130. package/dist/src/utils/bash/shellQuoting.js +1 -1
  131. package/dist/src/utils/billing.js +1 -1
  132. package/dist/src/utils/caCerts.js +1 -1
  133. package/dist/src/utils/claudeInChrome/common.js +1 -1
  134. package/dist/src/utils/claudeInChrome/setupPortable.js +1 -1
  135. package/dist/src/utils/claudemd.js +1 -1
  136. package/dist/src/utils/collapseBackgroundBashNotifications.js +1 -1
  137. package/dist/src/utils/collapseReadSearch.js +1 -1
  138. package/dist/src/utils/completionCache.js +1 -1
  139. package/dist/src/utils/computerUse/common.js +1 -1
  140. package/dist/src/utils/concurrentSessions.js +1 -1
  141. package/dist/src/utils/context.js +1 -1
  142. package/dist/src/utils/cron.js +1 -1
  143. package/dist/src/utils/cronTasks.js +1 -1
  144. package/dist/src/utils/cwd.js +1 -1
  145. package/dist/src/utils/debug.js +1 -1
  146. package/dist/src/utils/debugFilter.js +1 -1
  147. package/dist/src/utils/detectRepository.js +1 -1
  148. package/dist/src/utils/diagLogs.js +1 -1
  149. package/dist/src/utils/diff.js +1 -1
  150. package/dist/src/utils/directMemberMessage.js +1 -1
  151. package/dist/src/utils/doctorDiagnostic.js +1 -1
  152. package/dist/src/utils/dxt/helpers.js +1 -1
  153. package/dist/src/utils/dxt/zip.js +1 -1
  154. package/dist/src/utils/earlyInput.js +1 -1
  155. package/dist/src/utils/editor.js +1 -1
  156. package/dist/src/utils/effort.js +1 -1
  157. package/dist/src/utils/embeddedTools.js +1 -1
  158. package/dist/src/utils/envDynamic.js +1 -1
  159. package/dist/src/utils/envUtils.js +1 -1
  160. package/dist/src/utils/execFileNoThrowPortable.js +1 -1
  161. package/dist/src/utils/execSyncWrapper.js +1 -1
  162. package/dist/src/utils/exportRenderer.js +1 -1
  163. package/dist/src/utils/extraUsage.js +1 -1
  164. package/dist/src/utils/fastMode.js +1 -1
  165. package/dist/src/utils/fileOperationAnalytics.js +1 -1
  166. package/dist/src/utils/fileRead.js +1 -1
  167. package/dist/src/utils/findExecutable.js +1 -1
  168. package/dist/src/utils/format.js +1 -1
  169. package/dist/src/utils/frontmatterParser.js +1 -1
  170. package/dist/src/utils/fsOperations.js +1 -1
  171. package/dist/src/utils/fullscreen.js +1 -1
  172. package/dist/src/utils/genericProcessUtils.js +1 -1
  173. package/dist/src/utils/getWorktreePaths.js +1 -1
  174. package/dist/src/utils/git/gitConfigParser.js +1 -1
  175. package/dist/src/utils/git/gitFilesystem.js +1 -1
  176. package/dist/src/utils/git/gitignore.js +1 -1
  177. package/dist/src/utils/gitDiff.js +1 -1
  178. package/dist/src/utils/gitSettings.js +1 -1
  179. package/dist/src/utils/glob.js +1 -1
  180. package/dist/src/utils/gracefulShutdown.js +1 -1
  181. package/dist/src/utils/groupToolUses.js +1 -1
  182. package/dist/src/utils/handlePromptSubmit.js +1 -1
  183. package/dist/src/utils/hash.js +1 -1
  184. package/dist/src/utils/hooks/fileChangedWatcher.js +1 -1
  185. package/dist/src/utils/hooks/hooksSettings.js +1 -1
  186. package/dist/src/utils/hooks/registerSkillHooks.js +1 -1
  187. package/dist/src/utils/hooks/sessionHooks.js +1 -1
  188. package/dist/src/utils/http.js +1 -1
  189. package/dist/src/utils/hyperlink.js +1 -1
  190. package/dist/src/utils/ide.js +1 -1
  191. package/dist/src/utils/idePathConversion.js +1 -1
  192. package/dist/src/utils/imagePaste.js +1 -1
  193. package/dist/src/utils/imageResizer.js +1 -1
  194. package/dist/src/utils/imageStore.js +1 -1
  195. package/dist/src/utils/inProcessTeammateHelpers.js +1 -1
  196. package/dist/src/utils/ink.js +1 -1
  197. package/dist/src/utils/jetbrains.js +1 -1
  198. package/dist/src/utils/json.js +1 -1
  199. package/dist/src/utils/listSessionsImpl.js +1 -1
  200. package/dist/src/utils/localInstaller.js +1 -1
  201. package/dist/src/utils/lockfile.js +1 -1
  202. package/dist/src/utils/logoV2Utils.js +1 -1
  203. package/dist/src/utils/markdown.js +1 -1
  204. package/dist/src/utils/mcp/dateTimeParser.js +1 -1
  205. package/dist/src/utils/mcpOutputStorage.js +1 -1
  206. package/dist/src/utils/mcpValidation.js +1 -1
  207. package/dist/src/utils/memoize.js +1 -1
  208. package/dist/src/utils/memory/types.js +1 -1
  209. package/dist/src/utils/memoryFileDetection.js +1 -1
  210. package/dist/src/utils/messageQueueManager.js +1 -1
  211. package/dist/src/utils/messages/mappers.js +1 -1
  212. package/dist/src/utils/messages/systemInit.js +1 -1
  213. package/dist/src/utils/model/antModels.js +1 -1
  214. package/dist/src/utils/model/check1mAccess.js +1 -1
  215. package/dist/src/utils/model/contextWindowUpgradeCheck.js +1 -1
  216. package/dist/src/utils/model/model.js +1 -1
  217. package/dist/src/utils/model/modelAllowlist.js +1 -1
  218. package/dist/src/utils/model/modelCapabilities.js +1 -1
  219. package/dist/src/utils/model/modelOptions.js +1 -1
  220. package/dist/src/utils/model/modelStrings.js +1 -1
  221. package/dist/src/utils/model/providerBaseUrls.js +1 -1
  222. package/dist/src/utils/model/providerCatalog.js +1 -1
  223. package/dist/src/utils/model/providerModels.js +1 -1
  224. package/dist/src/utils/model/providerProfiles.js +1 -1
  225. package/dist/src/utils/model/providerProfilesDb.js +1 -1
  226. package/dist/src/utils/model/providerSwitch.js +1 -1
  227. package/dist/src/utils/model/providers.js +1 -1
  228. package/dist/src/utils/modelCost.js +1 -1
  229. package/dist/src/utils/modifiers.js +1 -1
  230. package/dist/src/utils/mtls.js +1 -1
  231. package/dist/src/utils/nativeInstaller/download.js +1 -1
  232. package/dist/src/utils/nativeInstaller/installer.js +1 -1
  233. package/dist/src/utils/nativeInstaller/packageManagers.js +1 -1
  234. package/dist/src/utils/nativeInstaller/pidLock.js +1 -1
  235. package/dist/src/utils/notebook.js +1 -1
  236. package/dist/src/utils/pasteStore.js +1 -1
  237. package/dist/src/utils/path.js +1 -1
  238. package/dist/src/utils/permissions/PermissionMode.js +1 -1
  239. package/dist/src/utils/permissions/PermissionPromptToolResultSchema.js +1 -1
  240. package/dist/src/utils/permissions/PermissionUpdate.js +1 -1
  241. package/dist/src/utils/permissions/PermissionUpdateSchema.js +1 -1
  242. package/dist/src/utils/permissions/autoModeState.js +1 -1
  243. package/dist/src/utils/permissions/bypassPermissionsKillswitch.js +1 -1
  244. package/dist/src/utils/permissions/filesystem.js +1 -1
  245. package/dist/src/utils/permissions/getNextPermissionMode.js +1 -1
  246. package/dist/src/utils/permissions/pathValidation.js +1 -1
  247. package/dist/src/utils/permissions/permissionRuleParser.js +1 -1
  248. package/dist/src/utils/permissions/permissionsDb.js +1 -1
  249. package/dist/src/utils/permissions/permissionsLoader.js +1 -1
  250. package/dist/src/utils/permissions/shellRuleMatching.js +1 -1
  251. package/dist/src/utils/planModeV2.js +1 -1
  252. package/dist/src/utils/plans.js +1 -1
  253. package/dist/src/utils/platform.js +1 -1
  254. package/dist/src/utils/plugins/addDirPluginSettings.js +1 -1
  255. package/dist/src/utils/plugins/cacheUtils.js +1 -1
  256. package/dist/src/utils/plugins/dependencyResolver.js +1 -1
  257. package/dist/src/utils/plugins/fetchTelemetry.js +1 -1
  258. package/dist/src/utils/plugins/gitAvailability.js +1 -1
  259. package/dist/src/utils/plugins/hintRecommendation.js +1 -1
  260. package/dist/src/utils/plugins/installedPluginsManager.js +1 -1
  261. package/dist/src/utils/plugins/loadPluginAgents.js +1 -1
  262. package/dist/src/utils/plugins/loadPluginCommands.js +1 -1
  263. package/dist/src/utils/plugins/loadPluginHooks.js +1 -1
  264. package/dist/src/utils/plugins/loadPluginOutputStyles.js +1 -1
  265. package/dist/src/utils/plugins/lspPluginIntegration.js +1 -1
  266. package/dist/src/utils/plugins/lspRecommendation.js +1 -1
  267. package/dist/src/utils/plugins/managedPlugins.js +1 -1
  268. package/dist/src/utils/plugins/marketplaceHelpers.js +1 -1
  269. package/dist/src/utils/plugins/marketplaceManager.js +1 -1
  270. package/dist/src/utils/plugins/mcpPluginIntegration.js +1 -1
  271. package/dist/src/utils/plugins/mcpbHandler.js +1 -1
  272. package/dist/src/utils/plugins/officialMarketplaceGcs.js +1 -1
  273. package/dist/src/utils/plugins/officialMarketplaceStartupCheck.js +1 -1
  274. package/dist/src/utils/plugins/orphanedPluginFilter.js +1 -1
  275. package/dist/src/utils/plugins/performStartupChecks.js +1 -1
  276. package/dist/src/utils/plugins/pluginAutoupdate.js +1 -1
  277. package/dist/src/utils/plugins/pluginBlocklist.js +1 -1
  278. package/dist/src/utils/plugins/pluginDirectories.js +1 -1
  279. package/dist/src/utils/plugins/pluginFlagging.js +1 -1
  280. package/dist/src/utils/plugins/pluginInstallationHelpers.js +1 -1
  281. package/dist/src/utils/plugins/pluginLoader.js +1 -1
  282. package/dist/src/utils/plugins/pluginOptionsStorage.js +1 -1
  283. package/dist/src/utils/plugins/pluginPolicy.js +1 -1
  284. package/dist/src/utils/plugins/pluginStartupCheck.js +1 -1
  285. package/dist/src/utils/plugins/pluginVersioning.js +1 -1
  286. package/dist/src/utils/plugins/reconciler.js +1 -1
  287. package/dist/src/utils/plugins/refresh.js +1 -1
  288. package/dist/src/utils/plugins/schemas.js +1 -1
  289. package/dist/src/utils/plugins/walkPluginMarkdown.js +1 -1
  290. package/dist/src/utils/plugins/zipCache.js +1 -1
  291. package/dist/src/utils/powershell/parser.js +1 -1
  292. package/dist/src/utils/processUserInput/processBashCommand.js +1 -1
  293. package/dist/src/utils/processUserInput/processSlashCommand.js +1 -1
  294. package/dist/src/utils/processUserInput/processTextPrompt.js +1 -1
  295. package/dist/src/utils/processUserInput/processUserInput.js +1 -1
  296. package/dist/src/utils/profilerBase.js +1 -1
  297. package/dist/src/utils/promptCategory.js +1 -1
  298. package/dist/src/utils/promptEditor.js +1 -1
  299. package/dist/src/utils/promptShellExecution.js +1 -1
  300. package/dist/src/utils/proxy.js +1 -1
  301. package/dist/src/utils/queryHelpers.js +1 -1
  302. package/dist/src/utils/queryProfiler.js +1 -1
  303. package/dist/src/utils/queueProcessor.js +1 -1
  304. package/dist/src/utils/readFileInRange.js +1 -1
  305. package/dist/src/utils/releaseNotes.js +1 -1
  306. package/dist/src/utils/renderOptions.js +1 -1
  307. package/dist/src/utils/ripgrep.js +1 -1
  308. package/dist/src/utils/sandbox/sandbox-adapter.js +1 -1
  309. package/dist/src/utils/sdkEventQueue.js +1 -1
  310. package/dist/src/utils/secureStorage/index.js +1 -1
  311. package/dist/src/utils/secureStorage/macOsKeychainHelpers.js +1 -1
  312. package/dist/src/utils/secureStorage/macOsKeychainStorage.js +1 -1
  313. package/dist/src/utils/secureStorage/plainTextStorage.js +1 -1
  314. package/dist/src/utils/secureStorage/sqliteStorage.js +1 -1
  315. package/dist/src/utils/sessionEnvironment.js +1 -1
  316. package/dist/src/utils/sessionIngressAuth.js +1 -1
  317. package/dist/src/utils/sessionRestore.js +1 -1
  318. package/dist/src/utils/sessionStart.js +1 -1
  319. package/dist/src/utils/sessionTitle.js +1 -1
  320. package/dist/src/utils/settings/managedPath.js +1 -1
  321. package/dist/src/utils/settings/mdm/rawRead.js +1 -1
  322. package/dist/src/utils/settings/mdm/settings.js +1 -1
  323. package/dist/src/utils/settings/permissionValidation.js +1 -1
  324. package/dist/src/utils/settings/pluginOnlyPolicy.js +1 -1
  325. package/dist/src/utils/settings/schemaOutput.js +1 -1
  326. package/dist/src/utils/settings/settings.js +1 -1
  327. package/dist/src/utils/settings/types.js +1 -1
  328. package/dist/src/utils/settings/validateEditTool.js +1 -1
  329. package/dist/src/utils/settings/validation.js +1 -1
  330. package/dist/src/utils/shell/bashProvider.js +1 -1
  331. package/dist/src/utils/shell/powershellDetection.js +1 -1
  332. package/dist/src/utils/shell/powershellProvider.js +1 -1
  333. package/dist/src/utils/shell/readOnlyCommandValidation.js +1 -1
  334. package/dist/src/utils/shell/resolveDefaultShell.js +1 -1
  335. package/dist/src/utils/shell/shellToolUtils.js +1 -1
  336. package/dist/src/utils/shell/specPrefix.js +1 -1
  337. package/dist/src/utils/shellConfig.js +1 -1
  338. package/dist/src/utils/sideQuestion.js +1 -1
  339. package/dist/src/utils/skills/skillChangeDetector.js +1 -1
  340. package/dist/src/utils/slashCommandParsing.js +1 -1
  341. package/dist/src/utils/sliceAnsi.js +1 -1
  342. package/dist/src/utils/slowOperations.js +1 -1
  343. package/dist/src/utils/standaloneAgent.js +1 -1
  344. package/dist/src/utils/startupProfiler.js +1 -1
  345. package/dist/src/utils/staticRender.js +1 -1
  346. package/dist/src/utils/status.js +1 -1
  347. package/dist/src/utils/statusNoticeDefinitions.js +1 -1
  348. package/dist/src/utils/suggestions/commandSuggestions.js +1 -1
  349. package/dist/src/utils/suggestions/directoryCompletion.js +1 -1
  350. package/dist/src/utils/suggestions/shellHistoryCompletion.js +1 -1
  351. package/dist/src/utils/suggestions/skillUsageTracking.js +1 -1
  352. package/dist/src/utils/suggestions/slackChannelSuggestions.js +1 -1
  353. package/dist/src/utils/swarm/backends/detection.js +1 -1
  354. package/dist/src/utils/swarm/permissionSync.js +1 -1
  355. package/dist/src/utils/swarm/reconnection.js +1 -1
  356. package/dist/src/utils/swarm/spawnUtils.js +1 -91
  357. package/dist/src/utils/swarm/teammateInit.js +1 -1
  358. package/dist/src/utils/systemDirectories.js +1 -1
  359. package/dist/src/utils/systemPrompt.js +1 -1
  360. package/dist/src/utils/systemTheme.js +1 -1
  361. package/dist/src/utils/task/TaskOutput.js +1 -1
  362. package/dist/src/utils/task/diskOutput.js +1 -1
  363. package/dist/src/utils/tasks.js +1 -1
  364. package/dist/src/utils/teamDiscovery.js +1 -1
  365. package/dist/src/utils/teamMemoryOps.js +1 -1
  366. package/dist/src/utils/teammateMailbox.js +1 -1
  367. package/dist/src/utils/telemetry/betaSessionTracing.js +1 -1
  368. package/dist/src/utils/telemetry/bigqueryExporter.js +1 -1
  369. package/dist/src/utils/telemetry/events.js +1 -1
  370. package/dist/src/utils/telemetry/instrumentation.js +1 -1
  371. package/dist/src/utils/telemetry/logger.js +1 -1
  372. package/dist/src/utils/telemetry/perfettoTracing.js +1 -1
  373. package/dist/src/utils/telemetry/pluginTelemetry.js +1 -1
  374. package/dist/src/utils/telemetry/sessionTracing.js +1 -1
  375. package/dist/src/utils/telemetryAttributes.js +1 -1
  376. package/dist/src/utils/teleport/api.js +1 -1
  377. package/dist/src/utils/teleport/environments.js +1 -1
  378. package/dist/src/utils/teleport/gitBundle.js +1 -1
  379. package/dist/src/utils/teleport.js +1 -1
  380. package/dist/src/utils/tempfile.js +1 -1
  381. package/dist/src/utils/terminal.js +1 -1
  382. package/dist/src/utils/terminalPanel.js +1 -1
  383. package/dist/src/utils/textHighlighting.js +1 -1
  384. package/dist/src/utils/theme.js +1 -1
  385. package/dist/src/utils/themes/bootstrap.js +1 -1
  386. package/dist/src/utils/themes/loader.js +1 -1
  387. package/dist/src/utils/thinking.js +1 -1
  388. package/dist/src/utils/tmuxSocket.js +1 -1
  389. package/dist/src/utils/tokens.js +1 -1
  390. package/dist/src/utils/toolPool.js +1 -1
  391. package/dist/src/utils/toolResultStorage.js +1 -1
  392. package/dist/src/utils/transcriptSearch.js +1 -1
  393. package/dist/src/utils/truncate.js +1 -1
  394. package/dist/src/utils/ultraplan/keyword.js +1 -1
  395. package/dist/src/utils/unaryLogging.js +1 -1
  396. package/dist/src/utils/undercover.js +1 -1
  397. package/dist/src/utils/user.js +1 -1
  398. package/dist/src/utils/userPromptKeywords.js +1 -1
  399. package/dist/src/utils/which.js +1 -1
  400. package/dist/src/utils/windowsPaths.js +1 -1
  401. package/dist/src/utils/worktree.js +1 -1
  402. package/dist/src/utils/zodToJsonSchema.js +1 -1
  403. package/dist/src/vim/operators.js +1 -1
  404. package/dist/src/vim/textObjects.js +1 -1
  405. package/dist/src/vim/transitions.js +1 -1
  406. package/dist/src/voice/voiceModeEnabled.js +1 -1
  407. package/dist/src/webapp/auth.js +1 -1
  408. package/dist/src/webapp/tunnel.js +1 -1
  409. package/dist/src/whatsapp/bridge.js +1 -1
  410. package/dist/src/whatsapp/mirror.js +1 -1
  411. package/package.json +41 -3
@@ -1 +1 @@
1
- import{createHash as t}from"crypto";import{getIsNonInteractiveSession as e}from"../../bootstrap/state.js";import{getFeatureValue_CACHED_MAY_BE_STALE as n}from"../../services/analytics/growthbook.js";import{sanitizeToolNameForAnalytics as s}from"../../services/analytics/metadata.js";import{isEnvTruthy as o}from"../envUtils.js";import{jsonParse as r,jsonStringify as a}from"../slowOperations.js";import{logOTelEvent as i}from"./events.js";const c=new Set,u=new Map;export function clearBetaTracingState(){c.clear(),u.clear()}export function isBetaTracingEnabled(){return!(!o(process.env.ENABLE_BETA_TRACING_DETAILED)||!Boolean(process.env.BETA_TRACING_ENDPOINT))&&("ant"===process.env.USER_TYPE||e()||n("tengu_trace_lantern",!1))}export function truncateContent(t,e=61440){return t.length<=e?{content:t,truncated:!1}:{content:t.slice(0,e)+"\n\n[TRUNCATED - Content exceeds 60KB limit]",truncated:!0}}function shortHash(e){return t("sha256").update(e).digest("hex").slice(0,12)}function hashMessage(t){return`msg_${shortHash(a(t.message.content))}`}const l=/^<system-reminder>\n?([\s\S]*?)\n?<\/system-reminder>$/;function extractSystemReminderContent(t){const e=t.trim().match(l);return e&&e[1]?e[1].trim():null}export function addBetaInteractionAttributes(t,e){if(!isBetaTracingEnabled())return;const{content:n,truncated:s}=truncateContent(`[USER PROMPT]\n${e}`);t.setAttributes({new_context:n,...s&&{new_context_truncated:!0,new_context_original_length:e.length}})}export function addBetaLLMRequestAttributes(t,e,n){if(isBetaTracingEnabled()){if(e?.systemPrompt){const n=`sp_${shortHash(e.systemPrompt)}`,s=e.systemPrompt.slice(0,500);if(t.setAttribute("system_prompt_hash",n),t.setAttribute("system_prompt_preview",s),t.setAttribute("system_prompt_length",e.systemPrompt.length),!c.has(n)){c.add(n);const{content:t,truncated:s}=truncateContent(e.systemPrompt);i("system_prompt",{system_prompt_hash:n,system_prompt:t,system_prompt_length:String(e.systemPrompt.length),...s&&{system_prompt_truncated:"true"}})}}if(e?.tools)try{const n=r(e.tools).map(t=>{const e=a(t),n=shortHash(e);return{name:"string"==typeof t.name?t.name:"unknown",hash:n,json:e}});t.setAttribute("tools",a(n.map(({name:t,hash:e})=>({name:t,hash:e})))),t.setAttribute("tools_count",n.length);for(const{name:t,hash:e,json:o}of n)if(!c.has(`tool_${e}`)){c.add(`tool_${e}`);const{content:n,truncated:r}=truncateContent(o);i("tool",{tool_name:s(t),tool_hash:e,tool:n,...r&&{tool_truncated:"true"}})}}catch{t.setAttribute("tools_parse_error",!0)}if(n&&n.length>0&&e?.querySource){const s=e.querySource,o=u.get(s);let r=0;if(o)for(let t=0;t<n.length;t++){const e=n[t];if(e&&hashMessage(e)===o){r=t+1;break}}const i=n.slice(r).filter(t=>"user"===t.type);if(i.length>0){const{contextParts:e,systemReminders:o}=function(t){const e=[],n=[];for(const s of t){const t=s.message.content;if("string"==typeof t){const s=extractSystemReminderContent(t);s?n.push(s):e.push(`[USER]\n${t}`)}else if(Array.isArray(t))for(const s of t)if("text"===s.type){const t=extractSystemReminderContent(s.text);t?n.push(t):e.push(`[USER]\n${s.text}`)}else if("tool_result"===s.type){const t="string"==typeof s.content?s.content:a(s.content),o=extractSystemReminderContent(t);o?n.push(o):e.push(`[TOOL RESULT: ${s.tool_use_id}]\n${t}`)}}return{contextParts:e,systemReminders:n}}(i);if(e.length>0){const n=e.join("\n\n---\n\n"),{content:s,truncated:o}=truncateContent(n);t.setAttributes({new_context:s,new_context_message_count:i.length,...o&&{new_context_truncated:!0,new_context_original_length:n.length}})}if(o.length>0){const e=o.join("\n\n---\n\n"),{content:n,truncated:s}=truncateContent(e);t.setAttributes({system_reminders:n,system_reminders_count:o.length,...s&&{system_reminders_truncated:!0,system_reminders_original_length:e.length}})}const r=n[n.length-1];r&&u.set(s,hashMessage(r))}}}}export function addBetaLLMResponseAttributes(t,e){if(isBetaTracingEnabled()&&e){if(void 0!==e.modelOutput){const{content:n,truncated:s}=truncateContent(e.modelOutput);t["response.model_output"]=n,s&&(t["response.model_output_truncated"]=!0,t["response.model_output_original_length"]=e.modelOutput.length)}if("ant"===process.env.USER_TYPE&&void 0!==e.thinkingOutput){const{content:n,truncated:s}=truncateContent(e.thinkingOutput);t["response.thinking_output"]=n,s&&(t["response.thinking_output_truncated"]=!0,t["response.thinking_output_original_length"]=e.thinkingOutput.length)}}}export function addBetaToolInputAttributes(t,e,n){if(!isBetaTracingEnabled())return;const{content:s,truncated:o}=truncateContent(`[TOOL INPUT: ${e}]\n${n}`);t.setAttributes({tool_input:s,...o&&{tool_input_truncated:!0,tool_input_original_length:n.length}})}export function addBetaToolResultAttributes(t,e,n){if(!isBetaTracingEnabled())return;const{content:s,truncated:o}=truncateContent(`[TOOL RESULT: ${e}]\n${n}`);t.new_context=s,o&&(t.new_context_truncated=!0,t.new_context_original_length=n.length)}
1
+ import{createHash as t}from"crypto";import{getIsNonInteractiveSession as e}from"../../bootstrap/state.js";import{getFeatureValue_CACHED_MAY_BE_STALE as n}from"../../services/analytics/growthbook.js";import{sanitizeToolNameForAnalytics as o}from"../../services/analytics/metadata.js";import{isEnvTruthy as s}from"../envUtils.js";import{jsonParse as r,jsonStringify as i}from"../slowOperations.js";import{logOTelEvent as c}from"./events.js";const a=new Set,u=new Map;export function clearBetaTracingState(){a.clear(),u.clear()}export function isBetaTracingEnabled(){return!(!s(process.env.ENABLE_BETA_TRACING_DETAILED)||!Boolean(process.env.BETA_TRACING_ENDPOINT))&&("ant"===process.env.USER_TYPE||(e()||n("tengu_trace_lantern",!1)))}export function truncateContent(t,e=61440){return t.length<=e?{content:t,truncated:!1}:{content:t.slice(0,e)+"\n\n[TRUNCATED - Content exceeds 60KB limit]",truncated:!0}}function shortHash(e){return t("sha256").update(e).digest("hex").slice(0,12)}function hashMessage(t){return`msg_${shortHash(i(t.message.content))}`}const m=/^<system-reminder>\n?([\s\S]*?)\n?<\/system-reminder>$/;function extractSystemReminderContent(t){const e=t.trim().match(m);return e&&e[1]?e[1].trim():null}export function addBetaInteractionAttributes(t,e){if(!isBetaTracingEnabled())return;const{content:n,truncated:o}=truncateContent(`[USER PROMPT]\n${e}`);t.setAttributes({new_context:n,...o&&{new_context_truncated:!0,new_context_original_length:e.length}})}export function addBetaLLMRequestAttributes(t,e,n){if(isBetaTracingEnabled()){if(e?.systemPrompt){const n=`sp_${shortHash(e.systemPrompt)}`,o=e.systemPrompt.slice(0,500);if(t.setAttribute("system_prompt_hash",n),t.setAttribute("system_prompt_preview",o),t.setAttribute("system_prompt_length",e.systemPrompt.length),!a.has(n)){a.add(n);const{content:t,truncated:o}=truncateContent(e.systemPrompt);c("system_prompt",{system_prompt_hash:n,system_prompt:t,system_prompt_length:String(e.systemPrompt.length),...o&&{system_prompt_truncated:"true"}})}}if(e?.tools)try{const n=r(e.tools).map(t=>{const e=i(t),n=shortHash(e);return{name:"string"==typeof t.name?t.name:"unknown",hash:n,json:e}});t.setAttribute("tools",i(n.map(({name:t,hash:e})=>({name:t,hash:e})))),t.setAttribute("tools_count",n.length);for(const{name:t,hash:e,json:s}of n)if(!a.has(`tool_${e}`)){a.add(`tool_${e}`);const{content:n,truncated:r}=truncateContent(s);c("tool",{tool_name:o(t),tool_hash:e,tool:n,...r&&{tool_truncated:"true"}})}}catch{t.setAttribute("tools_parse_error",!0)}if(n&&n.length>0&&e?.querySource){const o=e.querySource,s=u.get(o);let r=0;if(s)for(let t=0;t<n.length;t++){const e=n[t];if(e&&hashMessage(e)===s){r=t+1;break}}const c=n.slice(r).filter(t=>"user"===t.type);if(c.length>0){const{contextParts:e,systemReminders:s}=function(t){const e=[],n=[];for(const o of t){const t=o.message.content;if("string"==typeof t){const o=extractSystemReminderContent(t);o?n.push(o):e.push(`[USER]\n${t}`)}else if(Array.isArray(t))for(const o of t)if("text"===o.type){const t=extractSystemReminderContent(o.text);t?n.push(t):e.push(`[USER]\n${o.text}`)}else if("tool_result"===o.type){const t="string"==typeof o.content?o.content:i(o.content),s=extractSystemReminderContent(t);s?n.push(s):e.push(`[TOOL RESULT: ${o.tool_use_id}]\n${t}`)}}return{contextParts:e,systemReminders:n}}(c);if(e.length>0){const n=e.join("\n\n---\n\n"),{content:o,truncated:s}=truncateContent(n);t.setAttributes({new_context:o,new_context_message_count:c.length,...s&&{new_context_truncated:!0,new_context_original_length:n.length}})}if(s.length>0){const e=s.join("\n\n---\n\n"),{content:n,truncated:o}=truncateContent(e);t.setAttributes({system_reminders:n,system_reminders_count:s.length,...o&&{system_reminders_truncated:!0,system_reminders_original_length:e.length}})}const r=n[n.length-1];r&&u.set(o,hashMessage(r))}}}}export function addBetaLLMResponseAttributes(t,e){if(isBetaTracingEnabled()&&e){if(void 0!==e.modelOutput){const{content:n,truncated:o}=truncateContent(e.modelOutput);t["response.model_output"]=n,o&&(t["response.model_output_truncated"]=!0,t["response.model_output_original_length"]=e.modelOutput.length)}if("ant"===process.env.USER_TYPE&&void 0!==e.thinkingOutput){const{content:n,truncated:o}=truncateContent(e.thinkingOutput);t["response.thinking_output"]=n,o&&(t["response.thinking_output_truncated"]=!0,t["response.thinking_output_original_length"]=e.thinkingOutput.length)}}}export function addBetaToolInputAttributes(t,e,n){if(!isBetaTracingEnabled())return;const{content:o,truncated:s}=truncateContent(`[TOOL INPUT: ${e}]\n${n}`);t.setAttributes({tool_input:o,...s&&{tool_input_truncated:!0,tool_input_original_length:n.length}})}export function addBetaToolResultAttributes(t,e,n){if(!isBetaTracingEnabled())return;const{content:o,truncated:s}=truncateContent(`[TOOL RESULT: ${e}]\n${n}`);t.new_context=o,s&&(t.new_context_truncated=!0,t.new_context_original_length=n.length)}
@@ -1 +1 @@
1
- import{ExportResultCode as e}from"@opentelemetry/core";import{AggregationTemporality as t}from"@opentelemetry/sdk-metrics";import r from"axios";import{checkMetricsEnabled as s}from"src/services/api/metricsOptOut.js";import{getIsNonInteractiveSession as o}from"../../bootstrap/state.js";import{getSubscriptionType as i,isClaudeAISubscriber as n}from"../auth.js";import{checkHasTrustDialogAccepted as a}from"../config.js";import{logForDebugging as c}from"../debug.js";import{errorMessage as p,toError as u}from"../errors.js";import{getAuthHeaders as m}from"../http.js";import{logError as d}from"../log.js";import{jsonStringify as l}from"../slowOperations.js";import{getContextCodeUserAgent as g}from"../userAgent.js";export class BigQueryMetricsExporter{endpoint;timeout;pendingExports=[];isShutdown=!1;constructor(e={}){this.endpoint="",this.timeout=e.timeout||5e3}async export(t,r){if(this.isShutdown)return void r({code:e.FAILED,error:new Error("Exporter has been shutdown")});const s=this.doExport(t,r);this.pendingExports.push(s),s.finally(()=>{const e=this.pendingExports.indexOf(s);e>-1&&this.pendingExports.splice(e,1)})}async doExport(t,i){try{if(!a()&&!o())return c("BigQuery metrics export: trust not established, skipping"),void i({code:e.SUCCESS});if(!(await s()).enabled)return c("Metrics export disabled by organization setting"),void i({code:e.SUCCESS});const n=this.transformMetricsForInternal(t),p=m();if(p.error)return c(`Metrics export failed: ${p.error}`),void i({code:e.FAILED,error:new Error(p.error)});const u={"Content-Type":"application/json","User-Agent":g(),...p.headers},d=await r.post(this.endpoint,n,{timeout:this.timeout,headers:u});c("BigQuery metrics exported successfully"),c(`BigQuery API Response: ${l(d.data,null,2)}`),i({code:e.SUCCESS})}catch(t){c(`BigQuery metrics export failed: ${p(t)}`),d(t),i({code:e.FAILED,error:u(t)})}}transformMetricsForInternal(e){const r=e.resource.attributes,s={"service.name":r["service.name"]||"claude-code","service.version":r["service.version"]||"unknown","os.type":r["os.type"]||"unknown","os.version":r["os.version"]||"unknown","host.arch":r["host.arch"]||"unknown","aggregation.temporality":this.selectAggregationTemporality()===t.DELTA?"delta":"cumulative"};if(r["wsl.version"]&&(s["wsl.version"]=r["wsl.version"]),n()){s["user.customer_type"]="claude_ai";const e=i();e&&(s["user.subscription_type"]=e)}else s["user.customer_type"]="api";return{resource_attributes:s,metrics:e.scopeMetrics.flatMap(e=>e.metrics.map(e=>({name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit,data_points:this.extractDataPoints(e)})))}}extractDataPoints(e){return(e.dataPoints||[]).filter(e=>"number"==typeof e.value).map(e=>({attributes:this.convertAttributes(e.attributes),value:e.value,timestamp:this.hrTimeToISOString(e.endTime||e.startTime||[Date.now()/1e3,0])}))}async shutdown(){this.isShutdown=!0,await this.forceFlush(),c("BigQuery metrics exporter shutdown complete")}async forceFlush(){await Promise.all(this.pendingExports),c("BigQuery metrics exporter flush complete")}convertAttributes(e){const t={};if(e)for(const[r,s]of Object.entries(e))null!=s&&(t[r]=String(s));return t}hrTimeToISOString(e){const[t,r]=e;return new Date(1e3*t+r/1e6).toISOString()}selectAggregationTemporality(){return t.DELTA}}
1
+ import{ExportResultCode as t}from"@opentelemetry/core";import{AggregationTemporality as e}from"@opentelemetry/sdk-metrics";import r from"axios";import{checkMetricsEnabled as o}from"../../services/api/metricsOptOut.js";import{getIsNonInteractiveSession as s}from"../../bootstrap/state.js";import{getSubscriptionType as i,isClaudeAISubscriber as n}from"../auth.js";import{checkHasTrustDialogAccepted as a}from"../config.js";import{logForDebugging as p}from"../debug.js";import{errorMessage as c,toError as u}from"../errors.js";import{getAuthHeaders as m}from"../http.js";import{logError as d}from"../log.js";import{jsonStringify as l}from"../slowOperations.js";import{getContextCodeUserAgent as h}from"../userAgent.js";export class BigQueryMetricsExporter{endpoint;timeout;pendingExports=[];isShutdown=!1;constructor(t={}){this.endpoint="",this.timeout=t.timeout||5e3}async export(e,r){if(this.isShutdown)return void r({code:t.FAILED,error:new Error("Exporter has been shutdown")});const o=this.doExport(e,r);this.pendingExports.push(o),o.finally(()=>{const t=this.pendingExports.indexOf(o);t>-1&&this.pendingExports.splice(t,1)})}async doExport(e,i){try{if(!(a()||s()))return p("BigQuery metrics export: trust not established, skipping"),void i({code:t.SUCCESS});if(!(await o()).enabled)return p("Metrics export disabled by organization setting"),void i({code:t.SUCCESS});const n=this.transformMetricsForInternal(e),c=m();if(c.error)return p(`Metrics export failed: ${c.error}`),void i({code:t.FAILED,error:new Error(c.error)});const u={"Content-Type":"application/json","User-Agent":h(),...c.headers},d=await r.post(this.endpoint,n,{timeout:this.timeout,headers:u});p("BigQuery metrics exported successfully"),p(`BigQuery API Response: ${l(d.data,null,2)}`),i({code:t.SUCCESS})}catch(e){p(`BigQuery metrics export failed: ${c(e)}`),d(e),i({code:t.FAILED,error:u(e)})}}transformMetricsForInternal(t){const r=t.resource.attributes,o={"service.name":r["service.name"]||"claude-code","service.version":r["service.version"]||"unknown","os.type":r["os.type"]||"unknown","os.version":r["os.version"]||"unknown","host.arch":r["host.arch"]||"unknown","aggregation.temporality":this.selectAggregationTemporality()===e.DELTA?"delta":"cumulative"};if(r["wsl.version"]&&(o["wsl.version"]=r["wsl.version"]),n()){o["user.customer_type"]="claude_ai";const t=i();t&&(o["user.subscription_type"]=t)}else o["user.customer_type"]="api";return{resource_attributes:o,metrics:t.scopeMetrics.flatMap(t=>t.metrics.map(t=>({name:t.descriptor.name,description:t.descriptor.description,unit:t.descriptor.unit,data_points:this.extractDataPoints(t)})))}}extractDataPoints(t){return(t.dataPoints||[]).filter(t=>"number"==typeof t.value).map(t=>({attributes:this.convertAttributes(t.attributes),value:t.value,timestamp:this.hrTimeToISOString(t.endTime||t.startTime||[Date.now()/1e3,0])}))}async shutdown(){this.isShutdown=!0,await this.forceFlush(),p("BigQuery metrics exporter shutdown complete")}async forceFlush(){await Promise.all(this.pendingExports),p("BigQuery metrics exporter flush complete")}convertAttributes(t){const e={};if(t)for(const[r,o]of Object.entries(t))null!=o&&(e[r]=String(o));return e}hrTimeToISOString(t){const[e,r]=t;return new Date(1e3*e+r/1e6).toISOString()}selectAggregationTemporality(){return e.DELTA}}
@@ -1 +1 @@
1
- import{getEventLogger as e,getPromptId as t}from"src/bootstrap/state.js";import{logForDebugging as r}from"../debug.js";import{isEnvTruthy as o}from"../envUtils.js";import{getTelemetryAttributes as s}from"../telemetryAttributes.js";let n=0,i=!1;export function redactIfDisabled(e){return o(process.env.OTEL_LOG_USER_PROMPTS)?e:"<REDACTED>"}export async function logOTelEvent(o,p={}){const a=e();if(!a)return void(i||(i=!0,r(`[3P telemetry] Event dropped (no event logger initialized): ${o}`,{level:"warn"})));if("test"===process.env.NODE_ENV)return;const c={...s(),"event.name":o,"event.timestamp":(new Date).toISOString(),"event.sequence":n++},m=t();m&&(c["prompt.id"]=m);const v=process.env.CONTEXT_CODE_WORKSPACE_HOST_PATHS??process.env.CLAUDE_CODE_WORKSPACE_HOST_PATHS;v&&(c["workspace.host_paths"]=v.split("|"));for(const[e,t]of Object.entries(p))void 0!==t&&(c[e]=t);a.emit({body:`claude_code.${o}`,attributes:c})}
1
+ import{getEventLogger as e,getPromptId as t}from"../../bootstrap/state.js";import{logForDebugging as o}from"../debug.js";import{isEnvTruthy as r}from"../envUtils.js";import{getTelemetryAttributes as n}from"../telemetryAttributes.js";let s=0,i=!1;export function redactIfDisabled(e){return r(process.env.OTEL_LOG_USER_PROMPTS)?e:"<REDACTED>"}export async function logOTelEvent(r,p={}){const c=e();if(!c)return void(i||(i=!0,o(`[3P telemetry] Event dropped (no event logger initialized): ${r}`,{level:"warn"})));if("test"===process.env.NODE_ENV)return;const m={...n(),"event.name":r,"event.timestamp":(new Date).toISOString(),"event.sequence":s++},a=t();a&&(m["prompt.id"]=a);const v=process.env.CONTEXT_CODE_WORKSPACE_HOST_PATHS??process.env.CLAUDE_CODE_WORKSPACE_HOST_PATHS;v&&(m["workspace.host_paths"]=v.split("|"));for(const[e,t]of Object.entries(p))void 0!==t&&(m[e]=t);c.emit({body:`claude_code.${r}`,attributes:m})}
@@ -1 +1 @@
1
- import{MACRO as e}from"../../recovery/bunBundleShim.js";import{DiagLogLevel as r,diag as t,trace as o}from"@opentelemetry/api";import{logs as s}from"@opentelemetry/api-logs";import{envDetector as n,hostDetector as E,osDetector as T,resourceFromAttributes as p}from"@opentelemetry/resources";import{BatchLogRecordProcessor as c,ConsoleLogRecordExporter as i,LoggerProvider as a}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as O,MeterProvider as l,PeriodicExportingMetricReader as _}from"@opentelemetry/sdk-metrics";import{BasicTracerProvider as m,BatchSpanProcessor as R,ConsoleSpanExporter as L}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as u,ATTR_SERVICE_VERSION as P,SEMRESATTRS_HOST_ARCH as f}from"@opentelemetry/semantic-conventions";import{HttpsProxyAgent as g}from"https-proxy-agent";import{getLoggerProvider as h,getMeterProvider as v,getTracerProvider as y,setEventLogger as C,setLoggerProvider as w,setMeterProvider as d,setTracerProvider as S}from"src/bootstrap/state.js";import{getOtelHeadersFromHelper as x,getSubscriptionType as A,is1PApiCustomer as M,isClaudeAISubscriber as N}from"src/utils/auth.js";import{getPlatform as X,getWslVersion as b}from"src/utils/platform.js";import{getCACertificates as D}from"../caCerts.js";import{registerCleanup as I}from"../cleanupRegistry.js";import{getHasFormattedOutput as U,logForDebugging as j}from"../debug.js";import{isEnvTruthy as k}from"../envUtils.js";import{errorMessage as F}from"../errors.js";import{getMTLSConfig as $}from"../mtls.js";import{getProxyUrl as H,shouldBypassProxy as B}from"../proxy.js";import{getSettings_DEPRECATED as G}from"../settings/settings.js";import{jsonStringify as V}from"../slowOperations.js";import{profileCheckpoint as Y}from"../startupProfiler.js";import{isBetaTracingEnabled as W}from"./betaSessionTracing.js";import{BigQueryMetricsExporter as z}from"./bigqueryExporter.js";import{ClaudeCodeDiagLogger as q}from"./logger.js";import{initializePerfettoTracing as Q}from"./perfettoTracing.js";import{endInteractionSpan as J,isEnhancedTelemetryEnabled as K}from"./sessionTracing.js";class TelemetryTimeoutError extends Error{}function telemetryTimeout(e,r){return new Promise((t,o)=>{setTimeout((e,r)=>e(new TelemetryTimeoutError(r)),e,o,r).unref()})}export function bootstrapTelemetry(){"ant"===process.env.USER_TYPE&&(process.env.ANT_OTEL_METRICS_EXPORTER&&(process.env.OTEL_METRICS_EXPORTER=process.env.ANT_OTEL_METRICS_EXPORTER),process.env.ANT_OTEL_LOGS_EXPORTER&&(process.env.OTEL_LOGS_EXPORTER=process.env.ANT_OTEL_LOGS_EXPORTER),process.env.ANT_OTEL_TRACES_EXPORTER&&(process.env.OTEL_TRACES_EXPORTER=process.env.ANT_OTEL_TRACES_EXPORTER),process.env.ANT_OTEL_EXPORTER_OTLP_PROTOCOL&&(process.env.OTEL_EXPORTER_OTLP_PROTOCOL=process.env.ANT_OTEL_EXPORTER_OTLP_PROTOCOL),process.env.ANT_OTEL_EXPORTER_OTLP_ENDPOINT&&(process.env.OTEL_EXPORTER_OTLP_ENDPOINT=process.env.ANT_OTEL_EXPORTER_OTLP_ENDPOINT),process.env.ANT_OTEL_EXPORTER_OTLP_HEADERS&&(process.env.OTEL_EXPORTER_OTLP_HEADERS=process.env.ANT_OTEL_EXPORTER_OTLP_HEADERS)),process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE||(process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE="delta")}export function parseExporterTypes(e){return(e||"").trim().split(",").filter(Boolean).map(e=>e.trim()).filter(e=>"none"!==e)}export function isTelemetryEnabled(){return k(process.env.CONTEXT_CODE_ENABLE_TELEMETRY)||k(process.env.CLAUDE_CODE_ENABLE_TELEMETRY)}export async function initializeTelemetry(){if(Y("telemetry_init_start"),bootstrapTelemetry(),U())for(const e of["OTEL_METRICS_EXPORTER","OTEL_LOGS_EXPORTER","OTEL_TRACES_EXPORTER"]){const r=process.env[e];r?.includes("console")&&(process.env[e]=r.split(",").map(e=>e.trim()).filter(e=>"console"!==e).join(","))}t.setLogger(new q,r.ERROR),Q();const g=[],v=isTelemetryEnabled();j(`[3P telemetry] isTelemetryEnabled=${v} (CONTEXT_CODE_ENABLE_TELEMETRY=${process.env.CONTEXT_CODE_ENABLE_TELEMETRY}, CLAUDE_CODE_ENABLE_TELEMETRY=${process.env.CLAUDE_CODE_ENABLE_TELEMETRY})`),v&&g.push(...await async function(){const e=parseExporterTypes(process.env.OTEL_METRICS_EXPORTER),r=parseInt(process.env.OTEL_METRIC_EXPORT_INTERVAL||6e4.toString()),t=[];for(const r of e)if("console"===r){const e=new O,r=e.export.bind(e);e.export=(e,t)=>(e.resource&&e.resource.attributes&&(j("\n=== Resource Attributes ==="),j(V(e.resource.attributes)),j("===========================\n")),r(e,t)),t.push(e)}else if("otlp"===r){const e=process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),r=getOTLPExporterConfig();switch(e){case"grpc":{const{OTLPMetricExporter:e}=await import("@opentelemetry/exporter-metrics-otlp-grpc");t.push(new e);break}case"http/json":{const{OTLPMetricExporter:e}=await import("@opentelemetry/exporter-metrics-otlp-http");t.push(new e(r));break}case"http/protobuf":{const{OTLPMetricExporter:e}=await import("@opentelemetry/exporter-metrics-otlp-proto");t.push(new e(r));break}default:throw new Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_METRICS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${e}`)}}else{if("prometheus"!==r)throw new Error(`Unknown exporter type set in OTEL_EXPORTER_OTLP_METRICS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${r}`);{const{PrometheusExporter:e}=await import("@opentelemetry/exporter-prometheus");t.push(new e)}}return t.map(e=>"export"in e?new _({exporter:e,exportIntervalMillis:r}):e)}()),function(){const e=A(),r=N()&&("enterprise"===e||"team"===e);return M()||r}()&&g.push(function(){const e=new z;return new _({exporter:e,exportIntervalMillis:3e5})}());const x=X(),D={[u]:"claude-code",[P]:e.VERSION};if("wsl"===x){const e=b();e&&(D["wsl.version"]=e)}const k=p(D),F=p(T.detect().attributes||{}),$=E.detect(),H=$.attributes?.[f]?{[f]:$.attributes[f]}:{},B=p(H),G=p(n.detect().attributes||{}),Z=k.merge(F).merge(B).merge(G);if(W()){(async function(r){const t=process.env.BETA_TRACING_ENDPOINT;if(!t)return;const[{OTLPTraceExporter:n},{OTLPLogExporter:E}]=await Promise.all([import("@opentelemetry/exporter-trace-otlp-http"),import("@opentelemetry/exporter-logs-otlp-http")]),T={url:`${t}/v1/logs`},p=new n({url:`${t}/v1/traces`}),i=new R(p,{scheduledDelayMillis:5e3}),O=new m({resource:r,spanProcessors:[i]});o.setGlobalTracerProvider(O),S(O);const l=new E(T),_=new a({resource:r,processors:[new c(l,{scheduledDelayMillis:5e3})]});s.setGlobalLoggerProvider(_),w(_);const L=s.getLogger("com.anthropic.claude_code.events",e.VERSION);C(L),process.on("beforeExit",async()=>{await(_?.forceFlush()),await(O?.forceFlush())}),process.on("exit",()=>{_?.forceFlush(),O?.forceFlush()})})(Z).catch(e=>j(`Beta tracing init failed: ${e}`,{level:"error"}));const r=new l({resource:Z,views:[],readers:g});return d(r),I(async()=>{const e=parseInt(process.env.CONTEXT_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||process.env.CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||"2000");try{J();const t=h(),o=y(),s=[r.shutdown()];t&&s.push(t.forceFlush().then(()=>t.shutdown())),o&&s.push(o.forceFlush().then(()=>o.shutdown())),await Promise.race([Promise.all(s),telemetryTimeout(e,"OpenTelemetry shutdown timeout")])}catch{}}),r.getMeter("com.anthropic.claude_code",e.VERSION)}const ee=new l({resource:Z,views:[],readers:g});if(d(ee),v){const r=await async function(){const e=parseExporterTypes(process.env.OTEL_LOGS_EXPORTER),r=process.env.OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),t=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;j(`[3P telemetry] getOtlpLogExporters: types=${V(e)}, protocol=${r}, endpoint=${t}`);const o=[];for(const t of e)if("console"===t)o.push(new i);else{if("otlp"!==t)throw new Error(`Unknown exporter type set in OTEL_LOGS_EXPORTER env var: ${t}`);{const e=getOTLPExporterConfig();switch(r){case"grpc":{const{OTLPLogExporter:e}=await import("@opentelemetry/exporter-logs-otlp-grpc");o.push(new e);break}case"http/json":{const{OTLPLogExporter:r}=await import("@opentelemetry/exporter-logs-otlp-http");o.push(new r(e));break}case"http/protobuf":{const{OTLPLogExporter:r}=await import("@opentelemetry/exporter-logs-otlp-proto");o.push(new r(e));break}default:throw new Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_LOGS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${r}`)}}}return o}();if(j(`[3P telemetry] Created ${r.length} log exporter(s)`),r.length>0){const t=new a({resource:Z,processors:r.map(e=>new c(e,{scheduledDelayMillis:parseInt(process.env.OTEL_LOGS_EXPORT_INTERVAL||5e3.toString())}))});s.setGlobalLoggerProvider(t),w(t);const o=s.getLogger("com.anthropic.claude_code.events",e.VERSION);C(o),j("[3P telemetry] Event logger set successfully"),process.on("beforeExit",async()=>{await(t?.forceFlush());const e=y();await(e?.forceFlush())}),process.on("exit",()=>{t?.forceFlush(),y()?.forceFlush()})}}if(v&&K()){const e=await async function(){const e=parseExporterTypes(process.env.OTEL_TRACES_EXPORTER),r=[];for(const t of e)if("console"===t)r.push(new L);else{if("otlp"!==t)throw new Error(`Unknown exporter type set in OTEL_TRACES_EXPORTER env var: ${t}`);{const e=process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),t=getOTLPExporterConfig();switch(e){case"grpc":{const{OTLPTraceExporter:e}=await import("@opentelemetry/exporter-trace-otlp-grpc");r.push(new e);break}case"http/json":{const{OTLPTraceExporter:e}=await import("@opentelemetry/exporter-trace-otlp-http");r.push(new e(t));break}case"http/protobuf":{const{OTLPTraceExporter:e}=await import("@opentelemetry/exporter-trace-otlp-proto");r.push(new e(t));break}default:throw new Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_TRACES_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${e}`)}}}return r}();if(e.length>0){const r=e.map(e=>new R(e,{scheduledDelayMillis:parseInt(process.env.OTEL_TRACES_EXPORT_INTERVAL||5e3.toString())})),t=new m({resource:Z,spanProcessors:r});o.setGlobalTracerProvider(t),S(t)}}return I(async()=>{const e=parseInt(process.env.CONTEXT_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||process.env.CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||"2000");try{J();const r=[ee.shutdown()],t=h();t&&r.push(t.shutdown());const o=y();o&&r.push(o.shutdown()),await Promise.race([Promise.all(r),telemetryTimeout(e,"OpenTelemetry shutdown timeout")])}catch(r){throw r instanceof Error&&r.message.includes("timeout")&&j(`\nOpenTelemetry telemetry flush timed out after ${e}ms\n\nTo resolve this issue, you can:\n1. Increase the timeout by setting CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS env var (e.g., 5000 for 5 seconds)\n2. Check if your OpenTelemetry backend is experiencing scalability issues\n3. Disable OpenTelemetry by unsetting CLAUDE_CODE_ENABLE_TELEMETRY env var\n\nCurrent timeout: ${e}ms\n`,{level:"error"}),r}}),ee.getMeter("com.anthropic.claude_code",e.VERSION)}export async function flushTelemetry(){const e=v();if(!e)return;const r=parseInt(process.env.CONTEXT_CODE_OTEL_FLUSH_TIMEOUT_MS||process.env.CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS||"5000");try{const t=[e.forceFlush()],o=h();o&&t.push(o.forceFlush());const s=y();s&&t.push(s.forceFlush()),await Promise.race([Promise.all(t),telemetryTimeout(r,"OpenTelemetry flush timeout")]),j("Telemetry flushed successfully")}catch(e){e instanceof TelemetryTimeoutError?j(`Telemetry flush timed out after ${r}ms. Some metrics may not be exported.`,{level:"warn"}):j(`Telemetry flush failed: ${F(e)}`,{level:"error"})}}function getOTLPExporterConfig(){const e=H(),r=$(),t=G(),o={},s=function(){const e={},r=process.env.OTEL_EXPORTER_OTLP_HEADERS;if(r)for(const t of r.split(",")){const[r,...o]=t.split("=");r&&o.length>0&&(e[r.trim()]=o.join("=").trim())}return e}();t?.otelHeadersHelper?o.headers=async()=>{const e=x();return{...s,...e}}:Object.keys(s).length>0&&(o.headers=async()=>s);const n=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;if(!e||n&&B(n)){const e=D();return(r||e)&&(o.httpAgentOptions={...r,...e&&{ca:e}}),o}const E=D();return o.httpAgentOptions=t=>r||E?new g(e,{...r&&{cert:r.cert,key:r.key,passphrase:r.passphrase},...E&&{ca:E}}):new g(e),o}
1
+ import{MACRO as e}from"../../recovery/bunBundleShim.js";import{DiagLogLevel as r,diag as t,trace as o}from"@opentelemetry/api";import{logs as s}from"@opentelemetry/api-logs";import{envDetector as n,hostDetector as E,osDetector as T,resourceFromAttributes as p}from"@opentelemetry/resources";import{BatchLogRecordProcessor as c,ConsoleLogRecordExporter as O,LoggerProvider as i}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as _,MeterProvider as a,PeriodicExportingMetricReader as l}from"@opentelemetry/sdk-metrics";import{BasicTracerProvider as m,BatchSpanProcessor as L,ConsoleSpanExporter as R}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as u,ATTR_SERVICE_VERSION as P,SEMRESATTRS_HOST_ARCH as f}from"@opentelemetry/semantic-conventions";import{HttpsProxyAgent as h}from"https-proxy-agent";import{getLoggerProvider as y,getMeterProvider as w,getTracerProvider as v,setEventLogger as C,setLoggerProvider as g,setMeterProvider as d,setTracerProvider as x}from"../../bootstrap/state.js";import{getOtelHeadersFromHelper as S,getSubscriptionType as X,is1PApiCustomer as N,isClaudeAISubscriber as A}from"../auth.js";import{getPlatform as M,getWslVersion as b}from"../platform.js";import{getCACertificates as I}from"../caCerts.js";import{registerCleanup as D}from"../cleanupRegistry.js";import{getHasFormattedOutput as U,logForDebugging as j}from"../debug.js";import{isEnvTruthy as k}from"../envUtils.js";import{errorMessage as $}from"../errors.js";import{getMTLSConfig as F}from"../mtls.js";import{getProxyUrl as G,shouldBypassProxy as H}from"../proxy.js";import{getSettings_DEPRECATED as B}from"../settings/settings.js";import{jsonStringify as Y}from"../slowOperations.js";import{profileCheckpoint as V}from"../startupProfiler.js";import{isBetaTracingEnabled as W}from"./betaSessionTracing.js";import{BigQueryMetricsExporter as q}from"./bigqueryExporter.js";import{ClaudeCodeDiagLogger as z}from"./logger.js";import{initializePerfettoTracing as J}from"./perfettoTracing.js";import{endInteractionSpan as K,isEnhancedTelemetryEnabled as Q}from"./sessionTracing.js";class TelemetryTimeoutError extends Error{}function telemetryTimeout(e,r){return new Promise((t,o)=>{setTimeout((e,r)=>e(new TelemetryTimeoutError(r)),e,o,r).unref()})}export function bootstrapTelemetry(){"ant"===process.env.USER_TYPE&&(process.env.ANT_OTEL_METRICS_EXPORTER&&(process.env.OTEL_METRICS_EXPORTER=process.env.ANT_OTEL_METRICS_EXPORTER),process.env.ANT_OTEL_LOGS_EXPORTER&&(process.env.OTEL_LOGS_EXPORTER=process.env.ANT_OTEL_LOGS_EXPORTER),process.env.ANT_OTEL_TRACES_EXPORTER&&(process.env.OTEL_TRACES_EXPORTER=process.env.ANT_OTEL_TRACES_EXPORTER),process.env.ANT_OTEL_EXPORTER_OTLP_PROTOCOL&&(process.env.OTEL_EXPORTER_OTLP_PROTOCOL=process.env.ANT_OTEL_EXPORTER_OTLP_PROTOCOL),process.env.ANT_OTEL_EXPORTER_OTLP_ENDPOINT&&(process.env.OTEL_EXPORTER_OTLP_ENDPOINT=process.env.ANT_OTEL_EXPORTER_OTLP_ENDPOINT),process.env.ANT_OTEL_EXPORTER_OTLP_HEADERS&&(process.env.OTEL_EXPORTER_OTLP_HEADERS=process.env.ANT_OTEL_EXPORTER_OTLP_HEADERS)),process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE||(process.env.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE="delta")}export function parseExporterTypes(e){return(e||"").trim().split(",").filter(Boolean).map(e=>e.trim()).filter(e=>"none"!==e)}export function isTelemetryEnabled(){return k(process.env.CONTEXT_CODE_ENABLE_TELEMETRY)||k(process.env.CLAUDE_CODE_ENABLE_TELEMETRY)}export async function initializeTelemetry(){if(V("telemetry_init_start"),bootstrapTelemetry(),U())for(const e of["OTEL_METRICS_EXPORTER","OTEL_LOGS_EXPORTER","OTEL_TRACES_EXPORTER"]){const r=process.env[e];r?.includes("console")&&(process.env[e]=r.split(",").map(e=>e.trim()).filter(e=>"console"!==e).join(","))}t.setLogger(new z,r.ERROR),J();const h=[],w=isTelemetryEnabled();j(`[3P telemetry] isTelemetryEnabled=${w} (CONTEXT_CODE_ENABLE_TELEMETRY=${process.env.CONTEXT_CODE_ENABLE_TELEMETRY}, CLAUDE_CODE_ENABLE_TELEMETRY=${process.env.CLAUDE_CODE_ENABLE_TELEMETRY})`),w&&h.push(...await async function(){const e=parseExporterTypes(process.env.OTEL_METRICS_EXPORTER),r=parseInt(process.env.OTEL_METRIC_EXPORT_INTERVAL||6e4.toString()),t=[];for(const r of e)if("console"===r){const e=new _,r=e.export.bind(e);e.export=(e,t)=>(e.resource&&e.resource.attributes&&(j("\n=== Resource Attributes ==="),j(Y(e.resource.attributes)),j("===========================\n")),r(e,t)),t.push(e)}else if("otlp"===r){const e=process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),r=getOTLPExporterConfig();switch(e){case"grpc":{const{OTLPMetricExporter:e}=await import("@opentelemetry/exporter-metrics-otlp-grpc");t.push(new e);break}case"http/json":{const{OTLPMetricExporter:e}=await import("@opentelemetry/exporter-metrics-otlp-http");t.push(new e(r));break}case"http/protobuf":{const{OTLPMetricExporter:e}=await import("@opentelemetry/exporter-metrics-otlp-proto");t.push(new e(r));break}default:throw new Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_METRICS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${e}`)}}else{if("prometheus"!==r)throw new Error(`Unknown exporter type set in OTEL_EXPORTER_OTLP_METRICS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${r}`);{const{PrometheusExporter:e}=await import("@opentelemetry/exporter-prometheus");t.push(new e)}}return t.map(e=>"export"in e?new l({exporter:e,exportIntervalMillis:r}):e)}()),function(){const e=X(),r=A()&&("enterprise"===e||"team"===e);return N()||r}()&&h.push(function(){const e=new q;return new l({exporter:e,exportIntervalMillis:3e5})}());const S=M(),I={[u]:"claude-code",[P]:e.VERSION};if("wsl"===S){const e=b();e&&(I["wsl.version"]=e)}const k=p(I),$=p(T.detect().attributes||{}),F=E.detect(),G=F.attributes?.[f]?{[f]:F.attributes[f]}:{},H=p(G),B=p(n.detect().attributes||{}),Z=k.merge($).merge(H).merge(B);if(W()){(async function(r){const t=process.env.BETA_TRACING_ENDPOINT;if(!t)return;const[{OTLPTraceExporter:n},{OTLPLogExporter:E}]=await Promise.all([import("@opentelemetry/exporter-trace-otlp-http"),import("@opentelemetry/exporter-logs-otlp-http")]),T={url:`${t}/v1/logs`},p=new n({url:`${t}/v1/traces`}),O=new L(p,{scheduledDelayMillis:5e3}),_=new m({resource:r,spanProcessors:[O]});o.setGlobalTracerProvider(_),x(_);const a=new E(T),l=new i({resource:r,processors:[new c(a,{scheduledDelayMillis:5e3})]});s.setGlobalLoggerProvider(l),g(l);const R=s.getLogger("com.anthropic.claude_code.events",e.VERSION);C(R),process.on("beforeExit",async()=>{await(l?.forceFlush()),await(_?.forceFlush())}),process.on("exit",()=>{l?.forceFlush(),_?.forceFlush()})})(Z).catch(e=>j(`Beta tracing init failed: ${e}`,{level:"error"}));const r=new a({resource:Z,views:[],readers:h});d(r);return D(async()=>{const e=parseInt(process.env.CONTEXT_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||process.env.CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||"2000");try{K();const t=y(),o=v(),s=[r.shutdown()];t&&s.push(t.forceFlush().then(()=>t.shutdown())),o&&s.push(o.forceFlush().then(()=>o.shutdown())),await Promise.race([Promise.all(s),telemetryTimeout(e,"OpenTelemetry shutdown timeout")])}catch{}}),r.getMeter("com.anthropic.claude_code",e.VERSION)}const ee=new a({resource:Z,views:[],readers:h});if(d(ee),w){const r=await async function(){const e=parseExporterTypes(process.env.OTEL_LOGS_EXPORTER),r=process.env.OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),t=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;j(`[3P telemetry] getOtlpLogExporters: types=${Y(e)}, protocol=${r}, endpoint=${t}`);const o=[];for(const t of e)if("console"===t)o.push(new O);else{if("otlp"!==t)throw new Error(`Unknown exporter type set in OTEL_LOGS_EXPORTER env var: ${t}`);{const e=getOTLPExporterConfig();switch(r){case"grpc":{const{OTLPLogExporter:e}=await import("@opentelemetry/exporter-logs-otlp-grpc");o.push(new e);break}case"http/json":{const{OTLPLogExporter:r}=await import("@opentelemetry/exporter-logs-otlp-http");o.push(new r(e));break}case"http/protobuf":{const{OTLPLogExporter:r}=await import("@opentelemetry/exporter-logs-otlp-proto");o.push(new r(e));break}default:throw new Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_LOGS_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${r}`)}}}return o}();if(j(`[3P telemetry] Created ${r.length} log exporter(s)`),r.length>0){const t=new i({resource:Z,processors:r.map(e=>new c(e,{scheduledDelayMillis:parseInt(process.env.OTEL_LOGS_EXPORT_INTERVAL||5e3.toString())}))});s.setGlobalLoggerProvider(t),g(t);const o=s.getLogger("com.anthropic.claude_code.events",e.VERSION);C(o),j("[3P telemetry] Event logger set successfully"),process.on("beforeExit",async()=>{await(t?.forceFlush());const e=v();await(e?.forceFlush())}),process.on("exit",()=>{t?.forceFlush(),v()?.forceFlush()})}}if(w&&Q()){const e=await async function(){const e=parseExporterTypes(process.env.OTEL_TRACES_EXPORTER),r=[];for(const t of e)if("console"===t)r.push(new R);else{if("otlp"!==t)throw new Error(`Unknown exporter type set in OTEL_TRACES_EXPORTER env var: ${t}`);{const e=process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?.trim()||process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim(),t=getOTLPExporterConfig();switch(e){case"grpc":{const{OTLPTraceExporter:e}=await import("@opentelemetry/exporter-trace-otlp-grpc");r.push(new e);break}case"http/json":{const{OTLPTraceExporter:e}=await import("@opentelemetry/exporter-trace-otlp-http");r.push(new e(t));break}case"http/protobuf":{const{OTLPTraceExporter:e}=await import("@opentelemetry/exporter-trace-otlp-proto");r.push(new e(t));break}default:throw new Error(`Unknown protocol set in OTEL_EXPORTER_OTLP_TRACES_PROTOCOL or OTEL_EXPORTER_OTLP_PROTOCOL env var: ${e}`)}}}return r}();if(e.length>0){const r=e.map(e=>new L(e,{scheduledDelayMillis:parseInt(process.env.OTEL_TRACES_EXPORT_INTERVAL||5e3.toString())})),t=new m({resource:Z,spanProcessors:r});o.setGlobalTracerProvider(t),x(t)}}return D(async()=>{const e=parseInt(process.env.CONTEXT_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||process.env.CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS||"2000");try{K();const r=[ee.shutdown()],t=y();t&&r.push(t.shutdown());const o=v();o&&r.push(o.shutdown()),await Promise.race([Promise.all(r),telemetryTimeout(e,"OpenTelemetry shutdown timeout")])}catch(r){throw r instanceof Error&&r.message.includes("timeout")&&j(`\nOpenTelemetry telemetry flush timed out after ${e}ms\n\nTo resolve this issue, you can:\n1. Increase the timeout by setting CLAUDE_CODE_OTEL_SHUTDOWN_TIMEOUT_MS env var (e.g., 5000 for 5 seconds)\n2. Check if your OpenTelemetry backend is experiencing scalability issues\n3. Disable OpenTelemetry by unsetting CLAUDE_CODE_ENABLE_TELEMETRY env var\n\nCurrent timeout: ${e}ms\n`,{level:"error"}),r}}),ee.getMeter("com.anthropic.claude_code",e.VERSION)}export async function flushTelemetry(){const e=w();if(!e)return;const r=parseInt(process.env.CONTEXT_CODE_OTEL_FLUSH_TIMEOUT_MS||process.env.CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS||"5000");try{const t=[e.forceFlush()],o=y();o&&t.push(o.forceFlush());const s=v();s&&t.push(s.forceFlush()),await Promise.race([Promise.all(t),telemetryTimeout(r,"OpenTelemetry flush timeout")]),j("Telemetry flushed successfully")}catch(e){e instanceof TelemetryTimeoutError?j(`Telemetry flush timed out after ${r}ms. Some metrics may not be exported.`,{level:"warn"}):j(`Telemetry flush failed: ${$(e)}`,{level:"error"})}}function getOTLPExporterConfig(){const e=G(),r=F(),t=B(),o={},s=function(){const e={},r=process.env.OTEL_EXPORTER_OTLP_HEADERS;if(r)for(const t of r.split(",")){const[r,...o]=t.split("=");r&&o.length>0&&(e[r.trim()]=o.join("=").trim())}return e}();t?.otelHeadersHelper?o.headers=async()=>{const e=S();return{...s,...e}}:Object.keys(s).length>0&&(o.headers=async()=>s);const n=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;if(!e||n&&H(n)){const e=I();return(r||e)&&(o.httpAgentOptions={...r,...e&&{ca:e}}),o}const E=I();return o.httpAgentOptions=t=>r||E?new h(e,{...r&&{cert:r.cert,key:r.key,passphrase:r.passphrase},...E&&{ca:E}}):new h(e),o}
@@ -1 +1 @@
1
- import{logForDebugging as r}from"../debug.js";import{logError as e}from"../log.js";export class ClaudeCodeDiagLogger{error(o,...g){e(new Error(o)),r(`[3P telemetry] OTEL diag error: ${o}`,{level:"error"})}warn(o,...g){e(new Error(o)),r(`[3P telemetry] OTEL diag warn: ${o}`,{level:"warn"})}info(r,...e){}debug(r,...e){}verbose(r,...e){}}
1
+ import{logForDebugging as r}from"../debug.js";import{logError as e}from"../log.js";export class ClaudeCodeDiagLogger{error(o,...l){e(new Error(o)),r(`[3P telemetry] OTEL diag error: ${o}`,{level:"error"})}warn(o,...l){e(new Error(o)),r(`[3P telemetry] OTEL diag warn: ${o}`,{level:"warn"})}info(r,...e){}debug(r,...e){}verbose(r,...e){}}
@@ -1 +1 @@
1
- import{feature as e}from"bun:bundle";import{mkdirSync as t,writeFileSync as r}from"fs";import{mkdir as n,writeFile as a}from"fs/promises";import{dirname as s,join as o}from"path";import{getSessionId as i}from"../../bootstrap/state.js";import{registerCleanup as c}from"../cleanupRegistry.js";import{logForDebugging as p}from"../debug.js";import{getClaudeConfigHomeDir as d,isEnvDefinedFalsy as g,isEnvTruthy as u}from"../envUtils.js";import{errorMessage as f}from"../errors.js";import{djb2Hash as m}from"../hash.js";import{jsonStringify as l}from"../slowOperations.js";import{getAgentId as I,getAgentName as h,getParentSessionId as T}from"../teammate.js";let _=!1,v=null;const P=[],E=[],S=1e5,y=new Map,A=new Map;let w=0,C=0,k=0,x=!1,$=1;const b=new Map;let O=null,F=null;function stringToNumericHash(e){return Math.abs(m(e))||1}function getProcessIdForAgent(e){const t=b.get(e);return void 0!==t?t:($++,b.set(e,$),$)}function getCurrentAgentInfo(){const e=I()??i(),t=h()??"main",r=T(),n=A.get(e);if(n)return n;const a={agentId:e,agentName:t,parentAgentId:r,processId:e===i()?1:getProcessIdForAgent(e),threadId:stringToNumericHash(t)};return A.set(e,a),w++,a}function getTimestamp(){return 1e3*(Date.now()-C)}function generateSpanId(){return"span_"+ ++k}function evictStaleSpans(){const e=getTimestamp();for(const[t,r]of y)e-r.startTime>18e8&&(E.push({name:r.name,cat:r.category,ph:"E",ts:e,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{...r.args,evicted:!0,duration_ms:(e-r.startTime)/1e3}}),y.delete(t))}function buildTraceDocument(){return l({traceEvents:[...P,...E],metadata:{session_id:i(),trace_start_time:new Date(C).toISOString(),agent_count:w,total_event_count:P.length+E.length}})}function evictOldestEvents(){if(E.length<S)return;const e=E.splice(0,5e4);E.unshift({name:"trace_truncated",cat:"__metadata",ph:"i",ts:e[e.length-1]?.ts??0,pid:1,tid:0,args:{dropped_events:e.length}}),p(`[Perfetto] Evicted ${e.length} oldest events (cap 100000)`)}export function initializePerfettoTracing(){const n=process.env.CONTEXT_CODE_PERFETTO_TRACE??process.env.CLAUDE_CODE_PERFETTO_TRACE;if(p(`[Perfetto] initializePerfettoTracing called, env value: ${n}`),e("PERFETTO_TRACING")){if(!n||g(n))return void p("[Perfetto] Tracing disabled (env var not set or disabled)");if(_=!0,C=Date.now(),u(n)){const e=o(d(),"traces");v=o(e,`trace-${i()}.json`)}else v=n;p(`[Perfetto] Tracing enabled, will write to: ${v}, isEnabled=${_}`);const e=parseInt(process.env.CONTEXT_CODE_PERFETTO_WRITE_INTERVAL_S??process.env.CLAUDE_CODE_PERFETTO_WRITE_INTERVAL_S??"",10);e>0&&(O=setInterval(()=>{periodicWrite()},1e3*e),O.unref&&O.unref(),p(`[Perfetto] Periodic write enabled, interval: ${e}s`)),F=setInterval(()=>{evictStaleSpans(),evictOldestEvents()},6e4),F.unref&&F.unref(),c(async()=>{p("[Perfetto] Cleanup callback invoked"),await writePerfettoTrace()}),process.on("beforeExit",()=>{p("[Perfetto] beforeExit handler invoked"),writePerfettoTrace()}),process.on("exit",()=>{x||(p("[Perfetto] exit handler invoked, writing trace synchronously"),function(){if(_&&v&&!x){stopWriteInterval(),closeOpenSpans(),p(`[Perfetto] writePerfettoTraceSync called: events=${E.length}`);try{const e=s(v);t(e,{recursive:!0}),r(v,buildTraceDocument()),x=!0,p(`[Perfetto] Trace finalized synchronously at: ${v}`)}catch(e){p(`[Perfetto] Failed to write final trace synchronously: ${f(e)}`,{level:"error"})}}else p(`[Perfetto] Skipping final sync write: isEnabled=${_}, tracePath=${v}, traceWritten=${x}`)}())}),emitProcessMetadata(getCurrentAgentInfo())}}function emitProcessMetadata(e){_&&(P.push({name:"process_name",cat:"__metadata",ph:"M",ts:0,pid:e.processId,tid:0,args:{name:e.agentName}}),P.push({name:"thread_name",cat:"__metadata",ph:"M",ts:0,pid:e.processId,tid:e.threadId,args:{name:e.agentName}}),e.parentAgentId&&P.push({name:"parent_agent",cat:"__metadata",ph:"M",ts:0,pid:e.processId,tid:0,args:{parent_agent_id:e.parentAgentId}}))}export function isPerfettoTracingEnabled(){return _}export function registerAgent(e,t,r){if(!_)return;const n={agentId:e,agentName:t,parentAgentId:r,processId:getProcessIdForAgent(e),threadId:stringToNumericHash(t)};A.set(e,n),w++,emitProcessMetadata(n)}export function unregisterAgent(e){_&&(A.delete(e),b.delete(e))}export function startLLMRequestPerfettoSpan(e){if(!_)return"";const t=generateSpanId(),r=getCurrentAgentInfo();return y.set(t,{name:"API Call",category:"api",startTime:getTimestamp(),agentInfo:r,args:{model:e.model,prompt_tokens:e.promptTokens,message_id:e.messageId,is_speculative:e.isSpeculative??!1,query_source:e.querySource}}),E.push({name:"API Call",cat:"api",ph:"B",ts:y.get(t).startTime,pid:r.processId,tid:r.threadId,args:y.get(t).args}),t}export function endLLMRequestPerfettoSpan(e,t){if(!_||!e)return;const r=y.get(e);if(!r)return;const n=getTimestamp(),a=n-r.startTime,s=t.promptTokens??r.args.prompt_tokens,o=t.ttftMs,i=t.ttltMs,c=t.outputTokens,p=t.cacheReadTokens,d=void 0!==o&&void 0!==s&&o>0?Math.round(s/(o/1e3)*100)/100:void 0,g=void 0!==i&&void 0!==o?i-o:void 0,u=void 0!==g&&void 0!==c&&g>0?Math.round(c/(g/1e3)*100)/100:void 0,f=void 0!==p&&void 0!==s&&s>0?Math.round(p/s*1e4)/100:void 0,m=t.requestSetupMs,l=t.attemptStartTimes,I={...r.args,ttft_ms:o,ttlt_ms:i,prompt_tokens:s,output_tokens:c,cache_read_tokens:p,cache_creation_tokens:t.cacheCreationTokens,message_id:t.messageId??r.args.message_id,success:t.success??!0,error:t.error,duration_ms:a/1e3,request_setup_ms:m,itps:d,otps:u,cache_hit_rate_pct:f},h=void 0!==m&&m>0?1e3*m:0;if(h>0){const e=r.startTime+h;if(E.push({name:"Request Setup",cat:"api,setup",ph:"B",ts:r.startTime,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{request_setup_ms:m,attempt_count:l?.length??1}}),l&&l.length>1){const e=l[0];for(let t=0;t<l.length-1;t++){const n=r.startTime+1e3*(l[t]-e),a=r.startTime+1e3*(l[t+1]-e);E.push({name:`Attempt ${t+1} (retry)`,cat:"api,retry",ph:"B",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{attempt:t+1}}),E.push({name:`Attempt ${t+1} (retry)`,cat:"api,retry",ph:"E",ts:a,pid:r.agentInfo.processId,tid:r.agentInfo.threadId})}}E.push({name:"Request Setup",cat:"api,setup",ph:"E",ts:e,pid:r.agentInfo.processId,tid:r.agentInfo.threadId})}if(void 0!==o){const e=r.startTime+h,t=e+1e3*o;E.push({name:"First Token",cat:"api,ttft",ph:"B",ts:e,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{ttft_ms:o,prompt_tokens:s,itps:d,cache_hit_rate_pct:f}}),E.push({name:"First Token",cat:"api,ttft",ph:"E",ts:t,pid:r.agentInfo.processId,tid:r.agentInfo.threadId});const n=void 0!==i?i-o-h/1e3:void 0;void 0!==n&&n>0&&(E.push({name:"Sampling",cat:"api,sampling",ph:"B",ts:t,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{sampling_ms:n,output_tokens:c,otps:u}}),E.push({name:"Sampling",cat:"api,sampling",ph:"E",ts:t+1e3*n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId}))}E.push({name:r.name,cat:r.category,ph:"E",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:I}),y.delete(e)}export function startToolPerfettoSpan(e,t){if(!_)return"";const r=generateSpanId(),n=getCurrentAgentInfo();return y.set(r,{name:`Tool: ${e}`,category:"tool",startTime:getTimestamp(),agentInfo:n,args:{tool_name:e,...t}}),E.push({name:`Tool: ${e}`,cat:"tool",ph:"B",ts:y.get(r).startTime,pid:n.processId,tid:n.threadId,args:y.get(r).args}),r}export function endToolPerfettoSpan(e,t){if(!_||!e)return;const r=y.get(e);if(!r)return;const n=getTimestamp(),a=n-r.startTime,s={...r.args,success:t?.success??!0,error:t?.error,result_tokens:t?.resultTokens,duration_ms:a/1e3};E.push({name:r.name,cat:r.category,ph:"E",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:s}),y.delete(e)}export function startUserInputPerfettoSpan(e){if(!_)return"";const t=generateSpanId(),r=getCurrentAgentInfo();return y.set(t,{name:"Waiting for User Input",category:"user_input",startTime:getTimestamp(),agentInfo:r,args:{context:e}}),E.push({name:"Waiting for User Input",cat:"user_input",ph:"B",ts:y.get(t).startTime,pid:r.processId,tid:r.threadId,args:y.get(t).args}),t}export function endUserInputPerfettoSpan(e,t){if(!_||!e)return;const r=y.get(e);if(!r)return;const n=getTimestamp(),a=n-r.startTime,s={...r.args,decision:t?.decision,source:t?.source,duration_ms:a/1e3};E.push({name:r.name,cat:r.category,ph:"E",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:s}),y.delete(e)}export function emitPerfettoInstant(e,t,r){if(!_)return;const n=getCurrentAgentInfo();E.push({name:e,cat:t,ph:"i",ts:getTimestamp(),pid:n.processId,tid:n.threadId,args:r})}export function emitPerfettoCounter(e,t){if(!_)return;const r=getCurrentAgentInfo();E.push({name:e,cat:"counter",ph:"C",ts:getTimestamp(),pid:r.processId,tid:r.threadId,args:t})}export function startInteractionPerfettoSpan(e){if(!_)return"";const t=generateSpanId(),r=getCurrentAgentInfo();return y.set(t,{name:"Interaction",category:"interaction",startTime:getTimestamp(),agentInfo:r,args:{user_prompt_length:e?.length}}),E.push({name:"Interaction",cat:"interaction",ph:"B",ts:y.get(t).startTime,pid:r.processId,tid:r.threadId,args:y.get(t).args}),t}export function endInteractionPerfettoSpan(e){if(!_||!e)return;const t=y.get(e);if(!t)return;const r=getTimestamp(),n=r-t.startTime;E.push({name:t.name,cat:t.category,ph:"E",ts:r,pid:t.agentInfo.processId,tid:t.agentInfo.threadId,args:{...t.args,duration_ms:n/1e3}}),y.delete(e)}function stopWriteInterval(){F&&(clearInterval(F),F=null),O&&(clearInterval(O),O=null)}function closeOpenSpans(){for(const[e,t]of y){const r=getTimestamp();E.push({name:t.name,cat:t.category,ph:"E",ts:r,pid:t.agentInfo.processId,tid:t.agentInfo.threadId,args:{...t.args,incomplete:!0,duration_ms:(r-t.startTime)/1e3}}),y.delete(e)}}async function periodicWrite(){if(_&&v&&!x)try{await n(s(v),{recursive:!0}),await a(v,buildTraceDocument()),p(`[Perfetto] Periodic write: ${E.length} events to ${v}`)}catch(e){p(`[Perfetto] Periodic write failed: ${f(e)}`,{level:"error"})}}async function writePerfettoTrace(){if(_&&v&&!x){stopWriteInterval(),closeOpenSpans(),p(`[Perfetto] writePerfettoTrace called: events=${E.length}`);try{await n(s(v),{recursive:!0}),await a(v,buildTraceDocument()),x=!0,p(`[Perfetto] Trace finalized at: ${v}`)}catch(e){p(`[Perfetto] Failed to write final trace: ${f(e)}`,{level:"error"})}}else p(`[Perfetto] Skipping final write: isEnabled=${_}, tracePath=${v}, traceWritten=${x}`)}export function getPerfettoEvents(){return[...P,...E]}export function resetPerfettoTracer(){F&&(clearInterval(F),F=null),stopWriteInterval(),P.length=0,E.length=0,y.clear(),A.clear(),b.clear(),w=0,$=1,k=0,_=!1,v=null,C=0,x=!1}export async function triggerPeriodicWriteForTesting(){await periodicWrite()}export function evictStaleSpansForTesting(){evictStaleSpans()}export const MAX_EVENTS_FOR_TESTING=S;export function evictOldestEventsForTesting(){evictOldestEvents()}
1
+ import{feature as t}from"../../recovery/bunBundleShim.js";import{mkdirSync as e,writeFileSync as r}from"fs";import{mkdir as n,writeFile as a}from"fs/promises";import{dirname as s,join as o}from"path";import{getSessionId as i}from"../../bootstrap/state.js";import{registerCleanup as c}from"../cleanupRegistry.js";import{logForDebugging as p}from"../debug.js";import{getClaudeConfigHomeDir as d,isEnvDefinedFalsy as g,isEnvTruthy as u}from"../envUtils.js";import{errorMessage as f}from"../errors.js";import{djb2Hash as m}from"../hash.js";import{jsonStringify as l}from"../slowOperations.js";import{getAgentId as I,getAgentName as h,getParentSessionId as T}from"../teammate.js";let _=!1,v=null;const P=[],E=[],S=1e5,y=new Map,A=new Map;let w=0,x=0,C=0,$=!1,k=1;const O=new Map;let b=null;let M=null;function stringToNumericHash(t){return Math.abs(m(t))||1}function getProcessIdForAgent(t){const e=O.get(t);return void 0!==e?e:(k++,O.set(t,k),k)}function getCurrentAgentInfo(){const t=I()??i(),e=h()??"main",r=T(),n=A.get(t);if(n)return n;const a={agentId:t,agentName:e,parentAgentId:r,processId:t===i()?1:getProcessIdForAgent(t),threadId:stringToNumericHash(e)};return A.set(t,a),w++,a}function getTimestamp(){return 1e3*(Date.now()-x)}function generateSpanId(){return"span_"+ ++C}function evictStaleSpans(){const t=getTimestamp();for(const[e,r]of y)t-r.startTime>18e8&&(E.push({name:r.name,cat:r.category,ph:"E",ts:t,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{...r.args,evicted:!0,duration_ms:(t-r.startTime)/1e3}}),y.delete(e))}function buildTraceDocument(){return l({traceEvents:[...P,...E],metadata:{session_id:i(),trace_start_time:new Date(x).toISOString(),agent_count:w,total_event_count:P.length+E.length}})}function evictOldestEvents(){if(E.length<S)return;const t=E.splice(0,5e4);E.unshift({name:"trace_truncated",cat:"__metadata",ph:"i",ts:t[t.length-1]?.ts??0,pid:1,tid:0,args:{dropped_events:t.length}}),p(`[Perfetto] Evicted ${t.length} oldest events (cap 100000)`)}export function initializePerfettoTracing(){const n=process.env.CONTEXT_CODE_PERFETTO_TRACE??process.env.CLAUDE_CODE_PERFETTO_TRACE;if(p(`[Perfetto] initializePerfettoTracing called, env value: ${n}`),t("PERFETTO_TRACING")){if(!n||g(n))return void p("[Perfetto] Tracing disabled (env var not set or disabled)");if(_=!0,x=Date.now(),u(n)){const t=o(d(),"traces");v=o(t,`trace-${i()}.json`)}else v=n;p(`[Perfetto] Tracing enabled, will write to: ${v}, isEnabled=${_}`);const t=parseInt(process.env.CONTEXT_CODE_PERFETTO_WRITE_INTERVAL_S??process.env.CLAUDE_CODE_PERFETTO_WRITE_INTERVAL_S??"",10);t>0&&(b=setInterval(()=>{periodicWrite()},1e3*t),b.unref&&b.unref(),p(`[Perfetto] Periodic write enabled, interval: ${t}s`)),M=setInterval(()=>{evictStaleSpans(),evictOldestEvents()},6e4),M.unref&&M.unref(),c(async()=>{p("[Perfetto] Cleanup callback invoked"),await writePerfettoTrace()}),process.on("beforeExit",()=>{p("[Perfetto] beforeExit handler invoked"),writePerfettoTrace()}),process.on("exit",()=>{$||(p("[Perfetto] exit handler invoked, writing trace synchronously"),function(){if(!_||!v||$)return void p(`[Perfetto] Skipping final sync write: isEnabled=${_}, tracePath=${v}, traceWritten=${$}`);stopWriteInterval(),closeOpenSpans(),p(`[Perfetto] writePerfettoTraceSync called: events=${E.length}`);try{const t=s(v);e(t,{recursive:!0}),r(v,buildTraceDocument()),$=!0,p(`[Perfetto] Trace finalized synchronously at: ${v}`)}catch(t){p(`[Perfetto] Failed to write final trace synchronously: ${f(t)}`,{level:"error"})}}())});emitProcessMetadata(getCurrentAgentInfo())}}function emitProcessMetadata(t){_&&(P.push({name:"process_name",cat:"__metadata",ph:"M",ts:0,pid:t.processId,tid:0,args:{name:t.agentName}}),P.push({name:"thread_name",cat:"__metadata",ph:"M",ts:0,pid:t.processId,tid:t.threadId,args:{name:t.agentName}}),t.parentAgentId&&P.push({name:"parent_agent",cat:"__metadata",ph:"M",ts:0,pid:t.processId,tid:0,args:{parent_agent_id:t.parentAgentId}}))}export function isPerfettoTracingEnabled(){return _}export function registerAgent(t,e,r){if(!_)return;const n={agentId:t,agentName:e,parentAgentId:r,processId:getProcessIdForAgent(t),threadId:stringToNumericHash(e)};A.set(t,n),w++,emitProcessMetadata(n)}export function unregisterAgent(t){_&&(A.delete(t),O.delete(t))}export function startLLMRequestPerfettoSpan(t){if(!_)return"";const e=generateSpanId(),r=getCurrentAgentInfo();return y.set(e,{name:"API Call",category:"api",startTime:getTimestamp(),agentInfo:r,args:{model:t.model,prompt_tokens:t.promptTokens,message_id:t.messageId,is_speculative:t.isSpeculative??!1,query_source:t.querySource}}),E.push({name:"API Call",cat:"api",ph:"B",ts:y.get(e).startTime,pid:r.processId,tid:r.threadId,args:y.get(e).args}),e}export function endLLMRequestPerfettoSpan(t,e){if(!_||!t)return;const r=y.get(t);if(!r)return;const n=getTimestamp(),a=n-r.startTime,s=e.promptTokens??r.args.prompt_tokens,o=e.ttftMs,i=e.ttltMs,c=e.outputTokens,p=e.cacheReadTokens,d=void 0!==o&&void 0!==s&&o>0?Math.round(s/(o/1e3)*100)/100:void 0,g=void 0!==i&&void 0!==o?i-o:void 0,u=void 0!==g&&void 0!==c&&g>0?Math.round(c/(g/1e3)*100)/100:void 0,f=void 0!==p&&void 0!==s&&s>0?Math.round(p/s*1e4)/100:void 0,m=e.requestSetupMs,l=e.attemptStartTimes,I={...r.args,ttft_ms:o,ttlt_ms:i,prompt_tokens:s,output_tokens:c,cache_read_tokens:p,cache_creation_tokens:e.cacheCreationTokens,message_id:e.messageId??r.args.message_id,success:e.success??!0,error:e.error,duration_ms:a/1e3,request_setup_ms:m,itps:d,otps:u,cache_hit_rate_pct:f},h=void 0!==m&&m>0?1e3*m:0;if(h>0){const t=r.startTime+h;if(E.push({name:"Request Setup",cat:"api,setup",ph:"B",ts:r.startTime,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{request_setup_ms:m,attempt_count:l?.length??1}}),l&&l.length>1){const t=l[0];for(let e=0;e<l.length-1;e++){const n=r.startTime+1e3*(l[e]-t),a=r.startTime+1e3*(l[e+1]-t);E.push({name:`Attempt ${e+1} (retry)`,cat:"api,retry",ph:"B",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{attempt:e+1}}),E.push({name:`Attempt ${e+1} (retry)`,cat:"api,retry",ph:"E",ts:a,pid:r.agentInfo.processId,tid:r.agentInfo.threadId})}}E.push({name:"Request Setup",cat:"api,setup",ph:"E",ts:t,pid:r.agentInfo.processId,tid:r.agentInfo.threadId})}if(void 0!==o){const t=r.startTime+h,e=t+1e3*o;E.push({name:"First Token",cat:"api,ttft",ph:"B",ts:t,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{ttft_ms:o,prompt_tokens:s,itps:d,cache_hit_rate_pct:f}}),E.push({name:"First Token",cat:"api,ttft",ph:"E",ts:e,pid:r.agentInfo.processId,tid:r.agentInfo.threadId});const n=void 0!==i?i-o-h/1e3:void 0;void 0!==n&&n>0&&(E.push({name:"Sampling",cat:"api,sampling",ph:"B",ts:e,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:{sampling_ms:n,output_tokens:c,otps:u}}),E.push({name:"Sampling",cat:"api,sampling",ph:"E",ts:e+1e3*n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId}))}E.push({name:r.name,cat:r.category,ph:"E",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:I}),y.delete(t)}export function startToolPerfettoSpan(t,e){if(!_)return"";const r=generateSpanId(),n=getCurrentAgentInfo();return y.set(r,{name:`Tool: ${t}`,category:"tool",startTime:getTimestamp(),agentInfo:n,args:{tool_name:t,...e}}),E.push({name:`Tool: ${t}`,cat:"tool",ph:"B",ts:y.get(r).startTime,pid:n.processId,tid:n.threadId,args:y.get(r).args}),r}export function endToolPerfettoSpan(t,e){if(!_||!t)return;const r=y.get(t);if(!r)return;const n=getTimestamp(),a=n-r.startTime,s={...r.args,success:e?.success??!0,error:e?.error,result_tokens:e?.resultTokens,duration_ms:a/1e3};E.push({name:r.name,cat:r.category,ph:"E",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:s}),y.delete(t)}export function startUserInputPerfettoSpan(t){if(!_)return"";const e=generateSpanId(),r=getCurrentAgentInfo();return y.set(e,{name:"Waiting for User Input",category:"user_input",startTime:getTimestamp(),agentInfo:r,args:{context:t}}),E.push({name:"Waiting for User Input",cat:"user_input",ph:"B",ts:y.get(e).startTime,pid:r.processId,tid:r.threadId,args:y.get(e).args}),e}export function endUserInputPerfettoSpan(t,e){if(!_||!t)return;const r=y.get(t);if(!r)return;const n=getTimestamp(),a=n-r.startTime,s={...r.args,decision:e?.decision,source:e?.source,duration_ms:a/1e3};E.push({name:r.name,cat:r.category,ph:"E",ts:n,pid:r.agentInfo.processId,tid:r.agentInfo.threadId,args:s}),y.delete(t)}export function emitPerfettoInstant(t,e,r){if(!_)return;const n=getCurrentAgentInfo();E.push({name:t,cat:e,ph:"i",ts:getTimestamp(),pid:n.processId,tid:n.threadId,args:r})}export function emitPerfettoCounter(t,e){if(!_)return;const r=getCurrentAgentInfo();E.push({name:t,cat:"counter",ph:"C",ts:getTimestamp(),pid:r.processId,tid:r.threadId,args:e})}export function startInteractionPerfettoSpan(t){if(!_)return"";const e=generateSpanId(),r=getCurrentAgentInfo();return y.set(e,{name:"Interaction",category:"interaction",startTime:getTimestamp(),agentInfo:r,args:{user_prompt_length:t?.length}}),E.push({name:"Interaction",cat:"interaction",ph:"B",ts:y.get(e).startTime,pid:r.processId,tid:r.threadId,args:y.get(e).args}),e}export function endInteractionPerfettoSpan(t){if(!_||!t)return;const e=y.get(t);if(!e)return;const r=getTimestamp(),n=r-e.startTime;E.push({name:e.name,cat:e.category,ph:"E",ts:r,pid:e.agentInfo.processId,tid:e.agentInfo.threadId,args:{...e.args,duration_ms:n/1e3}}),y.delete(t)}function stopWriteInterval(){M&&(clearInterval(M),M=null),b&&(clearInterval(b),b=null)}function closeOpenSpans(){for(const[t,e]of y){const r=getTimestamp();E.push({name:e.name,cat:e.category,ph:"E",ts:r,pid:e.agentInfo.processId,tid:e.agentInfo.threadId,args:{...e.args,incomplete:!0,duration_ms:(r-e.startTime)/1e3}}),y.delete(t)}}async function periodicWrite(){if(_&&v&&!$)try{await n(s(v),{recursive:!0}),await a(v,buildTraceDocument()),p(`[Perfetto] Periodic write: ${E.length} events to ${v}`)}catch(t){p(`[Perfetto] Periodic write failed: ${f(t)}`,{level:"error"})}}async function writePerfettoTrace(){if(_&&v&&!$){stopWriteInterval(),closeOpenSpans(),p(`[Perfetto] writePerfettoTrace called: events=${E.length}`);try{await n(s(v),{recursive:!0}),await a(v,buildTraceDocument()),$=!0,p(`[Perfetto] Trace finalized at: ${v}`)}catch(t){p(`[Perfetto] Failed to write final trace: ${f(t)}`,{level:"error"})}}else p(`[Perfetto] Skipping final write: isEnabled=${_}, tracePath=${v}, traceWritten=${$}`)}export function getPerfettoEvents(){return[...P,...E]}export function resetPerfettoTracer(){M&&(clearInterval(M),M=null),stopWriteInterval(),P.length=0,E.length=0,y.clear(),A.clear(),O.clear(),w=0,k=1,C=0,_=!1,v=null,x=0,$=!1}export async function triggerPeriodicWriteForTesting(){await periodicWrite()}export function evictStaleSpansForTesting(){evictStaleSpans()}export const MAX_EVENTS_FOR_TESTING=S;export function evictOldestEventsForTesting(){evictOldestEvents()}
@@ -1 +1 @@
1
- import{createHash as e}from"crypto";import{sep as n}from"path";import{logEvent as i}from"../../services/analytics/index.js";import{isOfficialMarketplaceName as t,parsePluginIdentifier as o}from"../plugins/pluginIdentifier.js";export function hashPluginId(n,i){const t=i?`${n}@${i.toLowerCase()}`:n;return e("sha256").update(t+"claude-plugin-telemetry-v1").digest("hex").slice(0,16)}export function getTelemetryPluginScope(e,n,i){return"builtin"===n?"default-bundle":t(n)?"official":i?.has(e)?"org":"user-local"}export function getEnabledVia(e,i,t){return e.isBuiltin?"default-enable":i?.has(e.name)?"org-policy":t.some(i=>e.path.startsWith(i.endsWith(n)?i:i+n))?"seed-mount":"user-install"}export function buildPluginTelemetryFields(e,n,i=null){const t=getTelemetryPluginScope(e,n,i),o="official"===t||"default-bundle"===t;return{plugin_id_hash:hashPluginId(e,n),plugin_scope:t,plugin_name_redacted:o?e:"third-party",marketplace_name_redacted:o&&n?n:"third-party",is_official_plugin:o}}export function buildPluginCommandTelemetryFields(e,n=null){const{marketplace:i}=o(e.repository);return buildPluginTelemetryFields(e.pluginManifest.name,i,n)}export function logPluginsEnabledForSession(e,n,t){for(const l of e){const{marketplace:e}=o(l.repository);i("tengu_plugin_enabled_for_session",{_PROTO_plugin_name:l.name,...e&&{_PROTO_marketplace_name:e},...buildPluginTelemetryFields(l.name,e,n),enabled_via:getEnabledVia(l,n,t),skill_path_count:(l.skillsPath?1:0)+(l.skillsPaths?.length??0),command_path_count:(l.commandsPath?1:0)+(l.commandsPaths?.length??0),has_mcp:void 0!==l.manifest.mcpServers,has_hooks:void 0!==l.hooksConfig,...l.manifest.version&&{version:l.manifest.version}})}}export function classifyPluginCommandError(e){const n=String(e?.message??e);return/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network|Could not resolve|Connection refused|timed out/i.test(n)?"network":/\b404\b|not found|does not exist|no such plugin/i.test(n)?"not-found":/\b40[13]\b|EACCES|EPERM|permission denied|unauthorized/i.test(n)?"permission":/invalid|malformed|schema|validation|parse error/i.test(n)?"validation":"unknown"}export function logPluginLoadErrors(e,n){for(const t of e){const{name:e,marketplace:l}=o(t.source),a="plugin"in t&&t.plugin?t.plugin:e;i("tengu_plugin_load_failed",{error_category:t.type,_PROTO_plugin_name:a,...l&&{_PROTO_marketplace_name:l},...buildPluginTelemetryFields(a,l,n)})}}
1
+ import{createHash as e}from"crypto";import{sep as n}from"path";import{logEvent as t}from"../../services/analytics/index.js";import{isOfficialMarketplaceName as i,parsePluginIdentifier as o}from"../plugins/pluginIdentifier.js";export function hashPluginId(n,t){const i=t?`${n}@${t.toLowerCase()}`:n;return e("sha256").update(i+"claude-plugin-telemetry-v1").digest("hex").slice(0,16)}export function getTelemetryPluginScope(e,n,t){return"builtin"===n?"default-bundle":i(n)?"official":t?.has(e)?"org":"user-local"}export function getEnabledVia(e,t,i){return e.isBuiltin?"default-enable":t?.has(e.name)?"org-policy":i.some(t=>e.path.startsWith(t.endsWith(n)?t:t+n))?"seed-mount":"user-install"}export function buildPluginTelemetryFields(e,n,t=null){const i=getTelemetryPluginScope(e,n,t),o="official"===i||"default-bundle"===i;return{plugin_id_hash:hashPluginId(e,n),plugin_scope:i,plugin_name_redacted:o?e:"third-party",marketplace_name_redacted:o&&n?n:"third-party",is_official_plugin:o}}export function buildPluginCommandTelemetryFields(e,n=null){const{marketplace:t}=o(e.repository);return buildPluginTelemetryFields(e.pluginManifest.name,t,n)}export function logPluginsEnabledForSession(e,n,i){for(const l of e){const{marketplace:e}=o(l.repository);t("tengu_plugin_enabled_for_session",{_PROTO_plugin_name:l.name,...e&&{_PROTO_marketplace_name:e},...buildPluginTelemetryFields(l.name,e,n),enabled_via:getEnabledVia(l,n,i),skill_path_count:(l.skillsPath?1:0)+(l.skillsPaths?.length??0),command_path_count:(l.commandsPath?1:0)+(l.commandsPaths?.length??0),has_mcp:void 0!==l.manifest.mcpServers,has_hooks:void 0!==l.hooksConfig,...l.manifest.version&&{version:l.manifest.version}})}}export function classifyPluginCommandError(e){const n=String(e?.message??e);return/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network|Could not resolve|Connection refused|timed out/i.test(n)?"network":/\b404\b|not found|does not exist|no such plugin/i.test(n)?"not-found":/\b40[13]\b|EACCES|EPERM|permission denied|unauthorized/i.test(n)?"permission":/invalid|malformed|schema|validation|parse error/i.test(n)?"validation":"unknown"}export function logPluginLoadErrors(e,n){for(const i of e){const{name:e,marketplace:l}=o(i.source),r="plugin"in i&&i.plugin?i.plugin:e;t("tengu_plugin_load_failed",{error_category:i.type,_PROTO_plugin_name:r,...l&&{_PROTO_marketplace_name:l},...buildPluginTelemetryFields(r,l,n)})}}
@@ -1 +1 @@
1
- import{feature as e}from"bun:bundle";import{context as t,trace as n}from"@opentelemetry/api";import{AsyncLocalStorage as a}from"async_hooks";import{getFeatureValue_CACHED_MAY_BE_STALE as r}from"../../services/analytics/growthbook.js";import{isEnvDefinedFalsy as s,isEnvTruthy as o}from"../envUtils.js";import{getTelemetryAttributes as i}from"../telemetryAttributes.js";import{addBetaInteractionAttributes as c,addBetaLLMRequestAttributes as p,addBetaLLMResponseAttributes as u,addBetaToolInputAttributes as d,addBetaToolResultAttributes as l,isBetaTracingEnabled as S,truncateContent as f}from"./betaSessionTracing.js";import{endInteractionPerfettoSpan as T,endLLMRequestPerfettoSpan as m,endToolPerfettoSpan as g,endUserInputPerfettoSpan as _,isPerfettoTracingEnabled as b,startInteractionPerfettoSpan as E,startLLMRequestPerfettoSpan as v,startToolPerfettoSpan as A,startUserInputPerfettoSpan as k}from"./perfettoTracing.js";export{S as isBetaTracingEnabled};const y=new a,I=new a,h=new Map,w=new Map;let R=0,D=!1;function getSpanId(e){return e.spanContext().spanId||""}export function isEnhancedTelemetryEnabled(){if(e("ENHANCED_TELEMETRY_BETA")){const e=process.env.CONTEXT_CODE_ENHANCED_TELEMETRY_BETA??process.env.CLAUDE_CODE_ENHANCED_TELEMETRY_BETA??process.env.ENABLE_ENHANCED_TELEMETRY_BETA;return!!o(e)||!s(e)&&("ant"===process.env.USER_TYPE||r("enhanced_telemetry_beta",!1))}return!1}function isAnyTracingEnabled(){return isEnhancedTelemetryEnabled()||S()}function getTracer(){return n.getTracer("com.anthropic.claude_code.tracing","1.0.0")}function createSpanAttributes(e,t={}){return{...i(),"span.type":e,...t}}export function startInteractionSpan(e){!function(){if(D)return;D=!0;const e=setInterval(()=>{const e=Date.now()-18e5;for(const[t,n]of h){const a=n.deref();void 0===a?(h.delete(t),w.delete(t)):a.startTime<e&&(a.ended||a.span.end(),h.delete(t),w.delete(t))}},6e4);"function"==typeof e.unref&&e.unref()}();const t=b()?E(e):void 0;if(!isAnyTracingEnabled()){if(t){const e=n.getActiveSpan()||getTracer().startSpan("dummy"),a=getSpanId(e),r={span:e,startTime:Date.now(),attributes:{},perfettoSpanId:t};return h.set(a,new WeakRef(r)),y.enterWith(r),e}return n.getActiveSpan()||getTracer().startSpan("dummy")}const a=getTracer(),r=o(process.env.OTEL_LOG_USER_PROMPTS);R++;const s=createSpanAttributes("interaction",{user_prompt:r?e:"<REDACTED>",user_prompt_length:e.length,"interaction.sequence":R}),i=a.startSpan("claude_code.interaction",{attributes:s});c(i,e);const p=getSpanId(i),u={span:i,startTime:Date.now(),attributes:s,perfettoSpanId:t};return h.set(p,new WeakRef(u)),y.enterWith(u),i}export function endInteractionSpan(){const e=y.getStore();if(!e)return;if(e.ended)return;if(e.perfettoSpanId&&T(e.perfettoSpanId),!isAnyTracingEnabled())return e.ended=!0,h.delete(getSpanId(e.span)),void y.enterWith(void 0);const t=Date.now()-e.startTime;e.span.setAttributes({"interaction.duration_ms":t}),e.span.end(),e.ended=!0,h.delete(getSpanId(e.span)),y.enterWith(void 0)}export function startLLMRequestSpan(e,a,r,s){const o=b()?v({model:e,querySource:a?.querySource,messageId:void 0}):void 0;if(!isAnyTracingEnabled()){if(o){const t=n.getActiveSpan()||getTracer().startSpan("dummy"),a=getSpanId(t),r={span:t,startTime:Date.now(),attributes:{model:e},perfettoSpanId:o};return h.set(a,new WeakRef(r)),w.set(a,r),t}return n.getActiveSpan()||getTracer().startSpan("dummy")}const i=getTracer(),c=y.getStore(),u=createSpanAttributes("llm_request",{model:e,"llm_request.context":c?"interaction":"standalone",speed:s?"fast":"normal"}),d=c?n.setSpan(t.active(),c.span):t.active(),l=i.startSpan("claude_code.llm_request",{attributes:u},d);a?.querySource&&l.setAttribute("query_source",a.querySource),p(l,a,r);const S=getSpanId(l),f={span:l,startTime:Date.now(),attributes:u,perfettoSpanId:o};return h.set(S,new WeakRef(f)),w.set(S,f),l}export function endLLMRequestSpan(e,t){let n;if(e){const t=getSpanId(e);n=h.get(t)?.deref()}else n=Array.from(h.values()).findLast(e=>{const t=e.deref();return"llm_request"===t?.attributes["span.type"]||t?.attributes.model})?.deref();if(!n)return;const a=Date.now()-n.startTime;if(n.perfettoSpanId&&m(n.perfettoSpanId,{ttftMs:t?.ttftMs,ttltMs:a,promptTokens:t?.inputTokens,outputTokens:t?.outputTokens,cacheReadTokens:t?.cacheReadTokens,cacheCreationTokens:t?.cacheCreationTokens,success:t?.success,error:t?.error,requestSetupMs:t?.requestSetupMs,attemptStartTimes:t?.attemptStartTimes}),!isAnyTracingEnabled()){const e=getSpanId(n.span);return h.delete(e),void w.delete(e)}const r={duration_ms:a};t&&(void 0!==t.inputTokens&&(r.input_tokens=t.inputTokens),void 0!==t.outputTokens&&(r.output_tokens=t.outputTokens),void 0!==t.cacheReadTokens&&(r.cache_read_tokens=t.cacheReadTokens),void 0!==t.cacheCreationTokens&&(r.cache_creation_tokens=t.cacheCreationTokens),void 0!==t.success&&(r.success=t.success),void 0!==t.statusCode&&(r.status_code=t.statusCode),void 0!==t.error&&(r.error=t.error),void 0!==t.attempt&&(r.attempt=t.attempt),void 0!==t.hasToolCall&&(r["response.has_tool_call"]=t.hasToolCall),void 0!==t.ttftMs&&(r.ttft_ms=t.ttftMs),u(r,t)),n.span.setAttributes(r),n.span.end();const s=getSpanId(n.span);h.delete(s),w.delete(s)}export function startToolSpan(e,a,r){const s=b()?A(e,a):void 0;if(!isAnyTracingEnabled()){if(s){const t=n.getActiveSpan()||getTracer().startSpan("dummy"),a=getSpanId(t),r={span:t,startTime:Date.now(),attributes:{"span.type":"tool",tool_name:e},perfettoSpanId:s};return h.set(a,new WeakRef(r)),I.enterWith(r),t}return n.getActiveSpan()||getTracer().startSpan("dummy")}const o=getTracer(),i=y.getStore(),c=createSpanAttributes("tool",{tool_name:e,...a}),p=i?n.setSpan(t.active(),i.span):t.active(),u=o.startSpan("claude_code.tool",{attributes:c},p);r&&d(u,e,r);const l=getSpanId(u),S={span:u,startTime:Date.now(),attributes:c,perfettoSpanId:s};return h.set(l,new WeakRef(S)),I.enterWith(S),u}export function startToolBlockedOnUserSpan(){const e=b()?k("tool_permission"):void 0;if(!isAnyTracingEnabled()){if(e){const t=n.getActiveSpan()||getTracer().startSpan("dummy"),a=getSpanId(t),r={span:t,startTime:Date.now(),attributes:{"span.type":"tool.blocked_on_user"},perfettoSpanId:e};return h.set(a,new WeakRef(r)),w.set(a,r),t}return n.getActiveSpan()||getTracer().startSpan("dummy")}const a=getTracer(),r=I.getStore(),s=createSpanAttributes("tool.blocked_on_user"),o=r?n.setSpan(t.active(),r.span):t.active(),i=a.startSpan("claude_code.tool.blocked_on_user",{attributes:s},o),c=getSpanId(i),p={span:i,startTime:Date.now(),attributes:s,perfettoSpanId:e};return h.set(c,new WeakRef(p)),w.set(c,p),i}export function endToolBlockedOnUserSpan(e,t){const n=Array.from(h.values()).findLast(e=>"tool.blocked_on_user"===e.deref()?.attributes["span.type"])?.deref();if(!n)return;if(n.perfettoSpanId&&_(n.perfettoSpanId,{decision:e,source:t}),!isAnyTracingEnabled()){const e=getSpanId(n.span);return h.delete(e),void w.delete(e)}const a={duration_ms:Date.now()-n.startTime};e&&(a.decision=e),t&&(a.source=t),n.span.setAttributes(a),n.span.end();const r=getSpanId(n.span);h.delete(r),w.delete(r)}export function startToolExecutionSpan(){if(!isAnyTracingEnabled())return n.getActiveSpan()||getTracer().startSpan("dummy");const e=getTracer(),a=I.getStore(),r=createSpanAttributes("tool.execution"),s=a?n.setSpan(t.active(),a.span):t.active(),o=e.startSpan("claude_code.tool.execution",{attributes:r},s),i=getSpanId(o),c={span:o,startTime:Date.now(),attributes:r};return h.set(i,new WeakRef(c)),w.set(i,c),o}export function endToolExecutionSpan(e){if(!isAnyTracingEnabled())return;const t=Array.from(h.values()).findLast(e=>"tool.execution"===e.deref()?.attributes["span.type"])?.deref();if(!t)return;const n={duration_ms:Date.now()-t.startTime};e&&(void 0!==e.success&&(n.success=e.success),void 0!==e.error&&(n.error=e.error)),t.span.setAttributes(n),t.span.end();const a=getSpanId(t.span);h.delete(a),w.delete(a)}export function endToolSpan(e,t){const n=I.getStore();if(!n)return;if(n.perfettoSpanId&&g(n.perfettoSpanId,{success:!0,resultTokens:t}),!isAnyTracingEnabled()){const e=getSpanId(n.span);return h.delete(e),void I.enterWith(void 0)}const a={duration_ms:Date.now()-n.startTime};if(e){const t=n.attributes.tool_name||"unknown";l(a,t,e)}void 0!==t&&(a.result_tokens=t),n.span.setAttributes(a),n.span.end();const r=getSpanId(n.span);h.delete(r),I.enterWith(void 0)}export function addToolContentEvent(e,t){if(!isAnyTracingEnabled()||!o(process.env.OTEL_LOG_TOOL_CONTENT))return;const n=I.getStore();if(!n)return;const a={};for(const[e,n]of Object.entries(t))if("string"==typeof n){const{content:t,truncated:r}=f(n);a[e]=t,r&&(a[`${e}_truncated`]=!0,a[`${e}_original_length`]=n.length)}else a[e]=n;n.span.addEvent(e,a)}export function getCurrentSpan(){return isAnyTracingEnabled()?I.getStore()?.span??y.getStore()?.span??null:null}export async function executeInSpan(e,a,r){if(!isAnyTracingEnabled())return a(n.getActiveSpan()||getTracer().startSpan("dummy"));const s=getTracer(),o=I.getStore()??y.getStore(),i=createSpanAttributes("tool",{...r}),c=o?n.setSpan(t.active(),o.span):t.active(),p=s.startSpan(e,{attributes:i},c),u=getSpanId(p),d={span:p,startTime:Date.now(),attributes:i};h.set(u,new WeakRef(d)),w.set(u,d);try{const e=await a(p);return p.end(),h.delete(u),w.delete(u),e}catch(e){throw e instanceof Error&&p.recordException(e),p.end(),h.delete(u),w.delete(u),e}}export function startHookSpan(e,a,r,s){if(!S())return n.getActiveSpan()||getTracer().startSpan("dummy");const o=getTracer(),i=I.getStore()??y.getStore(),c=createSpanAttributes("hook",{hook_event:e,hook_name:a,num_hooks:r,hook_definitions:s}),p=i?n.setSpan(t.active(),i.span):t.active(),u=o.startSpan("claude_code.hook",{attributes:c},p),d=getSpanId(u),l={span:u,startTime:Date.now(),attributes:c};return h.set(d,new WeakRef(l)),w.set(d,l),u}export function endHookSpan(e,t){if(!S())return;const n=getSpanId(e),a=h.get(n)?.deref();if(!a)return;const r={duration_ms:Date.now()-a.startTime};t&&(void 0!==t.numSuccess&&(r.num_success=t.numSuccess),void 0!==t.numBlocking&&(r.num_blocking=t.numBlocking),void 0!==t.numNonBlockingError&&(r.num_non_blocking_error=t.numNonBlockingError),void 0!==t.numCancelled&&(r.num_cancelled=t.numCancelled)),a.span.setAttributes(r),a.span.end(),h.delete(n),w.delete(n)}
1
+ import{feature as e}from"../../recovery/bunBundleShim.js";import{context as t,trace as n}from"@opentelemetry/api";import{AsyncLocalStorage as r}from"async_hooks";import{getFeatureValue_CACHED_MAY_BE_STALE as a}from"../../services/analytics/growthbook.js";import{isEnvDefinedFalsy as o,isEnvTruthy as s}from"../envUtils.js";import{getTelemetryAttributes as i}from"../telemetryAttributes.js";import{addBetaInteractionAttributes as c,addBetaLLMRequestAttributes as p,addBetaLLMResponseAttributes as u,addBetaToolInputAttributes as d,addBetaToolResultAttributes as l,isBetaTracingEnabled as S,truncateContent as f}from"./betaSessionTracing.js";import{endInteractionPerfettoSpan as m,endLLMRequestPerfettoSpan as T,endToolPerfettoSpan as g,endUserInputPerfettoSpan as _,isPerfettoTracingEnabled as v,startInteractionPerfettoSpan as b,startLLMRequestPerfettoSpan as E,startToolPerfettoSpan as k,startUserInputPerfettoSpan as A}from"./perfettoTracing.js";export{S as isBetaTracingEnabled};const y=new r,I=new r,h=new Map,w=new Map;let x=0,D=!1;function getSpanId(e){return e.spanContext().spanId||""}export function isEnhancedTelemetryEnabled(){if(e("ENHANCED_TELEMETRY_BETA")){const e=process.env.CONTEXT_CODE_ENHANCED_TELEMETRY_BETA??process.env.CLAUDE_CODE_ENHANCED_TELEMETRY_BETA??process.env.ENABLE_ENHANCED_TELEMETRY_BETA;return!!s(e)||!o(e)&&("ant"===process.env.USER_TYPE||a("enhanced_telemetry_beta",!1))}return!1}function isAnyTracingEnabled(){return isEnhancedTelemetryEnabled()||S()}function getTracer(){return n.getTracer("com.anthropic.claude_code.tracing","1.0.0")}function createSpanAttributes(e,t={}){return{...i(),"span.type":e,...t}}export function startInteractionSpan(e){!function(){if(D)return;D=!0;const e=setInterval(()=>{const e=Date.now()-18e5;for(const[t,n]of h){const r=n.deref();void 0===r?(h.delete(t),w.delete(t)):r.startTime<e&&(r.ended||r.span.end(),h.delete(t),w.delete(t))}},6e4);"function"==typeof e.unref&&e.unref()}();const t=v()?b(e):void 0;if(!isAnyTracingEnabled()){if(t){const e=n.getActiveSpan()||getTracer().startSpan("dummy"),r=getSpanId(e),a={span:e,startTime:Date.now(),attributes:{},perfettoSpanId:t};return h.set(r,new WeakRef(a)),y.enterWith(a),e}return n.getActiveSpan()||getTracer().startSpan("dummy")}const r=getTracer(),a=s(process.env.OTEL_LOG_USER_PROMPTS);x++;const o=createSpanAttributes("interaction",{user_prompt:a?e:"<REDACTED>",user_prompt_length:e.length,"interaction.sequence":x}),i=r.startSpan("claude_code.interaction",{attributes:o});c(i,e);const p=getSpanId(i),u={span:i,startTime:Date.now(),attributes:o,perfettoSpanId:t};return h.set(p,new WeakRef(u)),y.enterWith(u),i}export function endInteractionSpan(){const e=y.getStore();if(!e)return;if(e.ended)return;if(e.perfettoSpanId&&m(e.perfettoSpanId),!isAnyTracingEnabled())return e.ended=!0,h.delete(getSpanId(e.span)),void y.enterWith(void 0);const t=Date.now()-e.startTime;e.span.setAttributes({"interaction.duration_ms":t}),e.span.end(),e.ended=!0,h.delete(getSpanId(e.span)),y.enterWith(void 0)}export function startLLMRequestSpan(e,r,a,o){const s=v()?E({model:e,querySource:r?.querySource,messageId:void 0}):void 0;if(!isAnyTracingEnabled()){if(s){const t=n.getActiveSpan()||getTracer().startSpan("dummy"),r=getSpanId(t),a={span:t,startTime:Date.now(),attributes:{model:e},perfettoSpanId:s};return h.set(r,new WeakRef(a)),w.set(r,a),t}return n.getActiveSpan()||getTracer().startSpan("dummy")}const i=getTracer(),c=y.getStore(),u=createSpanAttributes("llm_request",{model:e,"llm_request.context":c?"interaction":"standalone",speed:o?"fast":"normal"}),d=c?n.setSpan(t.active(),c.span):t.active(),l=i.startSpan("claude_code.llm_request",{attributes:u},d);r?.querySource&&l.setAttribute("query_source",r.querySource),p(l,r,a);const S=getSpanId(l),f={span:l,startTime:Date.now(),attributes:u,perfettoSpanId:s};return h.set(S,new WeakRef(f)),w.set(S,f),l}export function endLLMRequestSpan(e,t){let n;if(e){const t=getSpanId(e);n=h.get(t)?.deref()}else n=Array.from(h.values()).findLast(e=>{const t=e.deref();return"llm_request"===t?.attributes["span.type"]||t?.attributes.model})?.deref();if(!n)return;const r=Date.now()-n.startTime;if(n.perfettoSpanId&&T(n.perfettoSpanId,{ttftMs:t?.ttftMs,ttltMs:r,promptTokens:t?.inputTokens,outputTokens:t?.outputTokens,cacheReadTokens:t?.cacheReadTokens,cacheCreationTokens:t?.cacheCreationTokens,success:t?.success,error:t?.error,requestSetupMs:t?.requestSetupMs,attemptStartTimes:t?.attemptStartTimes}),!isAnyTracingEnabled()){const e=getSpanId(n.span);return h.delete(e),void w.delete(e)}const a={duration_ms:r};t&&(void 0!==t.inputTokens&&(a.input_tokens=t.inputTokens),void 0!==t.outputTokens&&(a.output_tokens=t.outputTokens),void 0!==t.cacheReadTokens&&(a.cache_read_tokens=t.cacheReadTokens),void 0!==t.cacheCreationTokens&&(a.cache_creation_tokens=t.cacheCreationTokens),void 0!==t.success&&(a.success=t.success),void 0!==t.statusCode&&(a.status_code=t.statusCode),void 0!==t.error&&(a.error=t.error),void 0!==t.attempt&&(a.attempt=t.attempt),void 0!==t.hasToolCall&&(a["response.has_tool_call"]=t.hasToolCall),void 0!==t.ttftMs&&(a.ttft_ms=t.ttftMs),u(a,t)),n.span.setAttributes(a),n.span.end();const o=getSpanId(n.span);h.delete(o),w.delete(o)}export function startToolSpan(e,r,a){const o=v()?k(e,r):void 0;if(!isAnyTracingEnabled()){if(o){const t=n.getActiveSpan()||getTracer().startSpan("dummy"),r=getSpanId(t),a={span:t,startTime:Date.now(),attributes:{"span.type":"tool",tool_name:e},perfettoSpanId:o};return h.set(r,new WeakRef(a)),I.enterWith(a),t}return n.getActiveSpan()||getTracer().startSpan("dummy")}const s=getTracer(),i=y.getStore(),c=createSpanAttributes("tool",{tool_name:e,...r}),p=i?n.setSpan(t.active(),i.span):t.active(),u=s.startSpan("claude_code.tool",{attributes:c},p);a&&d(u,e,a);const l=getSpanId(u),S={span:u,startTime:Date.now(),attributes:c,perfettoSpanId:o};return h.set(l,new WeakRef(S)),I.enterWith(S),u}export function startToolBlockedOnUserSpan(){const e=v()?A("tool_permission"):void 0;if(!isAnyTracingEnabled()){if(e){const t=n.getActiveSpan()||getTracer().startSpan("dummy"),r=getSpanId(t),a={span:t,startTime:Date.now(),attributes:{"span.type":"tool.blocked_on_user"},perfettoSpanId:e};return h.set(r,new WeakRef(a)),w.set(r,a),t}return n.getActiveSpan()||getTracer().startSpan("dummy")}const r=getTracer(),a=I.getStore(),o=createSpanAttributes("tool.blocked_on_user"),s=a?n.setSpan(t.active(),a.span):t.active(),i=r.startSpan("claude_code.tool.blocked_on_user",{attributes:o},s),c=getSpanId(i),p={span:i,startTime:Date.now(),attributes:o,perfettoSpanId:e};return h.set(c,new WeakRef(p)),w.set(c,p),i}export function endToolBlockedOnUserSpan(e,t){const n=Array.from(h.values()).findLast(e=>"tool.blocked_on_user"===e.deref()?.attributes["span.type"])?.deref();if(!n)return;if(n.perfettoSpanId&&_(n.perfettoSpanId,{decision:e,source:t}),!isAnyTracingEnabled()){const e=getSpanId(n.span);return h.delete(e),void w.delete(e)}const r={duration_ms:Date.now()-n.startTime};e&&(r.decision=e),t&&(r.source=t),n.span.setAttributes(r),n.span.end();const a=getSpanId(n.span);h.delete(a),w.delete(a)}export function startToolExecutionSpan(){if(!isAnyTracingEnabled())return n.getActiveSpan()||getTracer().startSpan("dummy");const e=getTracer(),r=I.getStore(),a=createSpanAttributes("tool.execution"),o=r?n.setSpan(t.active(),r.span):t.active(),s=e.startSpan("claude_code.tool.execution",{attributes:a},o),i=getSpanId(s),c={span:s,startTime:Date.now(),attributes:a};return h.set(i,new WeakRef(c)),w.set(i,c),s}export function endToolExecutionSpan(e){if(!isAnyTracingEnabled())return;const t=Array.from(h.values()).findLast(e=>"tool.execution"===e.deref()?.attributes["span.type"])?.deref();if(!t)return;const n={duration_ms:Date.now()-t.startTime};e&&(void 0!==e.success&&(n.success=e.success),void 0!==e.error&&(n.error=e.error)),t.span.setAttributes(n),t.span.end();const r=getSpanId(t.span);h.delete(r),w.delete(r)}export function endToolSpan(e,t){const n=I.getStore();if(!n)return;if(n.perfettoSpanId&&g(n.perfettoSpanId,{success:!0,resultTokens:t}),!isAnyTracingEnabled()){const e=getSpanId(n.span);return h.delete(e),void I.enterWith(void 0)}const r={duration_ms:Date.now()-n.startTime};if(e){const t=n.attributes.tool_name||"unknown";l(r,t,e)}void 0!==t&&(r.result_tokens=t),n.span.setAttributes(r),n.span.end();const a=getSpanId(n.span);h.delete(a),I.enterWith(void 0)}export function addToolContentEvent(e,t){if(!isAnyTracingEnabled()||!s(process.env.OTEL_LOG_TOOL_CONTENT))return;const n=I.getStore();if(!n)return;const r={};for(const[e,n]of Object.entries(t))if("string"==typeof n){const{content:t,truncated:a}=f(n);r[e]=t,a&&(r[`${e}_truncated`]=!0,r[`${e}_original_length`]=n.length)}else r[e]=n;n.span.addEvent(e,r)}export function getCurrentSpan(){return isAnyTracingEnabled()?I.getStore()?.span??y.getStore()?.span??null:null}export async function executeInSpan(e,r,a){if(!isAnyTracingEnabled())return r(n.getActiveSpan()||getTracer().startSpan("dummy"));const o=getTracer(),s=I.getStore()??y.getStore(),i=createSpanAttributes("tool",{...a}),c=s?n.setSpan(t.active(),s.span):t.active(),p=o.startSpan(e,{attributes:i},c),u=getSpanId(p),d={span:p,startTime:Date.now(),attributes:i};h.set(u,new WeakRef(d)),w.set(u,d);try{const e=await r(p);return p.end(),h.delete(u),w.delete(u),e}catch(e){throw e instanceof Error&&p.recordException(e),p.end(),h.delete(u),w.delete(u),e}}export function startHookSpan(e,r,a,o){if(!S())return n.getActiveSpan()||getTracer().startSpan("dummy");const s=getTracer(),i=I.getStore()??y.getStore(),c=createSpanAttributes("hook",{hook_event:e,hook_name:r,num_hooks:a,hook_definitions:o}),p=i?n.setSpan(t.active(),i.span):t.active(),u=s.startSpan("claude_code.hook",{attributes:c},p),d=getSpanId(u),l={span:u,startTime:Date.now(),attributes:c};return h.set(d,new WeakRef(l)),w.set(d,l),u}export function endHookSpan(e,t){if(!S())return;const n=getSpanId(e),r=h.get(n)?.deref();if(!r)return;const a={duration_ms:Date.now()-r.startTime};t&&(void 0!==t.numSuccess&&(a.num_success=t.numSuccess),void 0!==t.numBlocking&&(a.num_blocking=t.numBlocking),void 0!==t.numNonBlockingError&&(a.num_non_blocking_error=t.numNonBlockingError),void 0!==t.numCancelled&&(a.num_cancelled=t.numCancelled)),r.span.setAttributes(a),r.span.end(),h.delete(n),w.delete(n)}
@@ -1 +1 @@
1
- import{MACRO as t}from"../recovery/bunBundleShim.js";import{getSessionId as e}from"src/bootstrap/state.js";import{getOauthAccountInfo as r}from"./auth.js";import{getOrCreateUserID as s}from"./config.js";import{envDynamic as o}from"./envDynamic.js";import{isEnvTruthy as n}from"./envUtils.js";import{toTaggedId as i}from"./taggedId.js";const u={OTEL_METRICS_INCLUDE_SESSION_ID:!0,OTEL_METRICS_INCLUDE_VERSION:!1,OTEL_METRICS_INCLUDE_ACCOUNT_UUID:!0};function shouldIncludeAttribute(t){const e=u[t],r=process.env[t];return void 0===r?e:n(r)}export function getTelemetryAttributes(){const n=s(),u=e(),I={"user.id":n};shouldIncludeAttribute("OTEL_METRICS_INCLUDE_SESSION_ID")&&(I["session.id"]=u),shouldIncludeAttribute("OTEL_METRICS_INCLUDE_VERSION")&&(I["app.version"]=t.VERSION);const _=r();if(_){const t=_.organizationUuid,e=_.emailAddress,r=_.accountUuid;t&&(I["organization.id"]=t),e&&(I["user.email"]=e),r&&shouldIncludeAttribute("OTEL_METRICS_INCLUDE_ACCOUNT_UUID")&&(I["user.account_uuid"]=r,I["user.account_id"]=process.env.CONTEXT_CODE_ACCOUNT_TAGGED_ID||process.env.CLAUDE_CODE_ACCOUNT_TAGGED_ID||i("user",r))}return o.terminal&&(I["terminal.type"]=o.terminal),I}
1
+ import{MACRO as t}from"../recovery/bunBundleShim.js";import{getSessionId as e}from"../bootstrap/state.js";import{getOauthAccountInfo as o}from"./auth.js";import{getOrCreateUserID as r}from"./config.js";import{envDynamic as i}from"./envDynamic.js";import{isEnvTruthy as s}from"./envUtils.js";import{toTaggedId as n}from"./taggedId.js";const u={OTEL_METRICS_INCLUDE_SESSION_ID:!0,OTEL_METRICS_INCLUDE_VERSION:!1,OTEL_METRICS_INCLUDE_ACCOUNT_UUID:!0};function shouldIncludeAttribute(t){const e=u[t],o=process.env[t];return void 0===o?e:s(o)}export function getTelemetryAttributes(){const s=r(),u=e(),_={"user.id":s};shouldIncludeAttribute("OTEL_METRICS_INCLUDE_SESSION_ID")&&(_["session.id"]=u),shouldIncludeAttribute("OTEL_METRICS_INCLUDE_VERSION")&&(_["app.version"]=t.VERSION);const E=o();if(E){const t=E.organizationUuid,e=E.emailAddress,o=E.accountUuid;t&&(_["organization.id"]=t),e&&(_["user.email"]=e),o&&shouldIncludeAttribute("OTEL_METRICS_INCLUDE_ACCOUNT_UUID")&&(_["user.account_uuid"]=o,_["user.account_id"]=process.env.CONTEXT_CODE_ACCOUNT_TAGGED_ID||process.env.CLAUDE_CODE_ACCOUNT_TAGGED_ID||n("user",o))}return i.terminal&&(_["terminal.type"]=i.terminal),_}
@@ -1 +1 @@
1
- import t from"axios";import{randomUUID as e}from"crypto";import{getOauthConfig as s}from"src/constants/oauth.js";import{getOrganizationUUID as o}from"src/services/oauth/client.js";import r from"zod/v4";import{getClaudeAIOAuthTokens as n}from"../auth.js";import{logForDebugging as i}from"../debug.js";import{parseGitHubRepository as a}from"../detectRepository.js";import{errorMessage as c,toError as u}from"../errors.js";import{lazySchema as p}from"../lazySchema.js";import{logError as d}from"../log.js";import{sleep as l}from"../sleep.js";import{jsonStringify as g}from"../slowOperations.js";const h=[2e3,4e3,8e3,16e3],f=h.length;export const CCR_BYOC_BETA="ccr-byoc-2025-07-29";export function isTransientNetworkError(e){return!!t.isAxiosError(e)&&(!e.response||e.response.status>=500)}export async function axiosGetWithRetry(e,s){let o;for(let r=0;r<=f;r++)try{return await t.get(e,s)}catch(t){if(o=t,!isTransientNetworkError(t))throw t;if(r>=f)throw i(`Teleport request failed after ${r+1} attempts: ${c(t)}`),t;const e=h[r]??2e3;i(`Teleport request failed (attempt ${r+1}/${f+1}), retrying in ${e}ms: ${c(t)}`),await l(e)}throw o}export const CodeSessionSchema=p(()=>r.object({id:r.string(),title:r.string(),description:r.string(),status:r.enum(["idle","working","waiting","completed","archived","cancelled","rejected"]),repo:r.object({name:r.string(),owner:r.object({login:r.string()}),default_branch:r.string().optional()}).nullable(),turns:r.array(r.string()),created_at:r.string(),updated_at:r.string()}));export async function prepareApiRequest(){const t=n()?.accessToken;if(void 0===t)throw new Error("Context Code web sessions require authentication with a Claude.ai account. API key authentication is not sufficient. Please run /login to authenticate, or check your authentication status with /status.");const e=await o();if(!e)throw new Error("Unable to get organization UUID");return{accessToken:t,orgUUID:e}}export async function fetchCodeSessionsFromSessionsAPI(){const{accessToken:t,orgUUID:e}=await prepareApiRequest(),o=`${s().BASE_API_URL}/v1/sessions`;try{const s={...getOAuthHeaders(t),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":e},r=await axiosGetWithRetry(o,{headers:s});if(200!==r.status)throw new Error(`Failed to fetch code sessions: ${r.statusText}`);return r.data.data.map(t=>{const e=t.session_context.sources.find(t=>"git_repository"===t.type);let s=null;if(e?.url){const t=a(e.url);if(t){const[o,r]=t.split("/");o&&r&&(s={name:r,owner:{login:o},default_branch:e.revision||void 0})}}return{id:t.id,title:t.title||"Untitled",description:"",status:t.session_status,repo:s,turns:[],created_at:t.created_at,updated_at:t.updated_at}})}catch(t){const e=u(t);throw d(e),t}}export function getOAuthHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json","anthropic-version":"2023-06-01"}}export async function fetchSession(e){const{accessToken:o,orgUUID:r}=await prepareApiRequest(),n=`${s().BASE_API_URL}/v1/sessions/${e}`,i={...getOAuthHeaders(o),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":r},a=await t.get(n,{headers:i,timeout:15e3,validateStatus:t=>t<500});if(200!==a.status){const t=a.data,s=t?.error?.message;if(404===a.status)throw new Error(`Session not found: ${e}`);if(401===a.status)throw new Error("Session expired. Please run /login to sign in again.");throw new Error(s||`Failed to fetch session: ${a.status} ${a.statusText}`)}return a.data}export function getBranchFromSession(t){const e=t.session_context.outcomes?.find(t=>"git_repository"===t.type);return e?.git_info?.branches[0]}export async function sendEventToRemoteSession(o,r,n){try{const{accessToken:a,orgUUID:c}=await prepareApiRequest(),u=`${s().BASE_API_URL}/v1/sessions/${o}/events`,p={...getOAuthHeaders(a),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":c},d={events:[{uuid:n?.uuid??e(),session_id:o,type:"user",parent_tool_use_id:null,message:{role:"user",content:r}}]};i(`[sendEventToRemoteSession] Sending event to session ${o}`);const l=await t.post(u,d,{headers:p,validateStatus:t=>t<500,timeout:3e4});return 200===l.status||201===l.status?(i(`[sendEventToRemoteSession] Successfully sent event to session ${o}`),!0):(i(`[sendEventToRemoteSession] Failed with status ${l.status}: ${g(l.data)}`),!1)}catch(t){return i(`[sendEventToRemoteSession] Error: ${c(t)}`),!1}}export async function updateSessionTitle(e,o){try{const{accessToken:r,orgUUID:n}=await prepareApiRequest(),a=`${s().BASE_API_URL}/v1/sessions/${e}`,c={...getOAuthHeaders(r),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":n};i(`[updateSessionTitle] Updating title for session ${e}: "${o}"`);const u=await t.patch(a,{title:o},{headers:c,validateStatus:t=>t<500});return 200===u.status?(i(`[updateSessionTitle] Successfully updated title for session ${e}`),!0):(i(`[updateSessionTitle] Failed with status ${u.status}: ${g(u.data)}`),!1)}catch(t){return i(`[updateSessionTitle] Error: ${c(t)}`),!1}}
1
+ import t from"axios";import{randomUUID as e}from"crypto";import{getOauthConfig as s}from"../../constants/oauth.js";import{getOrganizationUUID as o}from"../../services/oauth/client.js";import r from"zod/v4";import{getClaudeAIOAuthTokens as n}from"../auth.js";import{logForDebugging as i}from"../debug.js";import{parseGitHubRepository as a}from"../detectRepository.js";import{errorMessage as c,toError as u}from"../errors.js";import{lazySchema as p}from"../lazySchema.js";import{logError as d}from"../log.js";import{sleep as l}from"../sleep.js";import{jsonStringify as h}from"../slowOperations.js";const f=[2e3,4e3,8e3,16e3],m=f.length;export const CCR_BYOC_BETA="ccr-byoc-2025-07-29";export function isTransientNetworkError(e){return!!t.isAxiosError(e)&&(!e.response||e.response.status>=500)}export async function axiosGetWithRetry(e,s){let o;for(let r=0;r<=m;r++)try{return await t.get(e,s)}catch(t){if(o=t,!isTransientNetworkError(t))throw t;if(r>=m)throw i(`Teleport request failed after ${r+1} attempts: ${c(t)}`),t;const e=f[r]??2e3;i(`Teleport request failed (attempt ${r+1}/${m+1}), retrying in ${e}ms: ${c(t)}`),await l(e)}throw o}export const CodeSessionSchema=p(()=>r.object({id:r.string(),title:r.string(),description:r.string(),status:r.enum(["idle","working","waiting","completed","archived","cancelled","rejected"]),repo:r.object({name:r.string(),owner:r.object({login:r.string()}),default_branch:r.string().optional()}).nullable(),turns:r.array(r.string()),created_at:r.string(),updated_at:r.string()}));export async function prepareApiRequest(){const t=n()?.accessToken;if(void 0===t)throw new Error("Context Code web sessions require authentication with a Claude.ai account. API key authentication is not sufficient. Please run /login to authenticate, or check your authentication status with /status.");const e=await o();if(!e)throw new Error("Unable to get organization UUID");return{accessToken:t,orgUUID:e}}export async function fetchCodeSessionsFromSessionsAPI(){const{accessToken:t,orgUUID:e}=await prepareApiRequest(),o=`${s().BASE_API_URL}/v1/sessions`;try{const s={...getOAuthHeaders(t),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":e},r=await axiosGetWithRetry(o,{headers:s});if(200!==r.status)throw new Error(`Failed to fetch code sessions: ${r.statusText}`);return r.data.data.map(t=>{const e=t.session_context.sources.find(t=>"git_repository"===t.type);let s=null;if(e?.url){const t=a(e.url);if(t){const[o,r]=t.split("/");o&&r&&(s={name:r,owner:{login:o},default_branch:e.revision||void 0})}}return{id:t.id,title:t.title||"Untitled",description:"",status:t.session_status,repo:s,turns:[],created_at:t.created_at,updated_at:t.updated_at}})}catch(t){const e=u(t);throw d(e),t}}export function getOAuthHeaders(t){return{Authorization:`Bearer ${t}`,"Content-Type":"application/json","anthropic-version":"2023-06-01"}}export async function fetchSession(e){const{accessToken:o,orgUUID:r}=await prepareApiRequest(),n=`${s().BASE_API_URL}/v1/sessions/${e}`,i={...getOAuthHeaders(o),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":r},a=await t.get(n,{headers:i,timeout:15e3,validateStatus:t=>t<500});if(200!==a.status){const t=a.data,s=t?.error?.message;if(404===a.status)throw new Error(`Session not found: ${e}`);if(401===a.status)throw new Error("Session expired. Please run /login to sign in again.");throw new Error(s||`Failed to fetch session: ${a.status} ${a.statusText}`)}return a.data}export function getBranchFromSession(t){const e=t.session_context.outcomes?.find(t=>"git_repository"===t.type);return e?.git_info?.branches[0]}export async function sendEventToRemoteSession(o,r,n){try{const{accessToken:a,orgUUID:c}=await prepareApiRequest(),u=`${s().BASE_API_URL}/v1/sessions/${o}/events`,p={...getOAuthHeaders(a),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":c},d={events:[{uuid:n?.uuid??e(),session_id:o,type:"user",parent_tool_use_id:null,message:{role:"user",content:r}}]};i(`[sendEventToRemoteSession] Sending event to session ${o}`);const l=await t.post(u,d,{headers:p,validateStatus:t=>t<500,timeout:3e4});return 200===l.status||201===l.status?(i(`[sendEventToRemoteSession] Successfully sent event to session ${o}`),!0):(i(`[sendEventToRemoteSession] Failed with status ${l.status}: ${h(l.data)}`),!1)}catch(t){return i(`[sendEventToRemoteSession] Error: ${c(t)}`),!1}}export async function updateSessionTitle(e,o){try{const{accessToken:r,orgUUID:n}=await prepareApiRequest(),a=`${s().BASE_API_URL}/v1/sessions/${e}`,c={...getOAuthHeaders(r),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":n};i(`[updateSessionTitle] Updating title for session ${e}: "${o}"`);const u=await t.patch(a,{title:o},{headers:c,validateStatus:t=>t<500});return 200===u.status?(i(`[updateSessionTitle] Successfully updated title for session ${e}`),!0):(i(`[updateSessionTitle] Failed with status ${u.status}: ${h(u.data)}`),!1)}catch(t){return i(`[updateSessionTitle] Error: ${c(t)}`),!1}}
@@ -1 +1 @@
1
- import t from"axios";import{getOauthConfig as o}from"src/constants/oauth.js";import{getOrganizationUUID as e}from"src/services/oauth/client.js";import{getClaudeAIOAuthTokens as n}from"../auth.js";import{toError as r}from"../errors.js";import{logError as a}from"../log.js";import{getOAuthHeaders as i}from"./api.js";export async function fetchEnvironments(){const s=n()?.accessToken;if(!s)throw new Error("Context Code web sessions require authentication with a Claude.ai account. API key authentication is not sufficient. Please run /login to authenticate, or check your authentication status with /status.");const c=await e();if(!c)throw new Error("Unable to get organization UUID");const u=`${o().BASE_API_URL}/v1/environment_providers`;try{const o={...i(s),"x-organization-uuid":c},e=await t.get(u,{headers:o,timeout:15e3});if(200!==e.status)throw new Error(`Failed to fetch environments: ${e.status} ${e.statusText}`);return e.data.environments}catch(t){const o=r(t);throw a(o),new Error(`Failed to fetch environments: ${o.message}`)}}export async function createDefaultCloudEnvironment(r){const a=n()?.accessToken;if(!a)throw new Error("No access token available");const s=await e();if(!s)throw new Error("Unable to get organization UUID");const c=`${o().BASE_API_URL}/v1/environment_providers/cloud/create`;return(await t.post(c,{name:r,kind:"anthropic_cloud",description:"",config:{environment_type:"anthropic",cwd:"/home/user",init_script:null,environment:{},languages:[{name:"python",version:"3.11"},{name:"node",version:"20"}],network_config:{allowed_hosts:[],allow_default_hosts:!0}}},{headers:{...i(a),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":s},timeout:15e3})).data}
1
+ import t from"axios";import{getOauthConfig as o}from"../../constants/oauth.js";import{getOrganizationUUID as e}from"../../services/oauth/client.js";import{getClaudeAIOAuthTokens as n}from"../auth.js";import{toError as r}from"../errors.js";import{logError as i}from"../log.js";import{getOAuthHeaders as a}from"./api.js";export async function fetchEnvironments(){const s=n()?.accessToken;if(!s)throw new Error("Context Code web sessions require authentication with a Claude.ai account. API key authentication is not sufficient. Please run /login to authenticate, or check your authentication status with /status.");const c=await e();if(!c)throw new Error("Unable to get organization UUID");const u=`${o().BASE_API_URL}/v1/environment_providers`;try{const o={...a(s),"x-organization-uuid":c},e=await t.get(u,{headers:o,timeout:15e3});if(200!==e.status)throw new Error(`Failed to fetch environments: ${e.status} ${e.statusText}`);return e.data.environments}catch(t){const o=r(t);throw i(o),new Error(`Failed to fetch environments: ${o.message}`)}}export async function createDefaultCloudEnvironment(r){const i=n()?.accessToken;if(!i)throw new Error("No access token available");const s=await e();if(!s)throw new Error("Unable to get organization UUID");const c=`${o().BASE_API_URL}/v1/environment_providers/cloud/create`;return(await t.post(c,{name:r,kind:"anthropic_cloud",description:"",config:{environment_type:"anthropic",cwd:"/home/user",init_script:null,environment:{},languages:[{name:"python",version:"3.11"},{name:"node",version:"20"}],network_config:{allowed_hosts:[],allow_default_hosts:!0}}},{headers:{...a(i),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":s},timeout:15e3})).data}
@@ -1 +1 @@
1
- import{stat as e,unlink as t}from"fs/promises";import{logEvent as s}from"src/services/analytics/index.js";import{getFeatureValue_CACHED_MAY_BE_STALE as r}from"../../services/analytics/growthbook.js";import{uploadFile as o}from"../../services/api/filesApi.js";import{getCwd as a}from"../cwd.js";import{logForDebugging as i}from"../debug.js";import{execFileNoThrowWithCwd as c}from"../execFileNoThrow.js";import{findGitRoot as d,gitExe as n}from"../git.js";import{generateTempFilePath as l}from"../tempfile.js";export async function createAndUploadGitBundle(u,f){const g=f?.cwd??a(),p=d(g);if(!p)return{success:!1,error:"Not in a git repository"};for(const e of["refs/seed/stash","refs/seed/root"])await c(n(),["update-ref","-d",e],{cwd:p});const m=await c(n(),["for-each-ref","--count=1","refs/"],{cwd:p});if(0===m.code&&""===m.stdout.trim())return s("tengu_ccr_bundle_upload",{outcome:"empty_repo"}),{success:!1,error:"Repository has no commits yet",failReason:"empty_repo"};const w=await c(n(),["stash","create"],{cwd:p,abortSignal:f?.signal}),_=0===w.code?w.stdout.trim():"",b=""!==_;0!==w.code?i(`[gitBundle] git stash create failed (${w.code}), proceeding without WIP: ${w.stderr.slice(0,200)}`):b&&(i(`[gitBundle] Captured WIP as stash ${_}`),await c(n(),["update-ref","refs/seed/stash",_],{cwd:p}));const h=l("ccr-seed",".bundle");try{const t=r("tengu_ccr_bundle_max_bytes",null)??104857600,a=await async function(t,s,r,o,a){const d=o?["refs/seed/stash"]:[],mkBundle=e=>c(n(),["bundle","create",s,e,...d],{cwd:t,abortSignal:a}),l=await mkBundle("--all");if(0!==l.code)return{ok:!1,error:`git bundle create --all failed (${l.code}): ${l.stderr.slice(0,200)}`,failReason:"git_error"};const{size:u}=await e(s);if(u<=r)return{ok:!0,size:u,scope:"all"};i(`[gitBundle] --all bundle is ${(u/1024/1024).toFixed(1)}MB (> ${(r/1024/1024).toFixed(0)}MB), retrying HEAD-only`);const f=await mkBundle("HEAD");if(0!==f.code)return{ok:!1,error:`git bundle create HEAD failed (${f.code}): ${f.stderr.slice(0,200)}`,failReason:"git_error"};const{size:g}=await e(s);if(g<=r)return{ok:!0,size:g,scope:"head"};i(`[gitBundle] HEAD bundle is ${(g/1024/1024).toFixed(1)}MB, retrying squashed-root`);const p=o?"refs/seed/stash^{tree}":"HEAD^{tree}",m=await c(n(),["commit-tree",p,"-m","seed"],{cwd:t,abortSignal:a});if(0!==m.code)return{ok:!1,error:`git commit-tree failed (${m.code}): ${m.stderr.slice(0,200)}`,failReason:"git_error"};const w=m.stdout.trim();await c(n(),["update-ref","refs/seed/root",w],{cwd:t});const _=await c(n(),["bundle","create",s,"refs/seed/root"],{cwd:t,abortSignal:a});if(0!==_.code)return{ok:!1,error:`git bundle create refs/seed/root failed (${_.code}): ${_.stderr.slice(0,200)}`,failReason:"git_error"};const{size:b}=await e(s);return b<=r?{ok:!0,size:b,scope:"squashed"}:{ok:!1,error:"Repo is too large to bundle. Please setup GitHub on https://claude.ai/code",failReason:"too_large"}}(p,h,t,b,f?.signal);if(!a.ok)return i(`[gitBundle] ${a.error}`),s("tengu_ccr_bundle_upload",{outcome:a.failReason,max_bytes:t}),{success:!1,error:a.error,failReason:a.failReason};const d=await o(h,"_source_seed.bundle",u,{signal:f?.signal});return d.success?(i(`[gitBundle] Uploaded ${d.size} bytes as file_id ${d.fileId}`),s("tengu_ccr_bundle_upload",{outcome:"success",size_bytes:d.size,scope:a.scope,has_wip:b}),{success:!0,fileId:d.fileId,bundleSizeBytes:d.size,scope:a.scope,hasWip:b}):(s("tengu_ccr_bundle_upload",{outcome:"failed"}),{success:!1,error:d.error})}finally{try{await t(h)}catch{i(`[gitBundle] Could not delete ${h} (non-fatal)`)}for(const e of["refs/seed/stash","refs/seed/root"])await c(n(),["update-ref","-d",e],{cwd:p})}}
1
+ import{stat as e,unlink as r}from"fs/promises";import{logEvent as t}from"../../services/analytics/index.js";import{getFeatureValue_CACHED_MAY_BE_STALE as s}from"../../services/analytics/growthbook.js";import{uploadFile as o}from"../../services/api/filesApi.js";import{getCwd as i}from"../cwd.js";import{logForDebugging as a}from"../debug.js";import{execFileNoThrowWithCwd as c}from"../execFileNoThrow.js";import{findGitRoot as d,gitExe as n}from"../git.js";import{generateTempFilePath as l}from"../tempfile.js";export async function createAndUploadGitBundle(u,f){const p=f?.cwd??i(),g=d(p);if(!g)return{success:!1,error:"Not in a git repository"};for(const e of["refs/seed/stash","refs/seed/root"])await c(n(),["update-ref","-d",e],{cwd:g});const m=await c(n(),["for-each-ref","--count=1","refs/"],{cwd:g});if(0===m.code&&""===m.stdout.trim())return t("tengu_ccr_bundle_upload",{outcome:"empty_repo"}),{success:!1,error:"Repository has no commits yet",failReason:"empty_repo"};const w=await c(n(),["stash","create"],{cwd:g,abortSignal:f?.signal}),_=0===w.code?w.stdout.trim():"",b=""!==_;0!==w.code?a(`[gitBundle] git stash create failed (${w.code}), proceeding without WIP: ${w.stderr.slice(0,200)}`):b&&(a(`[gitBundle] Captured WIP as stash ${_}`),await c(n(),["update-ref","refs/seed/stash",_],{cwd:g}));const h=l("ccr-seed",".bundle");try{const r=s("tengu_ccr_bundle_max_bytes",null)??104857600,i=await async function(r,t,s,o,i){const d=o?["refs/seed/stash"]:[],mkBundle=e=>c(n(),["bundle","create",t,e,...d],{cwd:r,abortSignal:i}),l=await mkBundle("--all");if(0!==l.code)return{ok:!1,error:`git bundle create --all failed (${l.code}): ${l.stderr.slice(0,200)}`,failReason:"git_error"};const{size:u}=await e(t);if(u<=s)return{ok:!0,size:u,scope:"all"};a(`[gitBundle] --all bundle is ${(u/1024/1024).toFixed(1)}MB (> ${(s/1024/1024).toFixed(0)}MB), retrying HEAD-only`);const f=await mkBundle("HEAD");if(0!==f.code)return{ok:!1,error:`git bundle create HEAD failed (${f.code}): ${f.stderr.slice(0,200)}`,failReason:"git_error"};const{size:p}=await e(t);if(p<=s)return{ok:!0,size:p,scope:"head"};a(`[gitBundle] HEAD bundle is ${(p/1024/1024).toFixed(1)}MB, retrying squashed-root`);const g=o?"refs/seed/stash^{tree}":"HEAD^{tree}",m=await c(n(),["commit-tree",g,"-m","seed"],{cwd:r,abortSignal:i});if(0!==m.code)return{ok:!1,error:`git commit-tree failed (${m.code}): ${m.stderr.slice(0,200)}`,failReason:"git_error"};const w=m.stdout.trim();await c(n(),["update-ref","refs/seed/root",w],{cwd:r});const _=await c(n(),["bundle","create",t,"refs/seed/root"],{cwd:r,abortSignal:i});if(0!==_.code)return{ok:!1,error:`git bundle create refs/seed/root failed (${_.code}): ${_.stderr.slice(0,200)}`,failReason:"git_error"};const{size:b}=await e(t);return b<=s?{ok:!0,size:b,scope:"squashed"}:{ok:!1,error:"Repo is too large to bundle. Please setup GitHub on https://claude.ai/code",failReason:"too_large"}}(g,h,r,b,f?.signal);if(!i.ok)return a(`[gitBundle] ${i.error}`),t("tengu_ccr_bundle_upload",{outcome:i.failReason,max_bytes:r}),{success:!1,error:i.error,failReason:i.failReason};const d=await o(h,"_source_seed.bundle",u,{signal:f?.signal});return d.success?(a(`[gitBundle] Uploaded ${d.size} bytes as file_id ${d.fileId}`),t("tengu_ccr_bundle_upload",{outcome:"success",size_bytes:d.size,scope:i.scope,has_wip:b}),{success:!0,fileId:d.fileId,bundleSizeBytes:d.size,scope:i.scope,hasWip:b}):(t("tengu_ccr_bundle_upload",{outcome:"failed"}),{success:!1,error:d.error})}finally{try{await r(h)}catch{a(`[gitBundle] Could not delete ${h} (non-fatal)`)}for(const e of["refs/seed/stash","refs/seed/root"])await c(n(),["update-ref","-d",e],{cwd:g})}}
@@ -1 +1 @@
1
- import{jsx as e}from"react/jsx-runtime";import t from"axios";import o from"chalk";import{randomUUID as r}from"crypto";import{getOriginalCwd as s,getSessionId as n}from"src/bootstrap/state.js";import{checkGate_CACHED_OR_BLOCKING as i}from"src/services/analytics/growthbook.js";import{logEvent as a}from"src/services/analytics/index.js";import{isPolicyAllowed as c}from"src/services/policyLimits/index.js";import{z as l}from"zod/v4";import{getTeleportErrors as u,TeleportError as d}from"../components/TeleportError.js";import{getOauthConfig as p}from"../constants/oauth.js";import{KeybindingSetup as m}from"../keybindings/KeybindingProviderSetup.js";import{queryHaiku as h}from"../services/api/claude.js";import{getSessionLogsViaOAuth as f,getTeleportEvents as g}from"../services/api/sessionIngress.js";import{getOrganizationUUID as _}from"../services/oauth/client.js";import{AppStateProvider as w}from"../state/AppState.js";import{checkAndRefreshOAuthTokenIfNeeded as b,getClaudeAIOAuthTokens as y}from"./auth.js";import{checkGithubAppInstalled as $}from"./background/remote/preconditions.js";import{deserializeMessages as v}from"./conversationRecovery.js";import{getCwd as E}from"./cwd.js";import{logForDebugging as k}from"./debug.js";import{detectCurrentRepositoryWithHost as S,parseGitHubRepository as R,parseGitRemote as j}from"./detectRepository.js";import{isEnvTruthy as x}from"./envUtils.js";import{TeleportOperationError as T,toError as A}from"./errors.js";import{execFileNoThrow as I}from"./execFileNoThrow.js";import{truncateToWidth as C}from"./format.js";import{findGitRoot as B,getDefaultBranch as P,getIsClean as U,gitExe as N}from"./git.js";import{safeParseJSON as D}from"./json.js";import{logError as L}from"./log.js";import{createSystemMessage as O,createUserMessage as F}from"./messages.js";import{getMainLoopModel as H}from"./model/model.js";import{isTranscriptMessage as M}from"./sessionStorage.js";import{getSettings_DEPRECATED as z}from"./settings/settings.js";import{jsonStringify as G}from"./slowOperations.js";import{asSystemPrompt as q}from"./systemPromptType.js";import{fetchSession as Y,getBranchFromSession as W,getOAuthHeaders as K}from"./teleport/api.js";import{fetchEnvironments as J}from"./teleport/environments.js";import{createAndUploadGitBundle as V}from"./teleport/gitBundle.js";function createTeleportResumeSystemMessage(e){if(null===e)return O("Session resumed","suggestion");const t=e instanceof T?e.formattedMessage:e.message;return O(`Session resumed without branch: ${t}`,"warning")}export async function validateGitState(){if(!await U({ignoreUntracked:!0}))throw a("tengu_teleport_error_git_not_clean",{}),new T("Git working directory is not clean. Please commit or stash your changes before using --teleport.",o.red("Error: Git working directory is not clean. Please commit or stash your changes before using --teleport.\n"))}async function getCurrentBranch(){const{stdout:e}=await I(N(),["branch","--show-current"]);return e.trim()}export function processMessagesForTeleportResume(e,t){return[...v(e),F({content:`This session is being continued from another machine. Application state may have changed. The updated working directory is ${s()}`,isMeta:!0}),createTeleportResumeSystemMessage(t)]}export async function checkOutTeleportedSessionBranch(e){try{const t=await getCurrentBranch();if(k(`Current branch before teleport: '${t}'`),e){k(`Switching to branch '${e}'...`),await async function(e){const t=e?["fetch","origin",`${e}:${e}`]:["fetch","origin"],{code:o,stderr:r}=await I(N(),t);if(0!==o)if(e&&r.includes("refspec")){k(`Specific branch fetch failed, trying to fetch ref: ${e}`);const{code:t,stderr:o}=await I(N(),["fetch","origin",e]);0!==t&&L(new Error(`Failed to fetch from remote origin: ${o}`))}else L(new Error(`Failed to fetch from remote origin: ${r}`))}(e),await async function(e){let{code:t,stderr:r}=await I(N(),["checkout",e]);if(0!==t){k(`Local checkout failed, trying to checkout from origin: ${r}`);const o=await I(N(),["checkout","-b",e,"--track",`origin/${e}`]);if(t=o.code,r=o.stderr,0!==t){k(`Remote checkout with -b failed, trying without -b: ${r}`);const o=await I(N(),["checkout","--track",`origin/${e}`]);t=o.code,r=o.stderr}}if(0!==t)throw a("tengu_teleport_error_branch_checkout_failed",{}),new T(`Failed to checkout branch '${e}': ${r}`,o.red(`Failed to checkout branch '${e}'\n`));await async function(e){const{code:t}=await I(N(),["rev-parse","--abbrev-ref",`${e}@{upstream}`]);if(0===t)return void k(`Branch '${e}' already has upstream set`);const{code:o}=await I(N(),["rev-parse","--verify",`origin/${e}`]);if(0===o){k(`Setting upstream for '${e}' to 'origin/${e}'`);const{code:t,stderr:o}=await I(N(),["branch","--set-upstream-to",`origin/${e}`,e]);k(0!==t?`Failed to set upstream for '${e}': ${o}`:`Successfully set upstream for '${e}'`)}else k(`Remote branch 'origin/${e}' does not exist, skipping upstream setup`)}(e)}(e);const t=await getCurrentBranch();k(`Branch after checkout: '${t}'`)}else k("No branch specified, staying on current branch");return{branchName:await getCurrentBranch(),branchError:null}}catch(e){return{branchName:await getCurrentBranch(),branchError:A(e)}}}export async function validateSessionRepository(e){const t=await S(),o=t?`${t.owner}/${t.name}`:null,r=e.session_context.sources.find(e=>"git_repository"===e.type);if(!r?.url)return k(o?"Session has no associated repository, proceeding without validation":"Session has no repo requirement and not in git directory, proceeding"),{status:"no_repo_required"};const s=j(r.url),n=s?`${s.owner}/${s.name}`:R(r.url);if(!n)return{status:"no_repo_required"};if(k(`Session is for repository: ${n}, current repo: ${o??"none"}`),!o)return{status:"not_in_repo",sessionRepo:n,sessionHost:s?.host,currentRepo:null};const stripPort=e=>e.replace(/:\d+$/,""),i=o.toLowerCase()===n.toLowerCase(),a=!t||!s||stripPort(t.host.toLowerCase())===stripPort(s.host.toLowerCase());return i&&a?{status:"match",sessionRepo:n,currentRepo:o}:{status:"mismatch",sessionRepo:n,currentRepo:o,sessionHost:s?.host,currentHost:t?.host}}export async function teleportResumeCodeSession(e,t){if(!c("allow_remote_sessions"))throw new Error("Remote sessions are disabled by your organization's policy.");k(`Resuming code session ID: ${e}`);try{const r=y()?.accessToken;if(!r)throw a("tengu_teleport_resume_error",{error_type:"no_access_token"}),new Error("Las sesiones web de Context Code requieren autenticación con una cuenta Context. La autenticación por API key no es suficiente. Ejecuta /login para autenticarte, o verifica tu estado con /status.");const s=await _();if(!s)throw a("tengu_teleport_resume_error",{error_type:"no_org_uuid"}),new Error("No se pudo obtener el UUID de la organización para construir la URL de sesión");t?.("validating");const n=await Y(e),i=await validateSessionRepository(n);switch(i.status){case"match":case"no_repo_required":break;case"not_in_repo":{a("tengu_teleport_error_repo_not_in_git_dir_sessions_api",{sessionId:e});const t=i.sessionHost&&"github.com"!==i.sessionHost.toLowerCase()?`${i.sessionHost}/${i.sessionRepo}`:i.sessionRepo;throw new T(`You must run claude --teleport ${e} from a checkout of ${t}.`,o.red(`You must run claude --teleport ${e} from a checkout of ${o.bold(t)}.\n`))}case"mismatch":{a("tengu_teleport_error_repo_mismatch_sessions_api",{sessionId:e});const t=i.sessionHost&&i.currentHost&&i.sessionHost.replace(/:\d+$/,"").toLowerCase()!==i.currentHost.replace(/:\d+$/,"").toLowerCase(),r=t?`${i.sessionHost}/${i.sessionRepo}`:i.sessionRepo,s=t?`${i.currentHost}/${i.currentRepo}`:i.currentRepo;throw new T(`You must run claude --teleport ${e} from a checkout of ${r}.\nThis repo is ${s}.`,o.red(`You must run claude --teleport ${e} from a checkout of ${o.bold(r)}.\nThis repo is ${o.bold(s)}.\n`))}case"error":throw new T(i.errorMessage||"Failed to validate session repository",o.red(`Error: ${i.errorMessage||"Failed to validate session repository"}\n`));default:{const e=i.status;throw new Error(`Unhandled repo validation status: ${e}`)}}return await teleportFromSessionsAPI(e,s,r,t,n)}catch(e){if(e instanceof T)throw e;const t=A(e);throw L(t),a("tengu_teleport_resume_error",{error_type:"resume_session_id_catch"}),new T(t.message,o.red(`Error: ${t.message}\n`))}}export async function teleportToRemoteWithErrorHandling(t,o,r,s){const n=new Set(["needsGitStash"]);return await async function(t,o){const r=await u();r.size>0&&(a("tengu_teleport_errors_detected",{error_types:Array.from(r).join(","),errors_ignored:Array.from(o||[]).join(",")}),await new Promise(s=>{t.render(e(w,{children:e(m,{children:e(d,{errorsToIgnore:o,onComplete:()=>{a("tengu_teleport_errors_resolved",{error_types:Array.from(r).join(",")}),s()}})})}))}))}(t,n),teleportToRemote({initialMessage:o,signal:r,branchName:s,onBundleFail:e=>process.stderr.write(`\n${e}\n`)})}export async function teleportFromSessionsAPI(e,r,s,n,i){const c=Date.now();try{k(`[teleport] Starting fetch for session: ${e}`),n?.("fetching_logs");const t=Date.now();let o=await g(e,s,r);if(null===o&&(k("[teleport] v2 endpoint returned null, trying session-ingress"),o=await f(e,s,r)),k(`[teleport] Session logs fetched in ${Date.now()-t}ms`),null===o)throw new Error("Error al obtener los registros de sesión");const a=Date.now(),l=o.filter(e=>M(e)&&!e.isSidechain);k(`[teleport] Filtered ${o.length} entries to ${l.length} messages in ${Date.now()-a}ms`),n?.("fetching_branch");const u=i?W(i):void 0;return u&&k(`[teleport] Found branch: ${u}`),k(`[teleport] Total teleportFromSessionsAPI time: ${Date.now()-c}ms`),{log:l,branch:u}}catch(r){const s=A(r);if(t.isAxiosError(r)&&404===r.response?.status)throw a("tengu_teleport_error_session_not_found_404",{sessionId:e}),new T(`${e} no encontrada.`,`${e} no encontrada.\n${o.dim("Ejecuta /status en Context Code para verificar tu cuenta.")}`);throw L(s),new Error(`Error al obtener la sesión desde la Sessions API: ${s.message}`)}}export async function pollRemoteSessionEvents(e,o=null,r){const s=y()?.accessToken;if(!s)throw new Error("Sin token de acceso para polling");const n=await _();if(!n)throw new Error("Sin UUID de organización para polling");const i={...K(s),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":n},a=`${p().BASE_API_URL}/v1/sessions/${e}/events`,c=[];let l,u,d=o;for(let e=0;e<50;e++){const e=await t.get(a,{headers:i,params:d?{after_id:d}:void 0,timeout:3e4});if(200!==e.status)throw new Error(`Error al obtener eventos de sesión: ${e.statusText}`);const o=e.data;if(!o?.data||!Array.isArray(o.data))throw new Error("Respuesta de eventos inválida");for(const e of o.data)if(e&&"object"==typeof e&&"type"in e){if("env_manager_log"===e.type||"control_response"===e.type)continue;"session_id"in e&&c.push(e)}if(!o.last_id)break;if(d=o.last_id,!o.has_more)break}if(r?.skipMetadata)return{newEvents:c,lastEventId:d};try{const t=await Y(e);l=W(t),u=t.session_status}catch(t){k(`teleport: failed to fetch session ${e} metadata: ${t}`,{level:"debug"})}return{newEvents:c,lastEventId:d,branch:l,sessionStatus:u}}export async function teleportToRemote(e){const{initialMessage:o,signal:s}=e;try{await b();const c=y()?.accessToken;if(!c)return L(new Error("No access token found for remote session creation")),null;const u=await _();if(!u)return L(new Error("Unable to get organization UUID for remote session creation")),null;if(e.environmentId){const o=`${p().BASE_API_URL}/v1/sessions`,r={...K(c),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":u},i={CLAUDE_CODE_OAUTH_TOKEN:c,...e.environmentVariables??{}};let l=null,d=null;if(e.useBundle){const e=await V({oauthToken:c,sessionId:n(),baseUrl:p().BASE_API_URL},{signal:s});if(!1===e.success)return L(new Error(`Bundle upload failed: ${e.error}`)),null;d=e.fileId,a("tengu_teleport_bundle_mode",{size_bytes:e.bundleSizeBytes,scope:e.scope,has_wip:e.hasWip,reason:"explicit_env_bundle"})}else{const t=await S();t&&(l={type:"git_repository",url:`https://${t.host}/${t.owner}/${t.name}`,revision:e.branchName})}const m={title:e.title||e.description||"Remote task",events:[],session_context:{sources:l?[l]:[],...d&&{seed_bundle_file_id:d},outcomes:[],environment_variables:i},environment_id:e.environmentId};k(`[teleportToRemote] explicit env ${e.environmentId}, ${Object.keys(i).length} env vars, ${d?`bundle=${d}`:`source=${l?.url??"none"}@${e.branchName??"default"}`}`);const h=await t.post(o,m,{headers:r,signal:s});if(200!==h.status&&201!==h.status)return L(new Error(`CreateSession ${h.status}: ${G(h.data)}`)),null;const f=h.data;return f&&"string"==typeof f.id?{id:f.id,title:f.title||m.title}:(L(new Error(`No session id in response: ${G(h.data)}`)),null)}let d=null,m=null,f=null;const g=await S();let w,v;if(e.title&&e.reuseOutcomeBranch)w=e.title,v=e.reuseOutcomeBranch;else{const t=await async function(e,t){const o=C(e,75),r="context/task";try{const s='You are coming up with a succinct title and git branch name for a coding session based on the provided description. The title should be clear, concise, and accurately reflect the content of the coding task.\nYou should keep it short and simple, ideally no more than 6 words. Avoid using jargon or overly technical terms unless absolutely necessary. The title should be easy to understand for anyone reading it.\nUse sentence case for the title (capitalize only the first word and proper nouns), not Title Case.\n\nThe branch name should be clear, concise, and accurately reflect the content of the coding task.\nYou should keep it short and simple, ideally no more than 4 words. The branch should always start with "context/" and should be all lower case, with words separated by dashes.\n\nReturn a JSON object with "title" and "branch" fields.\n\nExample 1: {"title": "Fix login button not working on mobile", "branch": "context/fix-mobile-login-button"}\nExample 2: {"title": "Update README with installation instructions", "branch": "context/update-readme"}\nExample 3: {"title": "Improve performance of data processing script", "branch": "context/improve-data-processing"}\n\nHere is the session description:\n<description>{description}</description>\nPlease generate a title and branch name for this session.'.replace("{description}",e),n=(await h({systemPrompt:q([]),userPrompt:s,outputFormat:{type:"json_schema",schema:{type:"object",properties:{title:{type:"string"},branch:{type:"string"}},required:["title","branch"],additionalProperties:!1}},signal:t,options:{querySource:"teleport_generate_title",agents:[],isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,mcpTools:[]}})).message.content[0];if("text"!==n?.type)return{title:o,branchName:r};const i=D(n.text.trim()),a=l.object({title:l.string(),branch:l.string()}).safeParse(i);return a.success?{title:a.data.title||o,branchName:a.data.branch||r}:{title:o,branchName:r}}catch(e){return L(new Error(`Error generating title and branch: ${e}`)),{title:o,branchName:r}}}(e.description||o||"Background task",s);w=e.title||t.title,v=e.reuseOutcomeBranch||t.branchName}let R=!1,j="no_git_at_all";const T=B(E()),A=!e.skipBundle&&x(process.env.CCR_FORCE_BUNDLE),I=!e.skipBundle&&null!==T&&(x(process.env.CCR_ENABLE_BUNDLE)||await i("tengu_ccr_bundle_seed_enabled"));if(g&&!A?"github.com"===g.host?(R=await $(g.owner,g.name,s),j=R?"github_preflight_ok":"github_preflight_failed"):(R=!0,j="ghes_optimistic"):A?j="forced_bundle":T&&(j="no_github_remote"),R||I||!g||(R=!0),R&&g){const{host:t,owner:o,name:r}=g,s=e.branchName??await P()??void 0;k(`[teleportToRemote] Git source: ${t}/${o}/${r}, revision: ${s??"none"}`),d={type:"git_repository",url:`https://${t}/${o}/${r}`,revision:s,...e.reuseOutcomeBranch&&{allow_unrestricted_git_push:!0}},m={type:"git_repository",git_info:{type:"github",repo:`${o}/${r}`,branches:[v]}}}if(!d&&I){k(`[teleportToRemote] Bundling (reason: ${j})`);const t=await V({oauthToken:c,sessionId:n(),baseUrl:p().BASE_API_URL},{signal:s});if(!1===t.success){const o=t.error,r=t.failReason;L(new Error(`Bundle upload failed: ${o}`));const s=g?". Please setup GitHub on https://claude.ai/code":"";let n;switch(r){case"empty_repo":n='Repository has no commits — run `git add . && git commit -m "initial"` then retry';break;case"too_large":n=`Repo is too large to teleport${s}`;break;case"git_error":n=`Failed to create git bundle (${o})${s}`;break;default:n=`Bundle upload failed: ${o}${s}`}return e.onBundleFail?.(n),null}f=t.fileId,a("tengu_teleport_bundle_mode",{size_bytes:t.bundleSizeBytes,scope:t.scope,has_wip:t.hasWip,reason:j})}a("tengu_teleport_source_decision",{reason:j,path:d?"github":f?"bundle":"empty"}),d||f||k("[teleportToRemote] No repository detected — session will have an empty sandbox");let U=await J();if(!U||0===U.length)return L(new Error("No environments available for session creation")),null;k(`Available environments: ${U.map(e=>`${e.environment_id} (${e.name}, ${e.kind})`).join(", ")}`);const N=z(),O=e.useDefaultEnvironment?void 0:N?.remote?.defaultEnvironmentId;let F=U.find(e=>"anthropic_cloud"===e.kind);if(e.useDefaultEnvironment&&!F){k(`No anthropic_cloud in env list (${U.length} envs); retrying fetchEnvironments`);const e=await J();if(F=e?.find(e=>"anthropic_cloud"===e.kind),!F)return L(new Error(`No anthropic_cloud environment available after retry (got: ${(e??U).map(e=>`${e.name} (${e.kind})`).join(", ")}). Silent byoc fallthrough would launch into a dead env — fail fast instead.`)),null;e&&(U=e)}const M=O&&U.find(e=>e.environment_id===O)||F||U.find(e=>"bridge"!==e.kind)||U[0];if(!M)return L(new Error("No environments available for session creation")),null;if(O){const e=M.environment_id===O;k(e?`Using configured default environment: ${O}`:`Configured default environment ${O} not found, using first available`)}const Y=M.environment_id;k(`Selected environment: ${Y} (${M.name}, ${M.kind})`);const W=`${p().BASE_API_URL}/v1/sessions`,Q={...K(c),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":u},X={sources:d?[d]:[],...f&&{seed_bundle_file_id:f},outcomes:m?[m]:[],model:e.model??H(),...e.reuseOutcomeBranch&&{reuse_outcome_branches:!0},...e.githubPr&&{github_pr:e.githubPr}},Z=[];e.permissionMode&&Z.push({type:"event",data:{type:"control_request",request_id:`set-mode-${r()}`,request:{subtype:"set_permission_mode",mode:e.permissionMode,ultraplan:e.ultraplan}}}),o&&Z.push({type:"event",data:{uuid:r(),session_id:"",type:"user",parent_tool_use_id:null,message:{role:"user",content:o}}});const ee={title:e.ultraplan?`ultraplan: ${w}`:w,events:Z,session_context:X,environment_id:Y};k(`Creating session with payload: ${G(ee,null,2)}`);const te=await t.post(W,ee,{headers:Q,signal:s});if(200!==te.status&&201!==te.status)return L(new Error(`API request failed with status ${te.status}: ${te.statusText}\n\nResponse data: ${G(te.data,null,2)}`)),null;const oe=te.data;return oe&&"string"==typeof oe.id?(k(`Successfully created remote session: ${oe.id}`),{id:oe.id,title:oe.title||ee.title}):(L(new Error(`Cannot determine session ID from API response: ${G(te.data)}`)),null)}catch(e){const t=A(e);return L(t),null}}export async function archiveRemoteSession(e){const o=y()?.accessToken;if(!o)return;const r=await _();if(!r)return;const s={...K(o),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":r},n=`${p().BASE_API_URL}/v1/sessions/${e}/archive`;try{const o=await t.post(n,{},{headers:s,timeout:1e4,validateStatus:e=>e<500});200===o.status||409===o.status?k(`[archiveRemoteSession] archived ${e}`):k(`[archiveRemoteSession] ${e} failed ${o.status}: ${G(o.data)}`)}catch(e){L(e)}}
1
+ import{jsx as e}from"react/jsx-runtime";import t from"axios";import o from"chalk";import{randomUUID as r}from"crypto";import{getOriginalCwd as n,getSessionId as s}from"../bootstrap/state.js";import{checkGate_CACHED_OR_BLOCKING as i}from"../services/analytics/growthbook.js";import{logEvent as a}from"../services/analytics/index.js";import{isPolicyAllowed as c}from"../services/policyLimits/index.js";import{z as l}from"zod/v4";import{getTeleportErrors as u,TeleportError as d}from"../components/TeleportError.js";import{getOauthConfig as p}from"../constants/oauth.js";import{KeybindingSetup as m}from"../keybindings/KeybindingProviderSetup.js";import{queryHaiku as h}from"../services/api/claude.js";import{getSessionLogsViaOAuth as f,getTeleportEvents as g}from"../services/api/sessionIngress.js";import{getOrganizationUUID as _}from"../services/oauth/client.js";import{AppStateProvider as w}from"../state/AppState.js";import{checkAndRefreshOAuthTokenIfNeeded as b,getClaudeAIOAuthTokens as $}from"./auth.js";import{checkGithubAppInstalled as y}from"./background/remote/preconditions.js";import{deserializeMessages as v}from"./conversationRecovery.js";import{getCwd as E}from"./cwd.js";import{logForDebugging as k}from"./debug.js";import{detectCurrentRepositoryWithHost as R,parseGitHubRepository as S,parseGitRemote as j}from"./detectRepository.js";import{isEnvTruthy as x}from"./envUtils.js";import{TeleportOperationError as B,toError as T}from"./errors.js";import{execFileNoThrow as I}from"./execFileNoThrow.js";import{truncateToWidth as A}from"./format.js";import{findGitRoot as C,getDefaultBranch as N,getIsClean as P,gitExe as U}from"./git.js";import{safeParseJSON as L}from"./json.js";import{logError as F}from"./log.js";import{createSystemMessage as D,createUserMessage as H}from"./messages.js";import{getMainLoopModel as z}from"./model/model.js";import{isTranscriptMessage as M}from"./sessionStorage.js";import{getSettings_DEPRECATED as O}from"./settings/settings.js";import{jsonStringify as q}from"./slowOperations.js";import{asSystemPrompt as Y}from"./systemPromptType.js";import{fetchSession as G,getBranchFromSession as W,getOAuthHeaders as K}from"./teleport/api.js";import{fetchEnvironments as J}from"./teleport/environments.js";import{createAndUploadGitBundle as V}from"./teleport/gitBundle.js";function createTeleportResumeSystemMessage(e){if(null===e)return D("Session resumed","suggestion");const t=e instanceof B?e.formattedMessage:e.message;return D(`Session resumed without branch: ${t}`,"warning")}const Q='You are coming up with a succinct title and git branch name for a coding session based on the provided description. The title should be clear, concise, and accurately reflect the content of the coding task.\nYou should keep it short and simple, ideally no more than 6 words. Avoid using jargon or overly technical terms unless absolutely necessary. The title should be easy to understand for anyone reading it.\nUse sentence case for the title (capitalize only the first word and proper nouns), not Title Case.\n\nThe branch name should be clear, concise, and accurately reflect the content of the coding task.\nYou should keep it short and simple, ideally no more than 4 words. The branch should always start with "context/" and should be all lower case, with words separated by dashes.\n\nReturn a JSON object with "title" and "branch" fields.\n\nExample 1: {"title": "Fix login button not working on mobile", "branch": "context/fix-mobile-login-button"}\nExample 2: {"title": "Update README with installation instructions", "branch": "context/update-readme"}\nExample 3: {"title": "Improve performance of data processing script", "branch": "context/improve-data-processing"}\n\nHere is the session description:\n<description>{description}</description>\nPlease generate a title and branch name for this session.';export async function validateGitState(){if(!await P({ignoreUntracked:!0})){a("tengu_teleport_error_git_not_clean",{});throw new B("Git working directory is not clean. Please commit or stash your changes before using --teleport.",o.red("Error: Git working directory is not clean. Please commit or stash your changes before using --teleport.\n"))}}async function checkoutBranch(e){let{code:t,stderr:r}=await I(U(),["checkout",e]);if(0!==t){k(`Local checkout failed, trying to checkout from origin: ${r}`);const o=await I(U(),["checkout","-b",e,"--track",`origin/${e}`]);if(t=o.code,r=o.stderr,0!==t){k(`Remote checkout with -b failed, trying without -b: ${r}`);const o=await I(U(),["checkout","--track",`origin/${e}`]);t=o.code,r=o.stderr}}if(0!==t)throw a("tengu_teleport_error_branch_checkout_failed",{}),new B(`Failed to checkout branch '${e}': ${r}`,o.red(`Failed to checkout branch '${e}'\n`));await async function(e){const{code:t}=await I(U(),["rev-parse","--abbrev-ref",`${e}@{upstream}`]);if(0===t)return void k(`Branch '${e}' already has upstream set`);const{code:o}=await I(U(),["rev-parse","--verify",`origin/${e}`]);if(0===o){k(`Setting upstream for '${e}' to 'origin/${e}'`);const{code:t,stderr:o}=await I(U(),["branch","--set-upstream-to",`origin/${e}`,e]);k(0!==t?`Failed to set upstream for '${e}': ${o}`:`Successfully set upstream for '${e}'`)}else k(`Remote branch 'origin/${e}' does not exist, skipping upstream setup`)}(e)}async function getCurrentBranch(){const{stdout:e}=await I(U(),["branch","--show-current"]);return e.trim()}export function processMessagesForTeleportResume(e,t){return[...v(e),H({content:`This session is being continued from another machine. Application state may have changed. The updated working directory is ${n()}`,isMeta:!0}),createTeleportResumeSystemMessage(t)]}export async function checkOutTeleportedSessionBranch(e){try{const t=await getCurrentBranch();if(k(`Current branch before teleport: '${t}'`),e){k(`Switching to branch '${e}'...`),await async function(e){const t=e?["fetch","origin",`${e}:${e}`]:["fetch","origin"],{code:o,stderr:r}=await I(U(),t);if(0!==o)if(e&&r.includes("refspec")){k(`Specific branch fetch failed, trying to fetch ref: ${e}`);const{code:t,stderr:o}=await I(U(),["fetch","origin",e]);0!==t&&F(new Error(`Failed to fetch from remote origin: ${o}`))}else F(new Error(`Failed to fetch from remote origin: ${r}`))}(e),await checkoutBranch(e);const t=await getCurrentBranch();k(`Branch after checkout: '${t}'`)}else k("No branch specified, staying on current branch");return{branchName:await getCurrentBranch(),branchError:null}}catch(e){return{branchName:await getCurrentBranch(),branchError:T(e)}}}export async function validateSessionRepository(e){const t=await R(),o=t?`${t.owner}/${t.name}`:null,r=e.session_context.sources.find(e=>"git_repository"===e.type);if(!r?.url)return k(o?"Session has no associated repository, proceeding without validation":"Session has no repo requirement and not in git directory, proceeding"),{status:"no_repo_required"};const n=j(r.url),s=n?`${n.owner}/${n.name}`:S(r.url);if(!s)return{status:"no_repo_required"};if(k(`Session is for repository: ${s}, current repo: ${o??"none"}`),!o)return{status:"not_in_repo",sessionRepo:s,sessionHost:n?.host,currentRepo:null};const stripPort=e=>e.replace(/:\d+$/,""),i=o.toLowerCase()===s.toLowerCase(),a=!t||!n||stripPort(t.host.toLowerCase())===stripPort(n.host.toLowerCase());return i&&a?{status:"match",sessionRepo:s,currentRepo:o}:{status:"mismatch",sessionRepo:s,currentRepo:o,sessionHost:n?.host,currentHost:t?.host}}export async function teleportResumeCodeSession(e,t){if(!c("allow_remote_sessions"))throw new Error("Remote sessions are disabled by your organization's policy.");k(`Resuming code session ID: ${e}`);try{const r=$()?.accessToken;if(!r)throw a("tengu_teleport_resume_error",{error_type:"no_access_token"}),new Error("Las sesiones web de Context Code requieren autenticación con una cuenta Context. La autenticación por API key no es suficiente. Ejecuta /login para autenticarte, o verifica tu estado con /status.");const n=await _();if(!n)throw a("tengu_teleport_resume_error",{error_type:"no_org_uuid"}),new Error("No se pudo obtener el UUID de la organización para construir la URL de sesión");t?.("validating");const s=await G(e),i=await validateSessionRepository(s);switch(i.status){case"match":case"no_repo_required":break;case"not_in_repo":{a("tengu_teleport_error_repo_not_in_git_dir_sessions_api",{sessionId:e});const t=i.sessionHost&&"github.com"!==i.sessionHost.toLowerCase()?`${i.sessionHost}/${i.sessionRepo}`:i.sessionRepo;throw new B(`You must run claude --teleport ${e} from a checkout of ${t}.`,o.red(`You must run claude --teleport ${e} from a checkout of ${o.bold(t)}.\n`))}case"mismatch":{a("tengu_teleport_error_repo_mismatch_sessions_api",{sessionId:e});const t=i.sessionHost&&i.currentHost&&i.sessionHost.replace(/:\d+$/,"").toLowerCase()!==i.currentHost.replace(/:\d+$/,"").toLowerCase(),r=t?`${i.sessionHost}/${i.sessionRepo}`:i.sessionRepo,n=t?`${i.currentHost}/${i.currentRepo}`:i.currentRepo;throw new B(`You must run claude --teleport ${e} from a checkout of ${r}.\nThis repo is ${n}.`,o.red(`You must run claude --teleport ${e} from a checkout of ${o.bold(r)}.\nThis repo is ${o.bold(n)}.\n`))}case"error":throw new B(i.errorMessage||"Failed to validate session repository",o.red(`Error: ${i.errorMessage||"Failed to validate session repository"}\n`));default:{const e=i.status;throw new Error(`Unhandled repo validation status: ${e}`)}}return await teleportFromSessionsAPI(e,n,r,t,s)}catch(e){if(e instanceof B)throw e;const t=T(e);throw F(t),a("tengu_teleport_resume_error",{error_type:"resume_session_id_catch"}),new B(t.message,o.red(`Error: ${t.message}\n`))}}export async function teleportToRemoteWithErrorHandling(t,o,r,n){const s=new Set(["needsGitStash"]);return await async function(t,o){const r=await u();r.size>0&&(a("tengu_teleport_errors_detected",{error_types:Array.from(r).join(","),errors_ignored:Array.from(o||[]).join(",")}),await new Promise(n=>{t.render(e(w,{children:e(m,{children:e(d,{errorsToIgnore:o,onComplete:()=>{a("tengu_teleport_errors_resolved",{error_types:Array.from(r).join(",")}),n()}})})}))}))}(t,s),teleportToRemote({initialMessage:o,signal:r,branchName:n,onBundleFail:e=>process.stderr.write(`\n${e}\n`)})}export async function teleportFromSessionsAPI(e,r,n,s,i){const c=Date.now();try{k(`[teleport] Starting fetch for session: ${e}`),s?.("fetching_logs");const t=Date.now();let o=await g(e,n,r);if(null===o&&(k("[teleport] v2 endpoint returned null, trying session-ingress"),o=await f(e,n,r)),k(`[teleport] Session logs fetched in ${Date.now()-t}ms`),null===o)throw new Error("Error al obtener los registros de sesión");const a=Date.now(),l=o.filter(e=>M(e)&&!e.isSidechain);k(`[teleport] Filtered ${o.length} entries to ${l.length} messages in ${Date.now()-a}ms`),s?.("fetching_branch");const u=i?W(i):void 0;return u&&k(`[teleport] Found branch: ${u}`),k(`[teleport] Total teleportFromSessionsAPI time: ${Date.now()-c}ms`),{log:l,branch:u}}catch(r){const n=T(r);if(t.isAxiosError(r)&&404===r.response?.status)throw a("tengu_teleport_error_session_not_found_404",{sessionId:e}),new B(`${e} no encontrada.`,`${e} no encontrada.\n${o.dim("Ejecuta /status en Context Code para verificar tu cuenta.")}`);throw F(n),new Error(`Error al obtener la sesión desde la Sessions API: ${n.message}`)}}export async function pollRemoteSessionEvents(e,o=null,r){const n=$()?.accessToken;if(!n)throw new Error("Sin token de acceso para polling");const s=await _();if(!s)throw new Error("Sin UUID de organización para polling");const i={...K(n),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":s},a=`${p().BASE_API_URL}/v1/sessions/${e}/events`,c=[];let l,u,d=o;for(let e=0;e<50;e++){const e=await t.get(a,{headers:i,params:d?{after_id:d}:void 0,timeout:3e4});if(200!==e.status)throw new Error(`Error al obtener eventos de sesión: ${e.statusText}`);const o=e.data;if(!o?.data||!Array.isArray(o.data))throw new Error("Respuesta de eventos inválida");for(const e of o.data)if(e&&"object"==typeof e&&"type"in e){if("env_manager_log"===e.type||"control_response"===e.type)continue;"session_id"in e&&c.push(e)}if(!o.last_id)break;if(d=o.last_id,!o.has_more)break}if(r?.skipMetadata)return{newEvents:c,lastEventId:d};try{const t=await G(e);l=W(t),u=t.session_status}catch(t){k(`teleport: failed to fetch session ${e} metadata: ${t}`,{level:"debug"})}return{newEvents:c,lastEventId:d,branch:l,sessionStatus:u}}export async function teleportToRemote(e){const{initialMessage:o,signal:n}=e;try{await b();const c=$()?.accessToken;if(!c)return F(new Error("No access token found for remote session creation")),null;const u=await _();if(!u)return F(new Error("Unable to get organization UUID for remote session creation")),null;if(e.environmentId){const o=`${p().BASE_API_URL}/v1/sessions`,r={...K(c),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":u},i={CLAUDE_CODE_OAUTH_TOKEN:c,...e.environmentVariables??{}};let l=null,d=null;if(e.useBundle){const e=await V({oauthToken:c,sessionId:s(),baseUrl:p().BASE_API_URL},{signal:n});if(!1===e.success)return F(new Error(`Bundle upload failed: ${e.error}`)),null;d=e.fileId,a("tengu_teleport_bundle_mode",{size_bytes:e.bundleSizeBytes,scope:e.scope,has_wip:e.hasWip,reason:"explicit_env_bundle"})}else{const t=await R();t&&(l={type:"git_repository",url:`https://${t.host}/${t.owner}/${t.name}`,revision:e.branchName})}const m={title:e.title||e.description||"Remote task",events:[],session_context:{sources:l?[l]:[],...d&&{seed_bundle_file_id:d},outcomes:[],environment_variables:i},environment_id:e.environmentId};k(`[teleportToRemote] explicit env ${e.environmentId}, ${Object.keys(i).length} env vars, ${d?`bundle=${d}`:`source=${l?.url??"none"}@${e.branchName??"default"}`}`);const h=await t.post(o,m,{headers:r,signal:n});if(200!==h.status&&201!==h.status)return F(new Error(`CreateSession ${h.status}: ${q(h.data)}`)),null;const f=h.data;return f&&"string"==typeof f.id?{id:f.id,title:f.title||m.title}:(F(new Error(`No session id in response: ${q(h.data)}`)),null)}let d=null,m=null,f=null;const g=await R();let w,v;if(e.title&&e.reuseOutcomeBranch)w=e.title,v=e.reuseOutcomeBranch;else{const t=await async function(e,t){const o=A(e,75),r="context/task";try{const n=Q.replace("{description}",e),s=(await h({systemPrompt:Y([]),userPrompt:n,outputFormat:{type:"json_schema",schema:{type:"object",properties:{title:{type:"string"},branch:{type:"string"}},required:["title","branch"],additionalProperties:!1}},signal:t,options:{querySource:"teleport_generate_title",agents:[],isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,mcpTools:[]}})).message.content[0];if("text"!==s?.type)return{title:o,branchName:r};const i=L(s.text.trim()),a=l.object({title:l.string(),branch:l.string()}).safeParse(i);return a.success?{title:a.data.title||o,branchName:a.data.branch||r}:{title:o,branchName:r}}catch(e){return F(new Error(`Error generating title and branch: ${e}`)),{title:o,branchName:r}}}(e.description||o||"Background task",n);w=e.title||t.title,v=e.reuseOutcomeBranch||t.branchName}let S=!1,j="no_git_at_all";const B=C(E()),T=!e.skipBundle&&x(process.env.CCR_FORCE_BUNDLE),I=!e.skipBundle&&null!==B&&(x(process.env.CCR_ENABLE_BUNDLE)||await i("tengu_ccr_bundle_seed_enabled"));if(g&&!T?"github.com"===g.host?(S=await y(g.owner,g.name,n),j=S?"github_preflight_ok":"github_preflight_failed"):(S=!0,j="ghes_optimistic"):T?j="forced_bundle":B&&(j="no_github_remote"),S||I||!g||(S=!0),S&&g){const{host:t,owner:o,name:r}=g,n=e.branchName??await N()??void 0;k(`[teleportToRemote] Git source: ${t}/${o}/${r}, revision: ${n??"none"}`),d={type:"git_repository",url:`https://${t}/${o}/${r}`,revision:n,...e.reuseOutcomeBranch&&{allow_unrestricted_git_push:!0}},m={type:"git_repository",git_info:{type:"github",repo:`${o}/${r}`,branches:[v]}}}if(!d&&I){k(`[teleportToRemote] Bundling (reason: ${j})`);const t=await V({oauthToken:c,sessionId:s(),baseUrl:p().BASE_API_URL},{signal:n});if(!1===t.success){const o=t.error,r=t.failReason;F(new Error(`Bundle upload failed: ${o}`));const n=g?". Please setup GitHub on https://claude.ai/code":"";let s;switch(r){case"empty_repo":s='Repository has no commits — run `git add . && git commit -m "initial"` then retry';break;case"too_large":s=`Repo is too large to teleport${n}`;break;case"git_error":s=`Failed to create git bundle (${o})${n}`;break;default:s=`Bundle upload failed: ${o}${n}`}return e.onBundleFail?.(s),null}f=t.fileId,a("tengu_teleport_bundle_mode",{size_bytes:t.bundleSizeBytes,scope:t.scope,has_wip:t.hasWip,reason:j})}a("tengu_teleport_source_decision",{reason:j,path:d?"github":f?"bundle":"empty"}),d||f||k("[teleportToRemote] No repository detected — session will have an empty sandbox");let P=await J();if(!P||0===P.length)return F(new Error("No environments available for session creation")),null;k(`Available environments: ${P.map(e=>`${e.environment_id} (${e.name}, ${e.kind})`).join(", ")}`);const U=O(),D=e.useDefaultEnvironment?void 0:U?.remote?.defaultEnvironmentId;let H=P.find(e=>"anthropic_cloud"===e.kind);if(e.useDefaultEnvironment&&!H){k(`No anthropic_cloud in env list (${P.length} envs); retrying fetchEnvironments`);const e=await J();if(H=e?.find(e=>"anthropic_cloud"===e.kind),!H)return F(new Error(`No anthropic_cloud environment available after retry (got: ${(e??P).map(e=>`${e.name} (${e.kind})`).join(", ")}). Silent byoc fallthrough would launch into a dead env — fail fast instead.`)),null;e&&(P=e)}const M=D&&P.find(e=>e.environment_id===D)||H||P.find(e=>"bridge"!==e.kind)||P[0];if(!M)return F(new Error("No environments available for session creation")),null;if(D){const e=M.environment_id===D;k(e?`Using configured default environment: ${D}`:`Configured default environment ${D} not found, using first available`)}const G=M.environment_id;k(`Selected environment: ${G} (${M.name}, ${M.kind})`);const W=`${p().BASE_API_URL}/v1/sessions`,X={...K(c),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":u},Z={sources:d?[d]:[],...f&&{seed_bundle_file_id:f},outcomes:m?[m]:[],model:e.model??z(),...e.reuseOutcomeBranch&&{reuse_outcome_branches:!0},...e.githubPr&&{github_pr:e.githubPr}},ee=[];e.permissionMode&&ee.push({type:"event",data:{type:"control_request",request_id:`set-mode-${r()}`,request:{subtype:"set_permission_mode",mode:e.permissionMode,ultraplan:e.ultraplan}}}),o&&ee.push({type:"event",data:{uuid:r(),session_id:"",type:"user",parent_tool_use_id:null,message:{role:"user",content:o}}});const te={title:e.ultraplan?`ultraplan: ${w}`:w,events:ee,session_context:Z,environment_id:G};k(`Creating session with payload: ${q(te,null,2)}`);const oe=await t.post(W,te,{headers:X,signal:n});if(!(200===oe.status||201===oe.status))return F(new Error(`API request failed with status ${oe.status}: ${oe.statusText}\n\nResponse data: ${q(oe.data,null,2)}`)),null;const re=oe.data;return re&&"string"==typeof re.id?(k(`Successfully created remote session: ${re.id}`),{id:re.id,title:re.title||te.title}):(F(new Error(`Cannot determine session ID from API response: ${q(oe.data)}`)),null)}catch(e){const t=T(e);return F(t),null}}export async function archiveRemoteSession(e){const o=$()?.accessToken;if(!o)return;const r=await _();if(!r)return;const n={...K(o),"anthropic-beta":"ccr-byoc-2025-07-29","x-organization-uuid":r},s=`${p().BASE_API_URL}/v1/sessions/${e}/archive`;try{const o=await t.post(s,{},{headers:n,timeout:1e4,validateStatus:e=>e<500});200===o.status||409===o.status?k(`[archiveRemoteSession] archived ${e}`):k(`[archiveRemoteSession] ${e} failed ${o.status}: ${q(o.data)}`)}catch(e){F(e)}}
@@ -1 +1 @@
1
- import{createHash as t,randomUUID as e}from"crypto";import{tmpdir as o}from"os";import{join as a}from"path";export function generateTempFilePath(r="claude-prompt",s=".md",m){const n=m?.contentHash?t("sha256").update(m.contentHash).digest("hex").slice(0,16):e();return a(o(),`${r}-${n}${s}`)}
1
+ import{createHash as t,randomUUID as e}from"crypto";import{tmpdir as o}from"os";import{join as r}from"path";export function generateTempFilePath(p="claude-prompt",m=".md",n){const a=n?.contentHash?t("sha256").update(n.contentHash).digest("hex").slice(0,16):e();return r(o(),`${p}-${a}${m}`)}
@@ -1 +1 @@
1
- import n from"chalk";import{ctrlOToExpand as t}from"../components/CtrlOToExpand.js";import{stringWidth as i}from"../ink/stringWidth.js";import e from"./sliceAnsi.js";export function renderTruncatedContent(o,r,s=!1){const l=o.trimEnd();if(!l)return"";const a=Math.max(r-10,10),m=3*a*4,c=l.length>m,d=c?l.slice(0,m):l,{aboveTheFold:f,remainingLines:h}=function(n,t){const o=n.split("\n"),r=[];for(const n of o){const o=i(n);if(o<=t)r.push(n.trimEnd());else{let i=0;for(;i<o;){const o=e(n,i,i+t);r.push(o.trimEnd()),i+=t}}}const s=r.length-3;return 1===s?{aboveTheFold:r.slice(0,4).join("\n").trimEnd(),remainingLines:0}:{aboveTheFold:r.slice(0,3).join("\n").trimEnd(),remainingLines:Math.max(0,s)}}(d,a),u=c?Math.max(h,Math.ceil(l.length/a)-3):h;return[f,u>0?n.dim(`… +${u} lines${s?"":` ${t()}`}`):""].filter(Boolean).join("\n")}export function isOutputLineTruncated(n){let t=0;for(let i=0;i<=3;i++){if(t=n.indexOf("\n",t),-1===t)return!1;t++}return t<n.length}
1
+ import n from"chalk";import{ctrlOToExpand as t}from"../components/CtrlOToExpand.js";import{stringWidth as e}from"../ink/stringWidth.js";import i from"./sliceAnsi.js";export function renderTruncatedContent(o,r,s=!1){const l=o.trimEnd();if(!l)return"";const m=Math.max(r-10,10),c=3*m*4,a=l.length>c,f=a?l.slice(0,c):l,{aboveTheFold:d,remainingLines:h}=function(n,t){const o=n.split("\n"),r=[];for(const n of o){const o=e(n);if(o<=t)r.push(n.trimEnd());else{let e=0;for(;e<o;){const o=i(n,e,e+t);r.push(o.trimEnd()),e+=t}}}const s=r.length-3;return 1===s?{aboveTheFold:r.slice(0,4).join("\n").trimEnd(),remainingLines:0}:{aboveTheFold:r.slice(0,3).join("\n").trimEnd(),remainingLines:Math.max(0,s)}}(f,m),u=a?Math.max(h,Math.ceil(l.length/m)-3):h;return[d,u>0?n.dim(`… +${u} lines${s?"":` ${t()}`}`):""].filter(Boolean).join("\n")}export function isOutputLineTruncated(n){let t=0;for(let e=0;e<=3;e++){if(t=n.indexOf("\n",t),-1===t)return!1;t++}return t<n.length}
@@ -1 +1 @@
1
- import{spawn as e,spawnSync as t}from"child_process";import{getSessionId as s}from"../bootstrap/state.js";import n from"../ink/instances.js";import{registerCleanup as i}from"./cleanupRegistry.js";import{pwd as r}from"./cwd.js";import{logForDebugging as a}from"./debug.js";const o="panel";export function getTerminalPanelSocket(){return`claude-panel-${s().slice(0,8)}`}let l;export function getTerminalPanel(){return l||(l=new TerminalPanel),l}class TerminalPanel{hasTmux;cleanupRegistered=!1;toggle(){this.showShell()}checkTmux(){if(void 0!==this.hasTmux)return this.hasTmux;const e=t("tmux",["-V"],{encoding:"utf-8"});return this.hasTmux=0===e.status,this.hasTmux||a("Terminal panel: tmux not found, falling back to non-persistent shell"),this.hasTmux}hasSession(){return 0===t("tmux",["-L",getTerminalPanelSocket(),"has-session","-t",o],{encoding:"utf-8"}).status}createSession(){const s=process.env.SHELL||"/bin/bash",n=r(),l=getTerminalPanelSocket(),u=t("tmux",["-L",l,"new-session","-d","-s",o,"-c",n,s,"-l"],{encoding:"utf-8"});return 0!==u.status?(a(`Terminal panel: failed to create tmux session: ${u.stderr}`),!1):(t("tmux",["-L",l,"bind-key","-n","M-j","detach-client",";","set-option","-g","status-style","bg=default",";","set-option","-g","status-left","",";","set-option","-g","status-right"," Alt+J to return to Claude ",";","set-option","-g","status-right-style","fg=brightblack"]),this.cleanupRegistered||(this.cleanupRegistered=!0,i(async()=>{e("tmux",["-L",l,"kill-server"],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref()})),!0)}attachSession(){t("tmux",["-L",getTerminalPanelSocket(),"attach-session","-t",o],{stdio:"inherit"})}showShell(){const e=n.get(process.stdout);if(e){e.enterAlternateScreen();try{this.checkTmux()&&this.ensureSession()?this.attachSession():this.runShellDirect()}finally{e.exitAlternateScreen()}}else a("Terminal panel: no Ink instance found, aborting")}ensureSession(){return!!this.hasSession()||this.createSession()}runShellDirect(){const e=process.env.SHELL||"/bin/bash",s=r();t(e,["-i","-l"],{stdio:"inherit",cwd:s,env:process.env})}}
1
+ import{spawn as e,spawnSync as t}from"child_process";import{getSessionId as s}from"../bootstrap/state.js";import n from"../ink/instances.js";import{registerCleanup as i}from"./cleanupRegistry.js";import{pwd as r}from"./cwd.js";import{logForDebugging as o}from"./debug.js";const a="panel";export function getTerminalPanelSocket(){return`claude-panel-${s().slice(0,8)}`}let l;export function getTerminalPanel(){return l||(l=new TerminalPanel),l}class TerminalPanel{hasTmux;cleanupRegistered=!1;toggle(){this.showShell()}checkTmux(){if(void 0!==this.hasTmux)return this.hasTmux;const e=t("tmux",["-V"],{encoding:"utf-8"});return this.hasTmux=0===e.status,this.hasTmux||o("Terminal panel: tmux not found, falling back to non-persistent shell"),this.hasTmux}hasSession(){return 0===t("tmux",["-L",getTerminalPanelSocket(),"has-session","-t",a],{encoding:"utf-8"}).status}createSession(){const s=process.env.SHELL||"/bin/bash",n=r(),l=getTerminalPanelSocket(),c=t("tmux",["-L",l,"new-session","-d","-s",a,"-c",n,s,"-l"],{encoding:"utf-8"});return 0!==c.status?(o(`Terminal panel: failed to create tmux session: ${c.stderr}`),!1):(t("tmux",["-L",l,"bind-key","-n","M-j","detach-client",";","set-option","-g","status-style","bg=default",";","set-option","-g","status-left","",";","set-option","-g","status-right"," Alt+J to return to Claude ",";","set-option","-g","status-right-style","fg=brightblack"]),this.cleanupRegistered||(this.cleanupRegistered=!0,i(async()=>{e("tmux",["-L",l,"kill-server"],{detached:!0,stdio:"ignore"}).on("error",()=>{}).unref()})),!0)}attachSession(){t("tmux",["-L",getTerminalPanelSocket(),"attach-session","-t",a],{stdio:"inherit"})}showShell(){const e=n.get(process.stdout);if(e){e.enterAlternateScreen();try{this.checkTmux()&&this.ensureSession()?this.attachSession():this.runShellDirect()}finally{e.exitAlternateScreen()}}else o("Terminal panel: no Ink instance found, aborting")}ensureSession(){return!!this.hasSession()||this.createSession()}runShellDirect(){const e=process.env.SHELL||"/bin/bash",s=r();t(e,["-i","-l"],{stdio:"inherit",cwd:s,env:process.env})}}
@@ -1 +1 @@
1
- import{ansiCodesToString as t,reduceAnsiCodes as s,tokenize as e,undoAnsiCodes as n}from"@alcalzone/ansi-tokenize";export function segmentTextByHighlights(t,s){if(0===s.length)return[{text:t,start:0}];const e=[...s].sort((t,s)=>t.start!==s.start?t.start-s.start:s.priority-t.priority),n=[],i=[];for(const t of e)t.start!==t.end&&(i.some(s=>t.start>=s.start&&t.start<s.end||t.end>s.start&&t.end<=s.end||t.start<=s.start&&t.end>=s.end)||(n.push(t),i.push({start:t.start,end:t.end})));return new HighlightSegmenter(t).segment(n)}class HighlightSegmenter{text;tokens;visiblePos=0;stringPos=0;tokenIdx=0;charIdx=0;codes=[];constructor(t){this.text=t,this.tokens=e(t)}segment(t){const s=[];for(const e of t){const t=this.segmentTo(e.start);t&&s.push(t);const n=this.segmentTo(e.end);n&&(n.highlight=e,s.push(n))}const e=this.segmentTo(1/0);return e&&s.push(e),s}segmentTo(s){if(this.tokenIdx>=this.tokens.length||s<=this.visiblePos)return null;const e=this.visiblePos;for(;this.tokenIdx<this.tokens.length;){const t=this.tokens[this.tokenIdx];if("ansi"!==t.type)break;this.codes.push(t),this.stringPos+=t.code.length,this.tokenIdx++}const i=this.stringPos,o=[...this.codes];for(;this.visiblePos<s&&this.tokenIdx<this.tokens.length;){const t=this.tokens[this.tokenIdx];if("ansi"===t.type)this.codes.push(t),this.stringPos+=t.code.length,this.tokenIdx++;else{const e=s-this.visiblePos,n=t.value.length-this.charIdx,i=Math.min(e,n);this.stringPos+=i,this.visiblePos+=i,this.charIdx+=i,this.charIdx>=t.value.length&&(this.tokenIdx++,this.charIdx=0)}}if(this.stringPos===i)return null;const h=reduceCodes(o),r=reduceCodes(this.codes);this.codes=r;const d=t(h),c=t(n(r));return{text:d+this.text.substring(i,this.stringPos)+c,start:e}}}function reduceCodes(t){return s(t).filter(t=>t.code!==t.endCode)}
1
+ import{ansiCodesToString as t,reduceAnsiCodes as s,tokenize as e,undoAnsiCodes as n}from"@alcalzone/ansi-tokenize";export function segmentTextByHighlights(t,s){if(0===s.length)return[{text:t,start:0}];const e=[...s].sort((t,s)=>t.start!==s.start?t.start-s.start:s.priority-t.priority),n=[],i=[];for(const t of e){if(t.start===t.end)continue;i.some(s=>t.start>=s.start&&t.start<s.end||t.end>s.start&&t.end<=s.end||t.start<=s.start&&t.end>=s.end)||(n.push(t),i.push({start:t.start,end:t.end}))}return new HighlightSegmenter(t).segment(n)}class HighlightSegmenter{text;tokens;visiblePos=0;stringPos=0;tokenIdx=0;charIdx=0;codes=[];constructor(t){this.text=t,this.tokens=e(t)}segment(t){const s=[];for(const e of t){const t=this.segmentTo(e.start);t&&s.push(t);const n=this.segmentTo(e.end);n&&(n.highlight=e,s.push(n))}const e=this.segmentTo(1/0);return e&&s.push(e),s}segmentTo(s){if(this.tokenIdx>=this.tokens.length||s<=this.visiblePos)return null;const e=this.visiblePos;for(;this.tokenIdx<this.tokens.length;){const t=this.tokens[this.tokenIdx];if("ansi"!==t.type)break;this.codes.push(t),this.stringPos+=t.code.length,this.tokenIdx++}const i=this.stringPos,o=[...this.codes];for(;this.visiblePos<s&&this.tokenIdx<this.tokens.length;){const t=this.tokens[this.tokenIdx];if("ansi"===t.type)this.codes.push(t),this.stringPos+=t.code.length,this.tokenIdx++;else{const e=s-this.visiblePos,n=t.value.length-this.charIdx,i=Math.min(e,n);this.stringPos+=i,this.visiblePos+=i,this.charIdx+=i,this.charIdx>=t.value.length&&(this.tokenIdx++,this.charIdx=0)}}if(this.stringPos===i)return null;const h=reduceCodes(o),r=reduceCodes(this.codes);this.codes=r;const d=t(h),c=t(n(r));return{text:d+this.text.substring(i,this.stringPos)+c,start:e}}}function reduceCodes(t){return s(t).filter(t=>t.code!==t.endCode)}