@iaforged/context-code 2.1.5 → 2.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/Task.js +1 -1
- package/dist/src/commands/add-dir/add-dir.js +1 -1
- package/dist/src/commands/add-dir/validation.js +1 -1
- package/dist/src/constants/oauth.js +1 -1
- package/dist/src/context/mailbox.js +1 -1
- package/dist/src/context/voice.js +1 -1
- package/dist/src/hooks/useTerminalSize.js +1 -1
- package/dist/src/ink/Ansi.js +1 -1
- package/dist/src/ink/clearTerminal.js +1 -1
- package/dist/src/ink/colorize.js +1 -1
- package/dist/src/ink/components/App.js +1 -1
- package/dist/src/ink/components/Button.js +1 -1
- package/dist/src/ink/components/ClockContext.js +1 -1
- package/dist/src/ink/components/CursorDeclarationContext.js +1 -1
- package/dist/src/ink/components/Link.js +1 -1
- package/dist/src/ink/components/StdinContext.js +1 -1
- package/dist/src/ink/components/TerminalFocusContext.js +1 -1
- package/dist/src/ink/dom.js +1 -1
- package/dist/src/ink/events/keyboard-event.js +1 -1
- package/dist/src/ink/hit-test.js +1 -1
- package/dist/src/ink/hooks/use-animation-frame.js +1 -1
- package/dist/src/ink/hooks/use-app.js +1 -1
- package/dist/src/ink/hooks/use-input.js +1 -1
- package/dist/src/ink/hooks/use-interval.js +1 -1
- package/dist/src/ink/hooks/use-selection.js +1 -1
- package/dist/src/ink/hooks/use-tab-status.js +1 -1
- package/dist/src/ink/hooks/use-terminal-focus.js +1 -1
- package/dist/src/ink/hooks/use-terminal-title.js +1 -1
- package/dist/src/ink/hooks/use-terminal-viewport.js +1 -1
- package/dist/src/ink/ink.js +1 -1
- package/dist/src/ink/layout/yoga.js +1 -1
- package/dist/src/ink/line-width-cache.js +1 -1
- package/dist/src/ink/log-update.js +1 -1
- package/dist/src/ink/measure-text.js +1 -1
- package/dist/src/ink/output.js +1 -1
- package/dist/src/ink/parse-keypress.js +1 -1
- package/dist/src/ink/reconciler.js +1 -1
- package/dist/src/ink/render-border.js +1 -1
- package/dist/src/ink/render-node-to-output.js +1 -1
- package/dist/src/ink/render-to-screen.js +1 -1
- package/dist/src/ink/renderer.js +1 -1
- package/dist/src/ink/root.js +1 -1
- package/dist/src/ink/screen.js +1 -1
- package/dist/src/ink/searchHighlight.js +1 -1
- package/dist/src/ink/selection.js +1 -1
- package/dist/src/ink/squash-text-nodes.js +1 -1
- package/dist/src/ink/stringWidth.js +1 -1
- package/dist/src/ink/tabstops.js +1 -1
- package/dist/src/ink/terminal.js +1 -1
- package/dist/src/ink/termio/osc.js +1 -1
- package/dist/src/ink/termio/parser.js +1 -1
- package/dist/src/ink/termio/tokenize.js +1 -1
- package/dist/src/ink/useTerminalNotification.js +1 -1
- package/dist/src/ink/warn.js +1 -1
- package/dist/src/ink/widest-line.js +1 -1
- package/dist/src/ink/wrap-text.js +1 -1
- package/dist/src/ink/wrapAnsi.js +1 -1
- package/dist/src/native-ts/yoga-layout/index.js +1 -1
- package/dist/src/schemas/hooks.js +1 -1
- package/dist/src/services/SessionMemory/sessionMemoryUtils.js +1 -1
- package/dist/src/services/api/client.js +1 -1
- package/dist/src/services/api/dumpPrompts.js +1 -1
- package/dist/src/services/api/errorUtils.js +1 -1
- package/dist/src/services/api/promptCacheBreakDetection.js +1 -1
- package/dist/src/services/api/withRetry.js +1 -1
- package/dist/src/services/autoDream/consolidationLock.js +1 -1
- package/dist/src/services/mcp/elicitationHandler.js +1 -1
- package/dist/src/services/mcp/mcpStringUtils.js +1 -1
- package/dist/src/services/mcp/oauthPort.js +1 -1
- package/dist/src/services/mcp/vscodeSdkMcp.js +1 -1
- package/dist/src/services/oauth/client.js +1 -1
- package/dist/src/services/oauth/getOauthProfile.js +1 -1
- package/dist/src/services/objetivo/types.js +1 -1
- package/dist/src/services/rateLimitMocking.js +1 -1
- package/dist/src/services/remoteManagedSettings/syncCacheState.js +1 -1
- package/dist/src/skills/bundledSkills.js +1 -1
- package/dist/src/tasks/DreamTask/DreamTask.js +1 -1
- package/dist/src/tools/AgentTool/agentMemory.js +1 -1
- package/dist/src/tools/AgentTool/forkSubagent.js +1 -1
- package/dist/src/tools/BashTool/BashToolResultMessage.js +1 -1
- package/dist/src/tools/BashTool/UI.js +1 -1
- package/dist/src/tools/BashTool/sedEditParser.js +1 -1
- package/dist/src/tools/BashTool/utils.js +1 -1
- package/dist/src/tools/FileReadTool/imageProcessor.js +1 -1
- package/dist/src/tools/FileReadTool/prompt.js +1 -1
- package/dist/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +1 -1
- package/dist/src/tools/ListMcpResourcesTool/UI.js +1 -1
- package/dist/src/tools/MCPTool/MCPTool.js +1 -1
- package/dist/src/tools/MCPTool/UI.js +1 -1
- package/dist/src/tools/McpAuthTool/McpAuthTool.js +1 -1
- package/dist/src/tools/NotebookEditTool/prompt.js +1 -1
- package/dist/src/tools/PowerShellTool/PowerShellTool.js +1 -1
- package/dist/src/tools/PowerShellTool/UI.js +1 -1
- package/dist/src/tools/PowerShellTool/gitSafety.js +1 -1
- package/dist/src/tools/PowerShellTool/modeValidation.js +1 -1
- package/dist/src/tools/PowerShellTool/pathValidation.js +1 -1
- package/dist/src/tools/PowerShellTool/powershellPermissions.js +1 -1
- package/dist/src/tools/PowerShellTool/powershellSecurity.js +1 -1
- package/dist/src/tools/PowerShellTool/prompt.js +1 -1
- package/dist/src/tools/PowerShellTool/readOnlyValidation.js +1 -1
- package/dist/src/tools/REPLTool/constants.js +1 -1
- package/dist/src/tools/REPLTool/primitiveTools.js +1 -1
- package/dist/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +1 -1
- package/dist/src/tools/ReadMcpResourceTool/UI.js +1 -1
- package/dist/src/tools/ScheduleCronTool/prompt.js +1 -1
- package/dist/src/tools/SkillTool/prompt.js +1 -1
- package/dist/src/tools/TodoWriteTool/TodoWriteTool.js +1 -1
- package/dist/src/tools/ToolSearchTool/prompt.js +1 -1
- package/dist/src/tools/WebSearchTool/prompt.js +1 -1
- package/dist/src/tools/shared/gitOperationTracking.js +1 -1
- package/dist/src/types/permissions.js +1 -1
- package/dist/src/utils/Cursor.js +1 -1
- package/dist/src/utils/QueryGuard.js +1 -1
- package/dist/src/utils/Shell.js +1 -1
- package/dist/src/utils/ShellCommand.js +1 -1
- package/dist/src/utils/activityManager.js +1 -1
- package/dist/src/utils/advisor.js +1 -1
- package/dist/src/utils/appleTerminalBackup.js +1 -1
- package/dist/src/utils/argumentSubstitution.js +1 -1
- package/dist/src/utils/authFileDescriptor.js +1 -1
- package/dist/src/utils/autoUpdater.js +1 -1
- package/dist/src/utils/background/remote/preconditions.js +1 -1
- package/dist/src/utils/background/remote/remoteSession.js +1 -1
- package/dist/src/utils/bash/ShellSnapshot.js +1 -1
- package/dist/src/utils/bash/ast.js +1 -1
- package/dist/src/utils/bash/bashParser.js +1 -1
- package/dist/src/utils/bash/bashPipeCommand.js +1 -1
- package/dist/src/utils/bash/parser.js +1 -1
- package/dist/src/utils/bash/shellQuote.js +1 -1
- package/dist/src/utils/bash/shellQuoting.js +1 -1
- package/dist/src/utils/billing.js +1 -1
- package/dist/src/utils/caCerts.js +1 -1
- package/dist/src/utils/claudeInChrome/common.js +1 -1
- package/dist/src/utils/claudeInChrome/setupPortable.js +1 -1
- package/dist/src/utils/claudemd.js +1 -1
- package/dist/src/utils/collapseBackgroundBashNotifications.js +1 -1
- package/dist/src/utils/collapseReadSearch.js +1 -1
- package/dist/src/utils/completionCache.js +1 -1
- package/dist/src/utils/computerUse/common.js +1 -1
- package/dist/src/utils/concurrentSessions.js +1 -1
- package/dist/src/utils/context.js +1 -1
- package/dist/src/utils/cron.js +1 -1
- package/dist/src/utils/cronTasks.js +1 -1
- package/dist/src/utils/cwd.js +1 -1
- package/dist/src/utils/debug.js +1 -1
- package/dist/src/utils/debugFilter.js +1 -1
- package/dist/src/utils/detectRepository.js +1 -1
- package/dist/src/utils/diagLogs.js +1 -1
- package/dist/src/utils/diff.js +1 -1
- package/dist/src/utils/directMemberMessage.js +1 -1
- package/dist/src/utils/doctorDiagnostic.js +1 -1
- package/dist/src/utils/dxt/helpers.js +1 -1
- package/dist/src/utils/dxt/zip.js +1 -1
- package/dist/src/utils/earlyInput.js +1 -1
- package/dist/src/utils/editor.js +1 -1
- package/dist/src/utils/effort.js +1 -1
- package/dist/src/utils/embeddedTools.js +1 -1
- package/dist/src/utils/envDynamic.js +1 -1
- package/dist/src/utils/envUtils.js +1 -1
- package/dist/src/utils/execFileNoThrowPortable.js +1 -1
- package/dist/src/utils/execSyncWrapper.js +1 -1
- package/dist/src/utils/exportRenderer.js +1 -1
- package/dist/src/utils/extraUsage.js +1 -1
- package/dist/src/utils/fastMode.js +1 -1
- package/dist/src/utils/fileOperationAnalytics.js +1 -1
- package/dist/src/utils/fileRead.js +1 -1
- package/dist/src/utils/findExecutable.js +1 -1
- package/dist/src/utils/format.js +1 -1
- package/dist/src/utils/frontmatterParser.js +1 -1
- package/dist/src/utils/fsOperations.js +1 -1
- package/dist/src/utils/fullscreen.js +1 -1
- package/dist/src/utils/genericProcessUtils.js +1 -1
- package/dist/src/utils/getWorktreePaths.js +1 -1
- package/dist/src/utils/git/gitConfigParser.js +1 -1
- package/dist/src/utils/git/gitFilesystem.js +1 -1
- package/dist/src/utils/git/gitignore.js +1 -1
- package/dist/src/utils/gitDiff.js +1 -1
- package/dist/src/utils/gitSettings.js +1 -1
- package/dist/src/utils/glob.js +1 -1
- package/dist/src/utils/gracefulShutdown.js +1 -1
- package/dist/src/utils/groupToolUses.js +1 -1
- package/dist/src/utils/handlePromptSubmit.js +1 -1
- package/dist/src/utils/hash.js +1 -1
- package/dist/src/utils/hooks/fileChangedWatcher.js +1 -1
- package/dist/src/utils/hooks/hooksSettings.js +1 -1
- package/dist/src/utils/hooks/registerSkillHooks.js +1 -1
- package/dist/src/utils/hooks/sessionHooks.js +1 -1
- package/dist/src/utils/http.js +1 -1
- package/dist/src/utils/hyperlink.js +1 -1
- package/dist/src/utils/ide.js +1 -1
- package/dist/src/utils/idePathConversion.js +1 -1
- package/dist/src/utils/imagePaste.js +1 -1
- package/dist/src/utils/imageResizer.js +1 -1
- package/dist/src/utils/imageStore.js +1 -1
- package/dist/src/utils/inProcessTeammateHelpers.js +1 -1
- package/dist/src/utils/ink.js +1 -1
- package/dist/src/utils/jetbrains.js +1 -1
- package/dist/src/utils/json.js +1 -1
- package/dist/src/utils/listSessionsImpl.js +1 -1
- package/dist/src/utils/localInstaller.js +1 -1
- package/dist/src/utils/lockfile.js +1 -1
- package/dist/src/utils/logoV2Utils.js +1 -1
- package/dist/src/utils/markdown.js +1 -1
- package/dist/src/utils/mcp/dateTimeParser.js +1 -1
- package/dist/src/utils/mcpOutputStorage.js +1 -1
- package/dist/src/utils/mcpValidation.js +1 -1
- package/dist/src/utils/memoize.js +1 -1
- package/dist/src/utils/memory/types.js +1 -1
- package/dist/src/utils/memoryFileDetection.js +1 -1
- package/dist/src/utils/messageQueueManager.js +1 -1
- package/dist/src/utils/messages/mappers.js +1 -1
- package/dist/src/utils/messages/systemInit.js +1 -1
- package/dist/src/utils/model/antModels.js +1 -1
- package/dist/src/utils/model/check1mAccess.js +1 -1
- package/dist/src/utils/model/contextWindowUpgradeCheck.js +1 -1
- package/dist/src/utils/model/model.js +1 -1
- package/dist/src/utils/model/modelAllowlist.js +1 -1
- package/dist/src/utils/model/modelCapabilities.js +1 -1
- package/dist/src/utils/model/modelOptions.js +1 -1
- package/dist/src/utils/model/modelStrings.js +1 -1
- package/dist/src/utils/model/providerModels.js +1 -1
- package/dist/src/utils/model/providerProfiles.js +1 -1
- package/dist/src/utils/model/providerProfilesDb.js +1 -1
- package/dist/src/utils/model/providerSwitch.js +1 -1
- package/dist/src/utils/model/providers.js +1 -1
- package/dist/src/utils/modelCost.js +1 -1
- package/dist/src/utils/modifiers.js +1 -1
- package/dist/src/utils/mtls.js +1 -1
- package/dist/src/utils/nativeInstaller/download.js +1 -1
- package/dist/src/utils/nativeInstaller/installer.js +1 -1
- package/dist/src/utils/nativeInstaller/packageManagers.js +1 -1
- package/dist/src/utils/nativeInstaller/pidLock.js +1 -1
- package/dist/src/utils/notebook.js +1 -1
- package/dist/src/utils/pasteStore.js +1 -1
- package/dist/src/utils/path.js +1 -1
- package/dist/src/utils/permissions/PermissionMode.js +1 -1
- package/dist/src/utils/permissions/PermissionPromptToolResultSchema.js +1 -1
- package/dist/src/utils/permissions/PermissionUpdate.js +1 -1
- package/dist/src/utils/permissions/PermissionUpdateSchema.js +1 -1
- package/dist/src/utils/permissions/autoModeState.js +1 -1
- package/dist/src/utils/permissions/bypassPermissionsKillswitch.js +1 -1
- package/dist/src/utils/permissions/filesystem.js +1 -1
- package/dist/src/utils/permissions/getNextPermissionMode.js +1 -1
- package/dist/src/utils/permissions/pathValidation.js +1 -1
- package/dist/src/utils/permissions/permissionRuleParser.js +1 -1
- package/dist/src/utils/permissions/permissionsDb.js +1 -1
- package/dist/src/utils/permissions/permissionsLoader.js +1 -1
- package/dist/src/utils/permissions/shellRuleMatching.js +1 -1
- package/dist/src/utils/planModeV2.js +1 -1
- package/dist/src/utils/plans.js +1 -1
- package/dist/src/utils/platform.js +1 -1
- package/dist/src/utils/plugins/addDirPluginSettings.js +1 -1
- package/dist/src/utils/plugins/cacheUtils.js +1 -1
- package/dist/src/utils/plugins/dependencyResolver.js +1 -1
- package/dist/src/utils/plugins/fetchTelemetry.js +1 -1
- package/dist/src/utils/plugins/gitAvailability.js +1 -1
- package/dist/src/utils/plugins/hintRecommendation.js +1 -1
- package/dist/src/utils/plugins/installedPluginsManager.js +1 -1
- package/dist/src/utils/plugins/loadPluginAgents.js +1 -1
- package/dist/src/utils/plugins/loadPluginCommands.js +1 -1
- package/dist/src/utils/plugins/loadPluginHooks.js +1 -1
- package/dist/src/utils/plugins/loadPluginOutputStyles.js +1 -1
- package/dist/src/utils/plugins/lspPluginIntegration.js +1 -1
- package/dist/src/utils/plugins/lspRecommendation.js +1 -1
- package/dist/src/utils/plugins/managedPlugins.js +1 -1
- package/dist/src/utils/plugins/marketplaceHelpers.js +1 -1
- package/dist/src/utils/plugins/marketplaceManager.js +1 -1
- package/dist/src/utils/plugins/mcpPluginIntegration.js +1 -1
- package/dist/src/utils/plugins/mcpbHandler.js +1 -1
- package/dist/src/utils/plugins/officialMarketplaceGcs.js +1 -1
- package/dist/src/utils/plugins/officialMarketplaceStartupCheck.js +1 -1
- package/dist/src/utils/plugins/orphanedPluginFilter.js +1 -1
- package/dist/src/utils/plugins/performStartupChecks.js +1 -1
- package/dist/src/utils/plugins/pluginAutoupdate.js +1 -1
- package/dist/src/utils/plugins/pluginBlocklist.js +1 -1
- package/dist/src/utils/plugins/pluginDirectories.js +1 -1
- package/dist/src/utils/plugins/pluginFlagging.js +1 -1
- package/dist/src/utils/plugins/pluginInstallationHelpers.js +1 -1
- package/dist/src/utils/plugins/pluginLoader.js +1 -1
- package/dist/src/utils/plugins/pluginOptionsStorage.js +1 -1
- package/dist/src/utils/plugins/pluginPolicy.js +1 -1
- package/dist/src/utils/plugins/pluginStartupCheck.js +1 -1
- package/dist/src/utils/plugins/pluginVersioning.js +1 -1
- package/dist/src/utils/plugins/reconciler.js +1 -1
- package/dist/src/utils/plugins/refresh.js +1 -1
- package/dist/src/utils/plugins/schemas.js +1 -1
- package/dist/src/utils/plugins/walkPluginMarkdown.js +1 -1
- package/dist/src/utils/plugins/zipCache.js +1 -1
- package/dist/src/utils/powershell/parser.js +1 -1
- package/dist/src/utils/processUserInput/processBashCommand.js +1 -1
- package/dist/src/utils/processUserInput/processSlashCommand.js +1 -1
- package/dist/src/utils/processUserInput/processTextPrompt.js +1 -1
- package/dist/src/utils/processUserInput/processUserInput.js +1 -1
- package/dist/src/utils/profilerBase.js +1 -1
- package/dist/src/utils/promptCategory.js +1 -1
- package/dist/src/utils/promptEditor.js +1 -1
- package/dist/src/utils/promptShellExecution.js +1 -1
- package/dist/src/utils/proxy.js +1 -1
- package/dist/src/utils/queryHelpers.js +1 -1
- package/dist/src/utils/queryProfiler.js +1 -1
- package/dist/src/utils/queueProcessor.js +1 -1
- package/dist/src/utils/readFileInRange.js +1 -1
- package/dist/src/utils/releaseNotes.js +1 -1
- package/dist/src/utils/renderOptions.js +1 -1
- package/dist/src/utils/ripgrep.js +1 -1
- package/dist/src/utils/sandbox/sandbox-adapter.js +1 -1
- package/dist/src/utils/sdkEventQueue.js +1 -1
- package/dist/src/utils/secureStorage/index.js +1 -1
- package/dist/src/utils/secureStorage/macOsKeychainHelpers.js +1 -1
- package/dist/src/utils/secureStorage/macOsKeychainStorage.js +1 -1
- package/dist/src/utils/secureStorage/plainTextStorage.js +1 -1
- package/dist/src/utils/secureStorage/sqliteStorage.js +1 -1
- package/dist/src/utils/sessionEnvironment.js +1 -1
- package/dist/src/utils/sessionIngressAuth.js +1 -1
- package/dist/src/utils/sessionRestore.js +1 -1
- package/dist/src/utils/sessionStart.js +1 -1
- package/dist/src/utils/sessionTitle.js +1 -1
- package/dist/src/utils/settings/managedPath.js +1 -1
- package/dist/src/utils/settings/mdm/rawRead.js +1 -1
- package/dist/src/utils/settings/mdm/settings.js +1 -1
- package/dist/src/utils/settings/permissionValidation.js +1 -1
- package/dist/src/utils/settings/pluginOnlyPolicy.js +1 -1
- package/dist/src/utils/settings/schemaOutput.js +1 -1
- package/dist/src/utils/settings/settings.js +1 -1
- package/dist/src/utils/settings/types.js +1 -1
- package/dist/src/utils/settings/validateEditTool.js +1 -1
- package/dist/src/utils/settings/validation.js +1 -1
- package/dist/src/utils/shell/bashProvider.js +1 -1
- package/dist/src/utils/shell/powershellDetection.js +1 -1
- package/dist/src/utils/shell/powershellProvider.js +1 -1
- package/dist/src/utils/shell/readOnlyCommandValidation.js +1 -1
- package/dist/src/utils/shell/resolveDefaultShell.js +1 -1
- package/dist/src/utils/shell/shellToolUtils.js +1 -1
- package/dist/src/utils/shell/specPrefix.js +1 -1
- package/dist/src/utils/shellConfig.js +1 -1
- package/dist/src/utils/sideQuestion.js +1 -1
- package/dist/src/utils/skills/skillChangeDetector.js +1 -1
- package/dist/src/utils/slashCommandParsing.js +1 -1
- package/dist/src/utils/sliceAnsi.js +1 -1
- package/dist/src/utils/slowOperations.js +1 -1
- package/dist/src/utils/standaloneAgent.js +1 -1
- package/dist/src/utils/startupProfiler.js +1 -1
- package/dist/src/utils/staticRender.js +1 -1
- package/dist/src/utils/status.js +1 -1
- package/dist/src/utils/statusNoticeDefinitions.js +1 -1
- package/dist/src/utils/suggestions/commandSuggestions.js +1 -1
- package/dist/src/utils/suggestions/directoryCompletion.js +1 -1
- package/dist/src/utils/suggestions/shellHistoryCompletion.js +1 -1
- package/dist/src/utils/suggestions/skillUsageTracking.js +1 -1
- package/dist/src/utils/suggestions/slackChannelSuggestions.js +1 -1
- package/dist/src/utils/swarm/backends/detection.js +1 -1
- package/dist/src/utils/swarm/permissionSync.js +1 -1
- package/dist/src/utils/swarm/reconnection.js +1 -1
- package/dist/src/utils/swarm/spawnUtils.js +91 -1
- package/dist/src/utils/swarm/teammateInit.js +1 -1
- package/dist/src/utils/systemDirectories.js +1 -1
- package/dist/src/utils/systemPrompt.js +1 -1
- package/dist/src/utils/systemTheme.js +1 -1
- package/dist/src/utils/task/TaskOutput.js +1 -1
- package/dist/src/utils/task/diskOutput.js +1 -1
- package/dist/src/utils/tasks.js +1 -1
- package/dist/src/utils/teamDiscovery.js +1 -1
- package/dist/src/utils/teamMemoryOps.js +1 -1
- package/dist/src/utils/teammateMailbox.js +1 -1
- package/dist/src/utils/telemetry/betaSessionTracing.js +1 -1
- package/dist/src/utils/telemetry/bigqueryExporter.js +1 -1
- package/dist/src/utils/telemetry/events.js +1 -1
- package/dist/src/utils/telemetry/instrumentation.js +1 -1
- package/dist/src/utils/telemetry/logger.js +1 -1
- package/dist/src/utils/telemetry/perfettoTracing.js +1 -1
- package/dist/src/utils/telemetry/pluginTelemetry.js +1 -1
- package/dist/src/utils/telemetry/sessionTracing.js +1 -1
- package/dist/src/utils/telemetryAttributes.js +1 -1
- package/dist/src/utils/teleport/api.js +1 -1
- package/dist/src/utils/teleport/environments.js +1 -1
- package/dist/src/utils/teleport/gitBundle.js +1 -1
- package/dist/src/utils/teleport.js +1 -1
- package/dist/src/utils/tempfile.js +1 -1
- package/dist/src/utils/terminal.js +1 -1
- package/dist/src/utils/terminalPanel.js +1 -1
- package/dist/src/utils/textHighlighting.js +1 -1
- package/dist/src/utils/theme.js +1 -1
- package/dist/src/utils/themes/bootstrap.js +1 -1
- package/dist/src/utils/themes/loader.js +1 -1
- package/dist/src/utils/thinking.js +1 -1
- package/dist/src/utils/tmuxSocket.js +1 -1
- package/dist/src/utils/tokens.js +1 -1
- package/dist/src/utils/toolPool.js +1 -1
- package/dist/src/utils/toolResultStorage.js +1 -1
- package/dist/src/utils/transcriptSearch.js +1 -1
- package/dist/src/utils/truncate.js +1 -1
- package/dist/src/utils/ultraplan/keyword.js +1 -1
- package/dist/src/utils/unaryLogging.js +1 -1
- package/dist/src/utils/undercover.js +1 -1
- package/dist/src/utils/user.js +1 -1
- package/dist/src/utils/userPromptKeywords.js +1 -1
- package/dist/src/utils/which.js +1 -1
- package/dist/src/utils/windowsPaths.js +1 -1
- package/dist/src/utils/worktree.js +1 -1
- package/dist/src/utils/zodToJsonSchema.js +1 -1
- package/dist/src/vim/operators.js +1 -1
- package/dist/src/vim/textObjects.js +1 -1
- package/dist/src/vim/transitions.js +1 -1
- package/dist/src/voice/voiceModeEnabled.js +1 -1
- package/dist/src/webapp/auth.js +1 -1
- package/dist/src/webapp/tunnel.js +1 -1
- package/dist/src/whatsapp/bridge.js +1 -1
- package/dist/src/whatsapp/mirror.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir as e,readdir as
|
|
1
|
+
import{mkdir as e,readdir as r,readFile as t,unlink as s,writeFile as n}from"fs/promises";import{join as o}from"path";import{z as i}from"zod/v4";import{logForDebugging as a}from"../debug.js";import{getErrnoCode as m}from"../errors.js";import{lazySchema as d}from"../lazySchema.js";import*as u from"../lockfile.js";import{logError as c}from"../log.js";import{jsonParse as l,jsonStringify as p}from"../slowOperations.js";import{getAgentId as f,getAgentName as g,getTeammateColor as w,getTeamName as P}from"../teammate.js";import{createPermissionRequestMessage as y,createPermissionResponseMessage as S,createSandboxPermissionRequestMessage as x,createSandboxPermissionResponseMessage as q,writeToMailbox as v}from"../teammateMailbox.js";import{getTeamDir as b,readTeamFileAsync as $}from"./teamHelpers.js";export const SwarmPermissionRequestSchema=d(()=>i.object({id:i.string(),workerId:i.string(),workerName:i.string(),workerColor:i.string().optional(),teamName:i.string(),toolName:i.string(),toolUseId:i.string(),description:i.string(),input:i.record(i.string(),i.unknown()),permissionSuggestions:i.array(i.unknown()),status:i.enum(["pending","approved","rejected"]),resolvedBy:i.enum(["worker","leader"]).optional(),resolvedAt:i.number().optional(),feedback:i.string().optional(),updatedInput:i.record(i.string(),i.unknown()).optional(),permissionUpdates:i.array(i.unknown()).optional(),createdAt:i.number()}));export function getPermissionDir(e){return o(b(e),"permissions")}function getPendingDir(e){return o(getPermissionDir(e),"pending")}function getResolvedDir(e){return o(getPermissionDir(e),"resolved")}async function ensurePermissionDirsAsync(r){const t=getPermissionDir(r),s=getPendingDir(r),n=getResolvedDir(r);for(const r of[t,s,n])await e(r,{recursive:!0})}function getPendingRequestPath(e,r){return o(getPendingDir(e),`${r}.json`)}function getResolvedRequestPath(e,r){return o(getResolvedDir(e),`${r}.json`)}export function generateRequestId(){return`perm-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}export function createPermissionRequest(e){const r=e.teamName||P(),t=e.workerId||f(),s=e.workerName||g(),n=e.workerColor||w();if(!r)throw new Error("Team name is required for permission requests");if(!t)throw new Error("Worker ID is required for permission requests");if(!s)throw new Error("Worker name is required for permission requests");return{id:generateRequestId(),workerId:t,workerName:s,workerColor:n,teamName:r,toolName:e.toolName,toolUseId:e.toolUseId,description:e.description,input:e.input,permissionSuggestions:e.permissionSuggestions||[],status:"pending",createdAt:Date.now()}}export async function writePermissionRequest(e){await ensurePermissionDirsAsync(e.teamName);const r=getPendingRequestPath(e.teamName,e.id),t=getPendingDir(e.teamName),s=o(t,".lock");let i;await n(s,"","utf-8");try{return i=await u.lock(s),await n(r,p(e,null,2),"utf-8"),a(`[PermissionSync] Wrote pending request ${e.id} from ${e.workerName} for ${e.toolName}`),e}catch(e){throw a(`[PermissionSync] Failed to write permission request: ${e}`),c(e),e}finally{i&&await i()}}export async function readPendingPermissions(e){const s=e||P();if(!s)return a("[PermissionSync] No team name available"),[];const n=getPendingDir(s);let i;try{i=await r(n)}catch(e){return"ENOENT"===m(e)||(a(`[PermissionSync] Failed to read pending requests: ${e}`),c(e)),[]}const d=i.filter(e=>e.endsWith(".json")&&".lock"!==e),u=(await Promise.all(d.map(async e=>{const r=o(n,e);try{const s=await t(r,"utf-8"),n=SwarmPermissionRequestSchema().safeParse(l(s));return n.success?n.data:(a(`[PermissionSync] Invalid request file ${e}: ${n.error.message}`),null)}catch(r){return a(`[PermissionSync] Failed to read request file ${e}: ${r}`),null}}))).filter(e=>null!==e);return u.sort((e,r)=>e.createdAt-r.createdAt),u}export async function readResolvedPermission(e,r){const s=r||P();if(!s)return null;const n=getResolvedRequestPath(s,e);try{const r=await t(n,"utf-8"),s=SwarmPermissionRequestSchema().safeParse(l(r));return s.success?s.data:(a(`[PermissionSync] Invalid resolved request ${e}: ${s.error.message}`),null)}catch(r){return"ENOENT"===m(r)||(a(`[PermissionSync] Failed to read resolved request ${e}: ${r}`),c(r)),null}}export async function resolvePermission(e,r,i){const d=i||P();if(!d)return a("[PermissionSync] No team name available"),!1;await ensurePermissionDirsAsync(d);const f=getPendingRequestPath(d,e),g=getResolvedRequestPath(d,e),w=o(getPendingDir(d),".lock");let y;await n(w,"","utf-8");try{let o;y=await u.lock(w);try{o=await t(f,"utf-8")}catch(r){if("ENOENT"===m(r))return a(`[PermissionSync] Pending request not found: ${e}`),!1;throw r}const i=SwarmPermissionRequestSchema().safeParse(l(o));if(!i.success)return a(`[PermissionSync] Invalid pending request ${e}: ${i.error.message}`),!1;const d={...i.data,status:"approved"===r.decision?"approved":"rejected",resolvedBy:r.resolvedBy,resolvedAt:Date.now(),feedback:r.feedback,updatedInput:r.updatedInput,permissionUpdates:r.permissionUpdates};return await n(g,p(d,null,2),"utf-8"),await s(f),a(`[PermissionSync] Resolved request ${e} with ${r.decision}`),!0}catch(e){return a(`[PermissionSync] Failed to resolve request: ${e}`),c(e),!1}finally{y&&await y()}}export async function cleanupOldResolutions(e,n=36e5){const i=e||P();if(!i)return 0;const d=getResolvedDir(i);let u;try{u=await r(d)}catch(e){return"ENOENT"===m(e)||(a(`[PermissionSync] Failed to cleanup resolutions: ${e}`),c(e)),0}const p=Date.now(),f=u.filter(e=>e.endsWith(".json")),g=(await Promise.all(f.map(async e=>{const r=o(d,e);try{const o=await t(r,"utf-8"),i=l(o),m=i.resolvedAt||i.createdAt;return p-m>=n?(await s(r),a(`[PermissionSync] Cleaned up old resolution: ${e}`),1):0}catch{try{return await s(r),1}catch{return 0}}}))).reduce((e,r)=>e+r,0);return g>0&&a(`[PermissionSync] Cleaned up ${g} old resolutions`),g}export async function pollForResponse(e,r,t){const s=await readResolvedPermission(e,t);return s?{requestId:s.id,decision:"approved"===s.status?"approved":"denied",timestamp:s.resolvedAt?new Date(s.resolvedAt).toISOString():new Date(s.createdAt).toISOString(),feedback:s.feedback,updatedInput:s.updatedInput,permissionUpdates:s.permissionUpdates}:null}export async function removeWorkerResponse(e,r,t){await deleteResolvedPermission(e,t)}export function isTeamLeader(e){if(!e&&!P())return!1;const r=f();return!r||"team-lead"===r}export function isSwarmWorker(){const e=P(),r=f();return!!e&&!!r&&!isTeamLeader()}export async function deleteResolvedPermission(e,r){const t=r||P();if(!t)return!1;const n=getResolvedRequestPath(t,e);try{return await s(n),a(`[PermissionSync] Deleted resolved permission: ${e}`),!0}catch(e){return"ENOENT"===m(e)||(a(`[PermissionSync] Failed to delete resolved permission: ${e}`),c(e)),!1}}export const submitPermissionRequest=writePermissionRequest;export async function getLeaderName(e){const r=e||P();if(!r)return null;const t=await $(r);if(!t)return a(`[PermissionSync] Team file not found for team: ${r}`),null;const s=t.members.find(e=>e.agentId===t.leadAgentId);return s?.name||"team-lead"}export async function sendPermissionRequestViaMailbox(e){const r=await getLeaderName(e.teamName);if(!r)return a("[PermissionSync] Cannot send permission request: leader name not found"),!1;try{const t=y({request_id:e.id,agent_id:e.workerName,tool_name:e.toolName,tool_use_id:e.toolUseId,description:e.description,input:e.input,permission_suggestions:e.permissionSuggestions});return await v(r,{from:e.workerName,text:p(t),timestamp:(new Date).toISOString(),color:e.workerColor},e.teamName),a(`[PermissionSync] Sent permission request ${e.id} to leader ${r} via mailbox`),!0}catch(e){return a(`[PermissionSync] Failed to send permission request via mailbox: ${e}`),c(e),!1}}export async function sendPermissionResponseViaMailbox(e,r,t,s){const n=s||P();if(!n)return a("[PermissionSync] Cannot send permission response: team name not found"),!1;try{const s=S({request_id:t,subtype:"approved"===r.decision?"success":"error",error:r.feedback,updated_input:r.updatedInput,permission_updates:r.permissionUpdates}),o=g()||"team-lead";return await v(e,{from:o,text:p(s),timestamp:(new Date).toISOString()},n),a(`[PermissionSync] Sent permission response for ${t} to worker ${e} via mailbox`),!0}catch(e){return a(`[PermissionSync] Failed to send permission response via mailbox: ${e}`),c(e),!1}}export function generateSandboxRequestId(){return`sandbox-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}export async function sendSandboxPermissionRequestViaMailbox(e,r,t){const s=t||P();if(!s)return a("[PermissionSync] Cannot send sandbox permission request: team name not found"),!1;const n=await getLeaderName(s);if(!n)return a("[PermissionSync] Cannot send sandbox permission request: leader name not found"),!1;const o=f(),i=g(),m=w();if(!o||!i)return a("[PermissionSync] Cannot send sandbox permission request: worker ID or name not found"),!1;try{const t=x({requestId:r,workerId:o,workerName:i,workerColor:m,host:e});return await v(n,{from:i,text:p(t),timestamp:(new Date).toISOString(),color:m},s),a(`[PermissionSync] Sent sandbox permission request ${r} for host ${e} to leader ${n} via mailbox`),!0}catch(e){return a(`[PermissionSync] Failed to send sandbox permission request via mailbox: ${e}`),c(e),!1}}export async function sendSandboxPermissionResponseViaMailbox(e,r,t,s,n){const o=n||P();if(!o)return a("[PermissionSync] Cannot send sandbox permission response: team name not found"),!1;try{const n=q({requestId:r,host:t,allow:s}),i=g()||"team-lead";return await v(e,{from:i,text:p(n),timestamp:(new Date).toISOString()},o),a(`[PermissionSync] Sent sandbox permission response for ${r} (host: ${t}, allow: ${s}) to worker ${e} via mailbox`),!0}catch(e){return a(`[PermissionSync] Failed to send sandbox permission response via mailbox: ${e}`),c(e),!1}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{logForDebugging as e}from"../debug.js";import{logError as t}from"../log.js";import{getDynamicTeamContext as
|
|
1
|
+
import{logForDebugging as e}from"../debug.js";import{logError as t}from"../log.js";import{getDynamicTeamContext as a}from"../teammate.js";import{getTeamFilePath as n,readTeamFile as o}from"./teamHelpers.js";export function computeInitialTeamContext(){const m=a();if(!m?.teamName||!m?.agentName)return void e("[Reconnection] computeInitialTeamContext: No teammate context set (not a teammate)");const{teamName:i,agentId:r,agentName:s}=m,d=o(i);if(!d)return void t(new Error(`[computeInitialTeamContext] Could not read team file for ${i}`));const l=n(i),c=!r;return e(`[Reconnection] Computed initial team context for ${c?"leader":`teammate ${s}`} in team ${i}`),{teamName:i,teamFilePath:l,leadAgentId:d.leadAgentId,selfAgentId:r,selfAgentName:s,isLeader:c,teammates:{}}}export function initializeTeammateContextFromSession(a,m,i){const r=o(m);if(!r)return void t(new Error(`[initializeTeammateContextFromSession] Could not read team file for ${m} (agent: ${i})`));const s=r.members.find(e=>e.name===i);s||e(`[Reconnection] Member ${i} not found in team ${m} - may have been removed`);const d=s?.agentId,l=n(m);a(e=>({...e,teamContext:{teamName:m,teamFilePath:l,leadAgentId:r.leadAgentId,selfAgentId:d,selfAgentName:i,isLeader:!1,teammates:{}}})),e(`[Reconnection] Initialized agent context from session for ${i} in team ${m}`)}
|
|
@@ -1 +1,91 @@
|
|
|
1
|
-
import{getChromeFlagOverride as o,getFlagSettingsPath as s,getInlinePlugins as t,getMainLoopModelOverride as e,getSessionBypassPermissionsMode as n}from"../../bootstrap/state.js";import{quote as E}from"../bash/shellQuote.js";import{isInBundledMode as r}from"../bundledMode.js";import{getTeammateModeFromSnapshot as p}from"./backends/teammateModeSnapshot.js";import{TEAMMATE_COMMAND_ENV_VAR as _}from"./constants.js";export function getTeammateCommand(){return process.env[_]?process.env[_]:r()?process.execPath:process.argv[1]}export function buildInheritedCliFlags(r){const _=[],{planModeRequired:i,permissionMode:c}=r||{};i||("bypassPermissions"===c||n()?_.push("--dangerously-skip-permissions"):"acceptEdits"===c&&_.push("--permission-mode acceptEdits"));const m=e();m&&_.push(`--model ${E([m])}`);const C=s();C&&_.push(`--settings ${E([C])}`);const a=t();for(const o of a)_.push(`--plugin-dir ${E([o])}`);const u=p();_.push(`--teammate-mode ${u}`);const D=o();return!0===D?_.push("--chrome"):!1===D&&_.push("--no-chrome"),_.join(" ")}const i=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","CLAUDE_CODE_REMOTE","CLAUDE_CODE_REMOTE_MEMORY_DIR","HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","NO_PROXY","no_proxy","SSL_CERT_FILE","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE"];export function buildInheritedEnvVars(){const o=["CLAUDECODE=1","CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1"];for(const s of i){const t=process.env[s];void 0!==t&&""!==t&&o.push(`${s}=${E([t])}`)}return o.join(" ")}
|
|
1
|
+
import{getChromeFlagOverride as o,getFlagSettingsPath as s,getInlinePlugins as t,getMainLoopModelOverride as e,getSessionBypassPermissionsMode as n}from"../../bootstrap/state.js";import{quote as E}from"../bash/shellQuote.js";import{isInBundledMode as r}from"../bundledMode.js";import{getTeammateModeFromSnapshot as p}from"./backends/teammateModeSnapshot.js";import{TEAMMATE_COMMAND_ENV_VAR as _}from"./constants.js";export function getTeammateCommand(){return process.env[_]?process.env[_]:r()?process.execPath:process.argv[1]}export function buildInheritedCliFlags(r){const _=[],{planModeRequired:i,permissionMode:c}=r||{};i||("bypassPermissions"===c||n()?_.push("--dangerously-skip-permissions"):"acceptEdits"===c&&_.push("--permission-mode acceptEdits"));const m=e();m&&_.push(`--model ${E([m])}`);const C=s();C&&_.push(`--settings ${E([C])}`);const a=t();for(const o of a)_.push(`--plugin-dir ${E([o])}`);const u=p();_.push(`--teammate-mode ${u}`);const D=o();return!0===D?_.push("--chrome"):!1===D&&_.push("--no-chrome"),_.join(" ")}const i=["CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","CLAUDE_CODE_USE_FOUNDRY","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","CLAUDE_CODE_REMOTE","CLAUDE_CODE_REMOTE_MEMORY_DIR","HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy","NO_PROXY","no_proxy","SSL_CERT_FILE","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE"];export function buildInheritedEnvVars(){const o=["CLAUDECODE=1","CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1"];for(const s of i){const t=process.env[s];void 0!==t&&""!==t&&o.push(`${s}=${E([t])}`)}return o.join(" ")}red) {
|
|
2
|
+
// Don't inherit bypass permissions when plan mode is required
|
|
3
|
+
}
|
|
4
|
+
else if (permissionMode === 'bypassPermissions' ||
|
|
5
|
+
getSessionBypassPermissionsMode()) {
|
|
6
|
+
flags.push('--dangerously-skip-permissions');
|
|
7
|
+
}
|
|
8
|
+
else if (permissionMode === 'acceptEdits') {
|
|
9
|
+
flags.push('--permission-mode acceptEdits');
|
|
10
|
+
}
|
|
11
|
+
// Propagate --model if explicitly set via CLI
|
|
12
|
+
const modelOverride = getMainLoopModelOverride();
|
|
13
|
+
if (modelOverride) {
|
|
14
|
+
flags.push(`--model ${quote([modelOverride])}`);
|
|
15
|
+
}
|
|
16
|
+
// Propagate --settings if set via CLI
|
|
17
|
+
const settingsPath = getFlagSettingsPath();
|
|
18
|
+
if (settingsPath) {
|
|
19
|
+
flags.push(`--settings ${quote([settingsPath])}`);
|
|
20
|
+
}
|
|
21
|
+
// Propagate --plugin-dir for each inline plugin
|
|
22
|
+
const inlinePlugins = getInlinePlugins();
|
|
23
|
+
for (const pluginDir of inlinePlugins) {
|
|
24
|
+
flags.push(`--plugin-dir ${quote([pluginDir])}`);
|
|
25
|
+
}
|
|
26
|
+
// Propagate --teammate-mode so tmux teammates use the same mode as leader
|
|
27
|
+
const sessionMode = getTeammateModeFromSnapshot();
|
|
28
|
+
flags.push(`--teammate-mode ${sessionMode}`);
|
|
29
|
+
// Propagate --chrome / --no-chrome if explicitly set on the CLI
|
|
30
|
+
const chromeFlagOverride = getChromeFlagOverride();
|
|
31
|
+
if (chromeFlagOverride === true) {
|
|
32
|
+
flags.push('--chrome');
|
|
33
|
+
}
|
|
34
|
+
else if (chromeFlagOverride === false) {
|
|
35
|
+
flags.push('--no-chrome');
|
|
36
|
+
}
|
|
37
|
+
return flags.join(' ');
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Environment variables that must be explicitly forwarded to tmux-spawned
|
|
41
|
+
* teammates. Tmux may start a new login shell that doesn't inherit the
|
|
42
|
+
* parent's env, so we forward any that are set in the current process.
|
|
43
|
+
*/
|
|
44
|
+
const TEAMMATE_ENV_VARS = [
|
|
45
|
+
// API provider selection — without these, teammates default to firstParty
|
|
46
|
+
// and send requests to the wrong endpoint (GitHub issue #23561)
|
|
47
|
+
'CLAUDE_CODE_USE_BEDROCK',
|
|
48
|
+
'CLAUDE_CODE_USE_VERTEX',
|
|
49
|
+
'CLAUDE_CODE_USE_FOUNDRY',
|
|
50
|
+
// Custom API endpoint
|
|
51
|
+
'ANTHROPIC_BASE_URL',
|
|
52
|
+
// Config directory override
|
|
53
|
+
'CLAUDE_CONFIG_DIR',
|
|
54
|
+
// CCR marker — teammates need this for CCR-aware code paths. Auth finds
|
|
55
|
+
// its own way via /home/claude/.claude/remote/.oauth_token regardless;
|
|
56
|
+
// the FD env var wouldn't help (pipe FDs don't cross tmux).
|
|
57
|
+
'CLAUDE_CODE_REMOTE',
|
|
58
|
+
// Auto-memory gate (memdir/paths.ts) checks REMOTE && !MEMORY_DIR to
|
|
59
|
+
// disable memory on ephemeral CCR filesystems. Forwarding REMOTE alone
|
|
60
|
+
// would flip teammates to memory-off when the parent has it on.
|
|
61
|
+
'CLAUDE_CODE_REMOTE_MEMORY_DIR',
|
|
62
|
+
// Upstream proxy — the parent's MITM relay is reachable from teammates
|
|
63
|
+
// (same container network). Forward the proxy vars so teammates route
|
|
64
|
+
// customer-configured upstream traffic through the relay for credential
|
|
65
|
+
// injection. Without these, teammates bypass the proxy entirely.
|
|
66
|
+
'HTTPS_PROXY',
|
|
67
|
+
'https_proxy',
|
|
68
|
+
'HTTP_PROXY',
|
|
69
|
+
'http_proxy',
|
|
70
|
+
'NO_PROXY',
|
|
71
|
+
'no_proxy',
|
|
72
|
+
'SSL_CERT_FILE',
|
|
73
|
+
'NODE_EXTRA_CA_CERTS',
|
|
74
|
+
'REQUESTS_CA_BUNDLE',
|
|
75
|
+
'CURL_CA_BUNDLE',
|
|
76
|
+
];
|
|
77
|
+
/**
|
|
78
|
+
* Builds the `env KEY=VALUE ...` string for teammate spawn commands.
|
|
79
|
+
* Always includes CLAUDECODE=1 and CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1,
|
|
80
|
+
* plus any provider/config env vars that are set in the current process.
|
|
81
|
+
*/
|
|
82
|
+
export function buildInheritedEnvVars() {
|
|
83
|
+
const envVars = ['CLAUDECODE=1', 'CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1'];
|
|
84
|
+
for (const key of TEAMMATE_ENV_VARS) {
|
|
85
|
+
const value = process.env[key];
|
|
86
|
+
if (value !== undefined && value !== '') {
|
|
87
|
+
envVars.push(`${key}=${quote([value])}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return envVars.join(' ');
|
|
91
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{logForDebugging as
|
|
1
|
+
import{logForDebugging as e}from"../debug.js";import{addFunctionHook as t}from"../hooks/sessionHooks.js";import{applyPermissionUpdate as a}from"../permissions/PermissionUpdate.js";import{jsonStringify as o}from"../slowOperations.js";import{getTeammateColor as i}from"../teammate.js";import{createIdleNotification as m,getLastPeerDmSummary as s,writeToMailbox as n}from"../teammateMailbox.js";import{readTeamFile as r,setMemberActive as l}from"./teamHelpers.js";export function initializeTeammateHooks(d,p,f){const{teamName:g,agentId:h,agentName:c}=f,u=r(g);if(!u)return void e(`[TeammateInit] Team file not found for team: ${g}`);const w=u.leadAgentId;if(u.teamAllowedPaths&&u.teamAllowedPaths.length>0){e(`[TeammateInit] Found ${u.teamAllowedPaths.length} team-wide allowed path(s)`);for(const t of u.teamAllowedPaths){const o=t.path.startsWith("/")?`/${t.path}/**`:`${t.path}/**`;e(`[TeammateInit] Applying team permission: ${t.toolName} allowed in ${t.path} (rule: ${o})`),d(e=>({...e,toolPermissionContext:a(e.toolPermissionContext,{type:"addRules",rules:[{toolName:t.toolName,ruleContent:o}],behavior:"allow",destination:"session"})}))}}const T=u.members.find(e=>e.agentId===w),I=T?.name||"team-lead";h!==w?(e(`[TeammateInit] Registering Stop hook for teammate ${c} to notify leader ${I}`),t(d,p,"Stop","",async(t,a)=>{l(g,c,!1);const r=m(c,{idleReason:"available",summary:s(t)});return await n(I,{from:c,text:o(r),timestamp:(new Date).toISOString(),color:i()}),e(`[TeammateInit] Sent idle notification to leader ${I}`),!0},"Failed to send idle notification to team leader",{timeout:1e4})):e("[TeammateInit] This agent is the team leader - skipping idle notification hook")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{homedir as
|
|
1
|
+
import{homedir as o}from"os";import{join as D}from"path";import{logForDebugging as t}from"./debug.js";import{getPlatform as e}from"./platform.js";export function getSystemDirectories(s){const r=s?.platform??e(),n=s?.homedir??o(),O=s?.env??process.env,a={HOME:n,DESKTOP:D(n,"Desktop"),DOCUMENTS:D(n,"Documents"),DOWNLOADS:D(n,"Downloads")};switch(r){case"windows":{const o=O.USERPROFILE||n;return{HOME:n,DESKTOP:D(o,"Desktop"),DOCUMENTS:D(o,"Documents"),DOWNLOADS:D(o,"Downloads")}}case"linux":case"wsl":return{HOME:n,DESKTOP:O.XDG_DESKTOP_DIR||a.DESKTOP,DOCUMENTS:O.XDG_DOCUMENTS_DIR||a.DOCUMENTS,DOWNLOADS:O.XDG_DOWNLOAD_DIR||a.DOWNLOADS};default:return"unknown"===r&&t("Unknown platform detected, using default paths"),a}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createRequire as t}from"module";const e=t(import.meta.url);import{feature as o}from"bun:bundle";import{logEvent as r}from"../services/analytics/index.js";import{isBuiltInAgent as s}from"../tools/AgentTool/loadAgentsDir.js";import{isEnvTruthy as m}from"./envUtils.js";import{asSystemPrompt as n}from"./systemPromptType.js";export{asSystemPrompt}from"./systemPromptType.js";const i=o("PROACTIVE")||o("KAIROS")?e("../proactive/index.js"):null;export function buildEffectiveSystemPrompt({mainThreadAgentDefinition:t,toolUseContext:p,customSystemPrompt:a,defaultSystemPrompt:c,appendSystemPrompt:y,overrideSystemPrompt:u}){if(u)return n([u]);if(o("COORDINATOR_MODE")&&(m(process.env.CONTEXT_CODE_COORDINATOR_MODE)||m(process.env.CLAUDE_CODE_COORDINATOR_MODE))&&!t){const{getCoordinatorSystemPrompt:t}=e("../coordinator/coordinatorMode.js");return n([t(),...y?[y]:[]])}const O=t?s(t)?t.getSystemPrompt({toolUseContext:{options:p.options}}):t.getSystemPrompt():void 0;return t?.memory&&r("tengu_agent_memory_loaded",{..."ant"===process.env.USER_TYPE&&{agent_type:t.agentType},scope:t.memory,source:"main-thread"}),O&&(o("PROACTIVE")||o("KAIROS"))&&i?.isProactiveActive()?n([...c,`\n# Custom Agent Instructions\n${O}`,...y?[y]:[]]):n([...O?[O]:a?[a]:c,...y?[y]:[]])}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
let e;export function getSystemThemeName(){return void 0===e&&(e=function(){const e=process.env.COLORFGBG;if(!e)return;const t=e.split(";"),n=t[t.length-1];if(void 0===n||""===n)return;const o=Number(n);return!Number.isInteger(o)||o<0||o>15?void 0:o<=6||8===o?"dark":"light"}()??"dark"),e}export function setCachedSystemTheme(t){e=t}export function resolveThemeSetting(e){return"auto"===e?getSystemThemeName():e}export function themeFromOscColor(e){const t=function(e){const t=/^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(e);if(t)return{r:hexComponent(t[1]),g:hexComponent(t[2]),b:hexComponent(t[3])};const n=/^#([0-9a-f]+)$/i.exec(e);if(n&&n[1].length%3==0){const e=n[1],t=e.length/3;return{r:hexComponent(e.slice(0,t)),g:hexComponent(e.slice(t,2*t)),b:hexComponent(e.slice(2*t))}}
|
|
1
|
+
let e;export function getSystemThemeName(){return void 0===e&&(e=function(){const e=process.env.COLORFGBG;if(!e)return;const t=e.split(";"),n=t[t.length-1];if(void 0===n||""===n)return;const o=Number(n);return!Number.isInteger(o)||o<0||o>15?void 0:o<=6||8===o?"dark":"light"}()??"dark"),e}export function setCachedSystemTheme(t){e=t}export function resolveThemeSetting(e){return"auto"===e?getSystemThemeName():e}export function themeFromOscColor(e){const t=function(e){const t=/^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(e);if(t)return{r:hexComponent(t[1]),g:hexComponent(t[2]),b:hexComponent(t[3])};const n=/^#([0-9a-f]+)$/i.exec(e);if(n&&n[1].length%3==0){const e=n[1],t=e.length/3;return{r:hexComponent(e.slice(0,t)),g:hexComponent(e.slice(t,2*t)),b:hexComponent(e.slice(2*t))}}}(e);if(t)return.2126*t.r+.7152*t.g+.0722*t.b>.5?"light":"dark"}function hexComponent(e){const t=16**e.length-1;return parseInt(e,16)/t}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{unlink as t}from"fs/promises";import{CircularBuffer as s}from"../CircularBuffer.js";import{logForDebugging as e}from"../debug.js";import{readFileRange as i,tailFile as
|
|
1
|
+
import{unlink as t}from"fs/promises";import{CircularBuffer as s}from"../CircularBuffer.js";import{logForDebugging as e}from"../debug.js";import{readFileRange as i,tailFile as u}from"../fsOperations.js";import{getMaxOutputLength as a}from"../shell/outputLimits.js";import{safeJoinLines as n}from"../stringUtils.js";import{DiskTaskOutput as r,getTaskOutputPath as h}from"./diskOutput.js";export class TaskOutput{taskId;path;stdoutToFile;#t="";#s="";#e=null;#i=new s(1e3);#u=0;#a=0;#n;#r;#h=!1;#l=0;static#o=new Map;static#p=new Map;static#d=null;constructor(t,s,e=!1,i=8388608){this.taskId=t,this.path=h(t),this.stdoutToFile=e,this.#n=i,this.#r=s,e&&s&&TaskOutput.#o.set(t,this)}static startPolling(t){const s=TaskOutput.#o.get(t);s&&s.#r&&(TaskOutput.#p.set(t,s),TaskOutput.#d||(TaskOutput.#d=setInterval(TaskOutput.#c,1e3),TaskOutput.#d.unref()))}static stopPolling(t){TaskOutput.#p.delete(t),0===TaskOutput.#p.size&&TaskOutput.#d&&(clearInterval(TaskOutput.#d),TaskOutput.#d=null)}static#c(){for(const[,t]of TaskOutput.#p)t.#r&&u(t.path,4096).then(({content:s,bytesRead:e,bytesTotal:i})=>{if(!t.#r)return;if(!s)return void t.#r("","",t.#u,i,!1);let u=s.length,a=0,n=0,r=0;for(;u>0;)u=s.lastIndexOf("\n",u-1),r++,5===r&&(a=u<=0?0:u+1),100===r&&(n=u<=0?0:u+1);const h=e>=i?r:Math.max(t.#u,Math.round(i/e*r));t.#u=h,t.#a=i,t.#r(s.slice(a),s.slice(n),h,i,e<i)},()=>{})}writeStdout(t){this.#f(t,!1)}writeStderr(t){this.#f(t,!0)}#f(t,s){this.#a+=t.length,this.#g(t),this.#e?this.#e.append(s?`[stderr] ${t}`:t):this.#t.length+this.#s.length+t.length>this.#n?this.#k(s?t:null,s?null:t):s?this.#s+=t:this.#t+=t}#g(t){let s=0;const e=[];let i=0,u=t.length;for(;u>0;){const a=t.lastIndexOf("\n",u-1);if(-1===a)break;if(s++,e.length<100&&i<4096){const s=u-a-1;if(s>0&&s<=4096-i){const n=t.slice(a+1,u);n.trim()&&(e.push(Buffer.from(n).toString()),i+=s)}}u=a}this.#u+=s;for(let t=e.length-1;t>=0;t--)this.#i.add(e[t]);if(this.#r&&e.length>0){const t=this.#i.getRecent(5);this.#r(n(t,"\n"),n(this.#i.getRecent(100),"\n"),this.#u,this.#a,null!==this.#e)}}#k(t,s){this.#e=new r(this.taskId),this.#t&&(this.#e.append(this.#t),this.#t=""),this.#s&&(this.#e.append(`[stderr] ${this.#s}`),this.#s=""),s&&this.#e.append(s),t&&this.#e.append(`[stderr] ${t}`)}async getStdout(){if(this.stdoutToFile)return this.#O();if(this.#e){const t=this.#i.getRecent(5),s=n(t,"\n"),e=`\nOutput truncated (${Math.round(this.#a/1024)}KB total). Full output saved to: ${this.path}`;return s?s+e:e.trimStart()}return this.#t}async#O(){const t=a();try{const s=await i(this.path,0,t);if(!s)return this.#h=!0,"";const{content:e,bytesRead:u,bytesTotal:a}=s;return this.#l=a,this.#h=a<=u,e}catch(t){const s=t instanceof Error&&"code"in t?String(t.code):"unknown";return e(`TaskOutput.#readStdoutFromFile: failed to read ${this.path} (${s}): ${t}`),`<bash output unavailable: output file ${this.path} could not be read (${s}). This usually means another Context Code process in the same project deleted it during startup cleanup.>`}}getStderr(){return this.#e?"":this.#s}get isOverflowed(){return null!==this.#e}get totalLines(){return this.#u}get totalBytes(){return this.#a}get outputFileRedundant(){return this.#h}get outputFileSize(){return this.#l}spillToDisk(){this.#e||this.#k(null,null)}async flush(){await(this.#e?.flush())}async deleteOutputFile(){try{await t(this.path)}catch{}}clear(){this.#t="",this.#s="",this.#i.clear(),this.#r=null,this.#e?.cancel(),TaskOutput.stopPolling(this.taskId),TaskOutput.#o.delete(this.taskId)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{constants as t}from"fs";import{mkdir as
|
|
1
|
+
import{constants as t}from"fs";import{mkdir as s,open as e,stat as a,symlink as n,unlink as r}from"fs/promises";import{join as i}from"path";import{getSessionId as u}from"../../bootstrap/state.js";import{getErrnoCode as o}from"../errors.js";import{readFileRange as c,tailFile as p}from"../fsOperations.js";import{logError as l}from"../log.js";import{getProjectTempDir as f}from"../permissions/filesystem.js";const h=t.O_NOFOLLOW??0;export const MAX_TASK_OUTPUT_BYTES=5368709120;export const MAX_TASK_OUTPUT_BYTES_DISPLAY="5GB";let O;export function getTaskOutputDir(){return void 0===O&&(O=i(f(),u(),"tasks")),O}export function _resetTaskOutputDirForTest(){O=void 0}async function ensureOutputDir(){await s(getTaskOutputDir(),{recursive:!0})}export function getTaskOutputPath(t){return i(getTaskOutputDir(),`${t}.output`)}const T=new Set;function track(t){return T.add(t),t.finally(()=>T.delete(t)).catch(()=>{}),t}export class DiskTaskOutput{#t;#s=null;#e=[];#a=0;#n=!1;#r=null;#i=null;constructor(t){this.#t=getTaskOutputPath(t)}append(t){this.#n||(this.#a+=t.length,this.#a>5368709120?(this.#n=!0,this.#e.push("\n[output truncated: exceeded 5GB disk cap]\n")):this.#e.push(t),this.#r||(this.#r=new Promise(t=>{this.#i=t}),track(this.#u())))}flush(){return this.#r??Promise.resolve()}cancel(){this.#e.length=0}async#o(){for(;;){try{for(this.#s||(await ensureOutputDir(),this.#s=await e(this.#t,"win32"===process.platform?"a":t.O_WRONLY|t.O_APPEND|t.O_CREAT|h));await this.#c(),0!==this.#e.length;);}finally{if(this.#s){const t=this.#s;this.#s=null,await t.close()}}if(!this.#e.length)break}}#c(){return this.#s.appendFile(this.#p())}#p(){const t=this.#e.splice(0,this.#e.length);let s=0;for(const e of t)s+=Buffer.byteLength(e,"utf8");const e=Buffer.allocUnsafe(s);let a=0;for(const s of t)a+=e.write(s,a,"utf8");return e}async#u(){try{await this.#o()}catch(t){if(l(t),this.#e.length>0)try{await this.#o()}catch(t){l(t)}}finally{const t=this.#i;this.#r=null,this.#i=null,t()}}}const k=new Map;export async function _clearOutputsForTest(){for(const t of k.values())t.cancel();for(;T.size>0;)await Promise.allSettled([...T]);k.clear()}export function appendTaskOutput(t,s){(function(t){let s=k.get(t);return s||(s=new DiskTaskOutput(t),k.set(t,s)),s})(t).append(s)}export async function flushTaskOutput(t){const s=k.get(t);s&&await s.flush()}export function evictTaskOutput(t){return track((async()=>{const s=k.get(t);s&&(await s.flush(),k.delete(t))})())}export async function getTaskOutputDelta(t,s,e=8388608){try{const a=await c(getTaskOutputPath(t),s,e);return a?{content:a.content,newOffset:s+a.bytesRead}:{content:"",newOffset:s}}catch(t){return"ENOENT"===o(t)||l(t),{content:"",newOffset:s}}}export async function getTaskOutput(t,s=8388608){try{const{content:e,bytesTotal:a,bytesRead:n}=await p(getTaskOutputPath(t),s);return a>n?`[${Math.round((a-n)/1024)}KB of earlier output omitted]\n${e}`:e}catch(t){return"ENOENT"===o(t)||l(t),""}}export async function getTaskOutputSize(t){try{return(await a(getTaskOutputPath(t))).size}catch(t){return"ENOENT"===o(t)||l(t),0}}export async function cleanupTaskOutput(t){const s=k.get(t);s&&(s.cancel(),k.delete(t));try{await r(getTaskOutputPath(t))}catch(t){if("ENOENT"===o(t))return;l(t)}}export function initTaskOutput(s){return track((async()=>{await ensureOutputDir();const a=getTaskOutputPath(s),n=await e(a,"win32"===process.platform?"wx":t.O_WRONLY|t.O_CREAT|t.O_EXCL|h);return await n.close(),a})())}export function initTaskOutputAsSymlink(t,s){return track((async()=>{try{await ensureOutputDir();const e=getTaskOutputPath(t);try{await n(s,e)}catch{await r(e),await n(s,e)}return e}catch(s){return l(s),initTaskOutput(t)}})())}
|
package/dist/src/utils/tasks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir as t,readdir as a,readFile as e,unlink as s,writeFile as n}from"fs/promises";import{join as r}from"path";import{z as i}from"zod/v4";import{getIsNonInteractiveSession as o,getSessionId as c}from"../bootstrap/state.js";import{uniq as u}from"./array.js";import{logForDebugging as l}from"./debug.js";import{getClaudeConfigHomeDir as k,getTeamsDir as d,isEnvTruthy as
|
|
1
|
+
import{mkdir as t,readdir as a,readFile as e,unlink as s,writeFile as n}from"fs/promises";import{join as r}from"path";import{z as i}from"zod/v4";import{getIsNonInteractiveSession as o,getSessionId as c}from"../bootstrap/state.js";import{uniq as u}from"./array.js";import{logForDebugging as l}from"./debug.js";import{getClaudeConfigHomeDir as k,getTeamsDir as d,isEnvTruthy as m}from"./envUtils.js";import{errorMessage as f,getErrnoCode as g}from"./errors.js";import{lazySchema as p}from"./lazySchema.js";import*as T from"./lockfile.js";import{logError as w}from"./log.js";import{createSignal as h}from"./signal.js";import{jsonParse as y,jsonStringify as b}from"./slowOperations.js";import{getTeamName as _}from"./teammate.js";import{getTeammateContext as S}from"./teammateContext.js";const x=h();let j;export function setLeaderTeamName(t){j!==t&&(j=t,notifyTasksUpdated())}export function clearLeaderTeamName(){void 0!==j&&(j=void 0,notifyTasksUpdated())}export const onTasksUpdated=x.subscribe;export function notifyTasksUpdated(){try{x.emit()}catch{}}export const TASK_STATUSES=["pending","in_progress","completed"];export const TaskStatusSchema=p(()=>i.enum(["pending","in_progress","completed"]));export const TaskSchema=p(()=>i.object({id:i.string(),subject:i.string(),description:i.string(),activeForm:i.string().optional(),owner:i.string().optional(),status:TaskStatusSchema(),blocks:i.array(i.string()),blockedBy:i.array(i.string()),metadata:i.record(i.string(),i.unknown()).optional()}));const E={retries:{retries:30,minTimeout:5,maxTimeout:100}};function getHighWaterMarkPath(t){return r(getTasksDir(t),".highwatermark")}async function readHighWaterMark(t){const a=getHighWaterMarkPath(t);try{const t=(await e(a,"utf-8")).trim(),s=parseInt(t,10);return isNaN(s)?0:s}catch{return 0}}async function writeHighWaterMark(t,a){const e=getHighWaterMarkPath(t);await n(e,String(a))}export function isTodoV2Enabled(){return!(!m(process.env.CONTEXT_CODE_ENABLE_TASKS)&&!m(process.env.CLAUDE_CODE_ENABLE_TASKS)&&o())}export async function resetTaskList(t){const e=getTasksDir(t),n=await ensureTaskListLockFile(t);let i;try{i=await T.lock(n,E);const o=await findHighestTaskIdFromFiles(t);let c;o>0&&o>await readHighWaterMark(t)&&await writeHighWaterMark(t,o);try{c=await a(e)}catch{c=[]}for(const t of c)if(t.endsWith(".json")&&!t.startsWith(".")){const a=r(e,t);try{await s(a)}catch{}}notifyTasksUpdated()}finally{i&&await i()}}export function getTaskListId(){const t=process.env.CONTEXT_CODE_TASK_LIST_ID??process.env.CLAUDE_CODE_TASK_LIST_ID;if(t)return t;const a=S();return a?a.teamName:_()||j||c()}export function sanitizePathComponent(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}export function getTasksDir(t){return r(k(),"tasks",sanitizePathComponent(t))}export function getTaskPath(t,a){return r(getTasksDir(t),`${sanitizePathComponent(a)}.json`)}export async function ensureTasksDir(a){const e=getTasksDir(a);try{await t(e,{recursive:!0})}catch{}}async function findHighestTaskIdFromFiles(t){const e=getTasksDir(t);let s;try{s=await a(e)}catch{return 0}let n=0;for(const t of s){if(!t.endsWith(".json"))continue;const a=parseInt(t.replace(".json",""),10);!isNaN(a)&&a>n&&(n=a)}return n}export async function createTask(t,a){const e=await ensureTaskListLockFile(t);let s;try{s=await T.lock(e,E);const r=await async function(t){const[a,e]=await Promise.all([findHighestTaskIdFromFiles(t),readHighWaterMark(t)]);return Math.max(a,e)}(t),i=String(r+1),o={id:i,...a},c=getTaskPath(t,i);return await n(c,b(o,null,2)),notifyTasksUpdated(),i}finally{s&&await s()}}export async function getTask(t,a){const s=getTaskPath(t,a);try{const t=await e(s,"utf-8"),n=y(t);"ant"===process.env.USER_TYPE&&("open"===n.status?n.status="pending":"resolved"===n.status?n.status="completed":n.status&&["planning","implementing","reviewing","verifying"].includes(n.status)&&(n.status="in_progress"));const r=TaskSchema().safeParse(n);return r.success?r.data:(l(`[Tasks] Task ${a} failed schema validation: ${r.error.message}`),null)}catch(t){return"ENOENT"===g(t)||(l(`[Tasks] Failed to read task ${a}: ${f(t)}`),w(t)),null}}async function updateTaskUnsafe(t,a,e){const s=await getTask(t,a);if(!s)return null;const r={...s,...e,id:a},i=getTaskPath(t,a);return await n(i,b(r,null,2)),notifyTasksUpdated(),r}export async function updateTask(t,a,e){const s=getTaskPath(t,a);if(!await getTask(t,a))return null;let n;try{return n=await T.lock(s,E),await updateTaskUnsafe(t,a,e)}finally{await(n?.())}}export async function deleteTask(t,a){const e=getTaskPath(t,a);try{const n=parseInt(a,10);isNaN(n)||n>await readHighWaterMark(t)&&await writeHighWaterMark(t,n);try{await s(e)}catch(t){if("ENOENT"===g(t))return!1;throw t}const r=await listTasks(t);for(const e of r){const s=e.blocks.filter(t=>t!==a),n=e.blockedBy.filter(t=>t!==a);s.length===e.blocks.length&&n.length===e.blockedBy.length||await updateTask(t,e.id,{blocks:s,blockedBy:n})}return notifyTasksUpdated(),!0}catch{return!1}}export async function listTasks(t){const e=getTasksDir(t);let s;try{s=await a(e)}catch{return[]}const n=s.filter(t=>t.endsWith(".json")).map(t=>t.replace(".json",""));return(await Promise.all(n.map(a=>getTask(t,a)))).filter(t=>null!==t)}export async function blockTask(t,a,e){const[s,n]=await Promise.all([getTask(t,a),getTask(t,e)]);return!(!s||!n||(s.blocks.includes(e)||await updateTask(t,a,{blocks:[...s.blocks,e]}),n.blockedBy.includes(a)||await updateTask(t,e,{blockedBy:[...n.blockedBy,a]}),0))}async function ensureTaskListLockFile(t){await ensureTasksDir(t);const a=function(t){return r(getTasksDir(t),".lock")}(t);try{await n(a,"",{flag:"wx"})}catch{}return a}export async function claimTask(t,a,e,s={}){const n=getTaskPath(t,a);if(!await getTask(t,a))return{success:!1,reason:"task_not_found"};if(s.checkAgentBusy)return async function(t,a,e){const s=await ensureTaskListLockFile(t);let n;try{n=await T.lock(s,E);const r=await listTasks(t),i=r.find(t=>t.id===a);if(!i)return{success:!1,reason:"task_not_found"};if(i.owner&&i.owner!==e)return{success:!1,reason:"already_claimed",task:i};if("completed"===i.status)return{success:!1,reason:"already_resolved",task:i};const o=new Set(r.filter(t=>"completed"!==t.status).map(t=>t.id)),c=i.blockedBy.filter(t=>o.has(t));if(c.length>0)return{success:!1,reason:"blocked",task:i,blockedByTasks:c};const u=r.filter(t=>"completed"!==t.status&&t.owner===e&&t.id!==a);return u.length>0?{success:!1,reason:"agent_busy",task:i,busyWithTasks:u.map(t=>t.id)}:{success:!0,task:await updateTask(t,a,{owner:e})}}catch(t){return l(`[Tasks] Failed to claim task ${a} with busy check: ${f(t)}`),w(t),{success:!1,reason:"task_not_found"}}finally{n&&await n()}}(t,a,e);let r;try{r=await T.lock(n,E);const s=await getTask(t,a);if(!s)return{success:!1,reason:"task_not_found"};if(s.owner&&s.owner!==e)return{success:!1,reason:"already_claimed",task:s};if("completed"===s.status)return{success:!1,reason:"already_resolved",task:s};const i=await listTasks(t),o=new Set(i.filter(t=>"completed"!==t.status).map(t=>t.id)),c=s.blockedBy.filter(t=>o.has(t));return c.length>0?{success:!1,reason:"blocked",task:s,blockedByTasks:c}:{success:!0,task:await updateTaskUnsafe(t,a,{owner:e})}}catch(t){return l(`[Tasks] Failed to claim task ${a}: ${f(t)}`),w(t),{success:!1,reason:"task_not_found"}}finally{r&&await r()}}function sanitizeName(t){return t.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}export async function getAgentStatuses(t){const a=await async function(t){const a=d(),s=r(a,sanitizeName(t),"config.json");try{const t=await e(s,"utf-8"),a=y(t);return{leadAgentId:a.leadAgentId,members:a.members.map(t=>({agentId:t.agentId,name:t.name,agentType:t.agentType}))}}catch(a){return"ENOENT"===g(a)||l(`[Tasks] Failed to read team file for ${t}: ${f(a)}`),null}}(t);if(!a)return null;const s=sanitizeName(t),n=await listTasks(s),i=new Map;for(const t of n)if("completed"!==t.status&&t.owner){const a=i.get(t.owner)||[];a.push(t.id),i.set(t.owner,a)}return a.members.map(t=>{const a=i.get(t.name)||[],e=i.get(t.agentId)||[],s=u([...a,...e]);return{agentId:t.agentId,name:t.name,agentType:t.agentType,status:0===s.length?"idle":"busy",currentTasks:s}})}export async function unassignTeammateTasks(t,a,e,s){const n=(await listTasks(t)).filter(t=>"completed"!==t.status&&(t.owner===a||t.owner===e));for(const a of n)await updateTask(t,a.id,{owner:void 0,status:"pending"});n.length>0&&l(`[Tasks] Unassigned ${n.length} task(s) from ${e}`);let r=`${e} ${"terminated"===s?"was terminated":"has shut down"}.`;if(n.length>0){const t=n.map(t=>`#${t.id} "${t.subject}"`).join(", ");r+=` ${n.length} task(s) were unassigned: ${t}. Use TaskList to check availability and TaskUpdate with owner to reassign them to idle teammates.`}return{unassignedTasks:n.map(t=>({id:t.id,subject:t.subject})),notificationMessage:r}}export const DEFAULT_TASKS_MODE_TASK_LIST_ID="tasklist";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isPaneBackend as e}from"./swarm/backends/types.js";import{readTeamFile as t}from"./swarm/teamHelpers.js";export function getTeammateStatuses(
|
|
1
|
+
import{isPaneBackend as e}from"./swarm/backends/types.js";import{readTeamFile as t}from"./swarm/teamHelpers.js";export function getTeammateStatuses(a){const n=t(a);if(!n)return[];const d=new Set(n.hiddenPaneIds??[]),o=[];for(const t of n.members){if("team-lead"===t.name)continue;const a=!1!==t.isActive?"running":"idle";o.push({name:t.name,agentId:t.agentId,agentType:t.agentType,model:t.model,prompt:t.prompt,status:a,color:t.color,tmuxPaneId:t.tmuxPaneId,cwd:t.cwd,worktreePath:t.worktreePath,isHidden:d.has(t.tmuxPaneId),backendType:t.backendType&&e(t.backendType)?t.backendType:void 0,mode:t.mode})}return o}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isTeamMemFile as e}from"../memdir/teamMemPaths.js";import{FILE_EDIT_TOOL_NAME as t}from"../tools/FileEditTool/constants.js";import{FILE_WRITE_TOOL_NAME as r}from"../tools/FileWriteTool/prompt.js";export{e as isTeamMemFile};export function isTeamMemorySearch(t){const r=t;return!!r&&!(!r.path||!e(r.path))}export function isTeamMemoryWriteOrEdit(o,m){if(o!==r&&o!==t)return!1;const i=m,
|
|
1
|
+
import{isTeamMemFile as e}from"../memdir/teamMemPaths.js";import{FILE_EDIT_TOOL_NAME as t}from"../tools/FileEditTool/constants.js";import{FILE_WRITE_TOOL_NAME as r}from"../tools/FileWriteTool/prompt.js";export{e as isTeamMemFile};export function isTeamMemorySearch(t){const r=t;return!!r&&!(!r.path||!e(r.path))}export function isTeamMemoryWriteOrEdit(o,m){if(o!==r&&o!==t)return!1;const i=m,a=i?.file_path??i?.path;return void 0!==a&&e(a)}export function appendTeamMemorySummaryParts(e,t,r){const o=e.teamMemoryReadCount??0,m=e.teamMemorySearchCount??0,i=e.teamMemoryWriteCount??0;if(o>0){const e=t?0===r.length?"Recalling":"recalling":0===r.length?"Recalled":"recalled";r.push(`${e} ${o} team ${1===o?"memory":"memories"}`)}if(m>0){const e=t?0===r.length?"Searching":"searching":0===r.length?"Searched":"searched";r.push(`${e} team memories`)}if(i>0){const e=t?0===r.length?"Writing":"writing":0===r.length?"Wrote":"wrote";r.push(`${e} ${i} team ${1===i?"memory":"memories"}`)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir as e,readFile as t,writeFile as a}from"fs/promises";import{join as s}from"path";import{z as o}from"zod/v4";import{TEAMMATE_MESSAGE_TAG as r}from"../constants/xml.js";import{PermissionModeSchema as n}from"../entrypoints/sdk/coreSchemas.js";import{SEND_MESSAGE_TOOL_NAME as i}from"../tools/SendMessageTool/constants.js";import{generateRequestId as m}from"./agentId.js";import{count as u}from"./array.js";import{logForDebugging as c}from"./debug.js";import{getTeamsDir as l}from"./envUtils.js";import{getErrnoCode as p}from"./errors.js";import{lazySchema as d}from"./lazySchema.js";import*as f from"./lockfile.js";import{logError as g}from"./log.js";import{jsonParse as x,jsonStringify as y}from"./slowOperations.js";import{TEAM_LEAD_NAME as M}from"./swarm/constants.js";import{sanitizePathComponent as h}from"./tasks.js";import{getAgentName as b,getTeammateColor as w,getTeamName as _}from"./teammate.js";const k={retries:{retries:10,minTimeout:5,maxTimeout:100}};export function getInboxPath(e,t){const a=t||_()||"default",o=h(a),r=h(e),n=s(l(),o,"inboxes"),i=s(n,`${r}.json`);return c(`[TeammateMailbox] getInboxPath: agent=${e}, team=${a}, fullPath=${i}`),i}export async function readMailbox(e,a){const s=getInboxPath(e,a);c(`[TeammateMailbox] readMailbox: path=${s}`);try{const e=await t(s,"utf-8"),a=x(e);return c(`[TeammateMailbox] readMailbox: read ${a.length} message(s)`),a}catch(t){return"ENOENT"===p(t)?(c("[TeammateMailbox] readMailbox: file does not exist"),[]):(c(`Failed to read inbox for ${e}: ${t}`),g(t),[])}}export async function readUnreadMessages(e,t){const a=await readMailbox(e,t),s=a.filter(e=>!e.read);return c(`[TeammateMailbox] readUnreadMessages: ${s.length} unread of ${a.length} total`),s}export async function writeToMailbox(t,o,r){await async function(t){const a=t||_()||"default",o=h(a),r=s(l(),o,"inboxes");await e(r,{recursive:!0}),c(`[TeammateMailbox] Ensured inbox directory: ${r}`)}(r);const n=getInboxPath(t,r),i=`${n}.lock`;c(`[TeammateMailbox] writeToMailbox: recipient=${t}, from=${o.from}, path=${n}`);try{await a(n,"[]",{encoding:"utf-8",flag:"wx"}),c("[TeammateMailbox] writeToMailbox: created new inbox file")}catch(e){if("EEXIST"!==p(e))return c(`[TeammateMailbox] writeToMailbox: failed to create inbox file: ${e}`),void g(e)}let m;try{m=await f.lock(n,{lockfilePath:i,...k});const e=await readMailbox(t,r),s={...o,read:!1};e.push(s),await a(n,y(e,null,2),"utf-8"),c(`[TeammateMailbox] Wrote message to ${t}'s inbox from ${o.from}`)}catch(e){c(`Failed to write to inbox for ${t}: ${e}`),g(e)}finally{m&&await m()}}export async function markMessageAsReadByIndex(e,t,s){const o=getInboxPath(e,t);c(`[TeammateMailbox] markMessageAsReadByIndex called: agentName=${e}, teamName=${t}, index=${s}, path=${o}`);const r=`${o}.lock`;let n;try{c("[TeammateMailbox] markMessageAsReadByIndex: acquiring lock..."),n=await f.lock(o,{lockfilePath:r,...k}),c("[TeammateMailbox] markMessageAsReadByIndex: lock acquired");const i=await readMailbox(e,t);if(c(`[TeammateMailbox] markMessageAsReadByIndex: read ${i.length} messages after lock`),s<0||s>=i.length)return void c(`[TeammateMailbox] markMessageAsReadByIndex: index ${s} out of bounds (${i.length} messages)`);const m=i[s];if(!m||m.read)return void c("[TeammateMailbox] markMessageAsReadByIndex: message already read or missing");i[s]={...m,read:!0},await a(o,y(i,null,2),"utf-8"),c(`[TeammateMailbox] markMessageAsReadByIndex: marked message at index ${s} as read`)}catch(t){if("ENOENT"===p(t))return void c(`[TeammateMailbox] markMessageAsReadByIndex: file does not exist at ${o}`);c(`[TeammateMailbox] markMessageAsReadByIndex FAILED for ${e}: ${t}`),g(t)}finally{n&&(await n(),c("[TeammateMailbox] markMessageAsReadByIndex: lock released"))}}export async function markMessagesAsRead(e,t){const s=getInboxPath(e,t);c(`[TeammateMailbox] markMessagesAsRead called: agentName=${e}, teamName=${t}, path=${s}`);const o=`${s}.lock`;let r;try{c("[TeammateMailbox] markMessagesAsRead: acquiring lock..."),r=await f.lock(s,{lockfilePath:o,...k}),c("[TeammateMailbox] markMessagesAsRead: lock acquired");const n=await readMailbox(e,t);if(c(`[TeammateMailbox] markMessagesAsRead: read ${n.length} messages after lock`),0===n.length)return void c("[TeammateMailbox] markMessagesAsRead: no messages to mark");const i=u(n,e=>!e.read);c(`[TeammateMailbox] markMessagesAsRead: ${i} unread of ${n.length} total`);for(const e of n)e.read=!0;await a(s,y(n,null,2),"utf-8"),c(`[TeammateMailbox] markMessagesAsRead: WROTE ${i} message(s) as read to ${s}`)}catch(t){if("ENOENT"===p(t))return void c(`[TeammateMailbox] markMessagesAsRead: file does not exist at ${s}`);c(`[TeammateMailbox] markMessagesAsRead FAILED for ${e}: ${t}`),g(t)}finally{r&&(await r(),c("[TeammateMailbox] markMessagesAsRead: lock released"))}}export async function clearMailbox(e,t){const s=getInboxPath(e,t);try{await a(s,"[]",{encoding:"utf-8",flag:"r+"}),c(`[TeammateMailbox] Cleared inbox for ${e}`)}catch(t){if("ENOENT"===p(t))return;c(`Failed to clear inbox for ${e}: ${t}`),g(t)}}export function formatTeammateMessages(e){return e.map(e=>{const t=e.color?` color="${e.color}"`:"",a=e.summary?` summary="${e.summary}"`:"";return`<${r} teammate_id="${e.from}"${t}${a}>\n${e.text}\n</${r}>`}).join("\n\n")}export function createIdleNotification(e,t){return{type:"idle_notification",from:e,timestamp:(new Date).toISOString(),idleReason:t?.idleReason,summary:t?.summary,completedTaskId:t?.completedTaskId,completedStatus:t?.completedStatus,failureReason:t?.failureReason}}export function isIdleNotification(e){try{const t=x(e);if(t&&"idle_notification"===t.type)return t}catch{}return null}export function createPermissionRequestMessage(e){return{type:"permission_request",request_id:e.request_id,agent_id:e.agent_id,tool_name:e.tool_name,tool_use_id:e.tool_use_id,description:e.description,input:e.input,permission_suggestions:e.permission_suggestions||[]}}export function createPermissionResponseMessage(e){return"error"===e.subtype?{type:"permission_response",request_id:e.request_id,subtype:"error",error:e.error||"Permission denied"}:{type:"permission_response",request_id:e.request_id,subtype:"success",response:{updated_input:e.updated_input,permission_updates:e.permission_updates}}}export function isPermissionRequest(e){try{const t=x(e);if(t&&"permission_request"===t.type)return t}catch{}return null}export function isPermissionResponse(e){try{const t=x(e);if(t&&"permission_response"===t.type)return t}catch{}return null}export function createSandboxPermissionRequestMessage(e){return{type:"sandbox_permission_request",requestId:e.requestId,workerId:e.workerId,workerName:e.workerName,workerColor:e.workerColor,hostPattern:{host:e.host},createdAt:Date.now()}}export function createSandboxPermissionResponseMessage(e){return{type:"sandbox_permission_response",requestId:e.requestId,host:e.host,allow:e.allow,timestamp:(new Date).toISOString()}}export function isSandboxPermissionRequest(e){try{const t=x(e);if(t&&"sandbox_permission_request"===t.type)return t}catch{}return null}export function isSandboxPermissionResponse(e){try{const t=x(e);if(t&&"sandbox_permission_response"===t.type)return t}catch{}return null}export const PlanApprovalRequestMessageSchema=d(()=>o.object({type:o.literal("plan_approval_request"),from:o.string(),timestamp:o.string(),planFilePath:o.string(),planContent:o.string(),requestId:o.string()}));export const PlanApprovalResponseMessageSchema=d(()=>o.object({type:o.literal("plan_approval_response"),requestId:o.string(),approved:o.boolean(),feedback:o.string().optional(),timestamp:o.string(),permissionMode:n().optional()}));export const ShutdownRequestMessageSchema=d(()=>o.object({type:o.literal("shutdown_request"),requestId:o.string(),from:o.string(),reason:o.string().optional(),timestamp:o.string()}));export const ShutdownApprovedMessageSchema=d(()=>o.object({type:o.literal("shutdown_approved"),requestId:o.string(),from:o.string(),timestamp:o.string(),paneId:o.string().optional(),backendType:o.string().optional()}));export const ShutdownRejectedMessageSchema=d(()=>o.object({type:o.literal("shutdown_rejected"),requestId:o.string(),from:o.string(),reason:o.string(),timestamp:o.string()}));export function createShutdownRequestMessage(e){return{type:"shutdown_request",requestId:e.requestId,from:e.from,reason:e.reason,timestamp:(new Date).toISOString()}}export function createShutdownApprovedMessage(e){return{type:"shutdown_approved",requestId:e.requestId,from:e.from,timestamp:(new Date).toISOString(),paneId:e.paneId,backendType:e.backendType}}export function createShutdownRejectedMessage(e){return{type:"shutdown_rejected",requestId:e.requestId,from:e.from,reason:e.reason,timestamp:(new Date).toISOString()}}export async function sendShutdownRequestToMailbox(e,t,a){const s=t||_(),o=b()||M,r=m("shutdown",e),n=createShutdownRequestMessage({requestId:r,from:o,reason:a});return await writeToMailbox(e,{from:o,text:y(n),timestamp:(new Date).toISOString(),color:w()},s),{requestId:r,target:e}}export function isShutdownRequest(e){try{const t=ShutdownRequestMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isPlanApprovalRequest(e){try{const t=PlanApprovalRequestMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isShutdownApproved(e){try{const t=ShutdownApprovedMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isShutdownRejected(e){try{const t=ShutdownRejectedMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isPlanApprovalResponse(e){try{const t=PlanApprovalResponseMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isTaskAssignment(e){try{const t=x(e);if(t&&"task_assignment"===t.type)return t}catch{}return null}export function isTeamPermissionUpdate(e){try{const t=x(e);if(t&&"team_permission_update"===t.type)return t}catch{}return null}export const ModeSetRequestMessageSchema=d(()=>o.object({type:o.literal("mode_set_request"),mode:n(),from:o.string()}));export function createModeSetRequestMessage(e){return{type:"mode_set_request",mode:e.mode,from:e.from}}export function isModeSetRequest(e){try{const t=ModeSetRequestMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isStructuredProtocolMessage(e){try{const t=x(e);if(!t||"object"!=typeof t||!("type"in t))return!1;const a=t.type;return"permission_request"===a||"permission_response"===a||"sandbox_permission_request"===a||"sandbox_permission_response"===a||"shutdown_request"===a||"shutdown_approved"===a||"team_permission_update"===a||"mode_set_request"===a||"plan_approval_request"===a||"plan_approval_response"===a}catch{return!1}}export async function markMessagesAsReadByPredicate(e,t,s){const o=getInboxPath(e,s),r=`${o}.lock`;let n;try{n=await f.lock(o,{lockfilePath:r,...k});const i=await readMailbox(e,s);if(0===i.length)return;const m=i.map(e=>!e.read&&t(e)?{...e,read:!0}:e);await a(o,y(m,null,2),"utf-8")}catch(e){if("ENOENT"===p(e))return;g(e)}finally{if(n)try{await n()}catch{}}}export function getLastPeerDmSummary(e){for(let t=e.length-1;t>=0;t--){const a=e[t];if(a){if("user"===a.type&&"string"==typeof a.message.content)break;if("assistant"===a.type)for(const e of a.message.content)if("tool_use"===e.type&&e.name===i&&"object"==typeof e.input&&null!==e.input&&"to"in e.input&&"string"==typeof e.input.to&&"*"!==e.input.to&&e.input.to.toLowerCase()!==M.toLowerCase()&&"message"in e.input&&"string"==typeof e.input.message){return`[to ${e.input.to}] ${"summary"in e.input&&"string"==typeof e.input.summary?e.input.summary:e.input.message.slice(0,80)}`}}}}
|
|
1
|
+
import{mkdir as e,readFile as t,writeFile as a}from"fs/promises";import{join as s}from"path";import{z as o}from"zod/v4";import{TEAMMATE_MESSAGE_TAG as r}from"../constants/xml.js";import{PermissionModeSchema as n}from"../entrypoints/sdk/coreSchemas.js";import{SEND_MESSAGE_TOOL_NAME as i}from"../tools/SendMessageTool/constants.js";import{generateRequestId as m}from"./agentId.js";import{count as u}from"./array.js";import{logForDebugging as c}from"./debug.js";import{getTeamsDir as l}from"./envUtils.js";import{getErrnoCode as p}from"./errors.js";import{lazySchema as d}from"./lazySchema.js";import*as f from"./lockfile.js";import{logError as g}from"./log.js";import{jsonParse as x,jsonStringify as M}from"./slowOperations.js";import{TEAM_LEAD_NAME as y}from"./swarm/constants.js";import{sanitizePathComponent as h}from"./tasks.js";import{getAgentName as b,getTeammateColor as _,getTeamName as w}from"./teammate.js";const k={retries:{retries:10,minTimeout:5,maxTimeout:100}};export function getInboxPath(e,t){const a=t||w()||"default",o=h(a),r=h(e),n=s(l(),o,"inboxes"),i=s(n,`${r}.json`);return c(`[TeammateMailbox] getInboxPath: agent=${e}, team=${a}, fullPath=${i}`),i}export async function readMailbox(e,a){const s=getInboxPath(e,a);c(`[TeammateMailbox] readMailbox: path=${s}`);try{const e=await t(s,"utf-8"),a=x(e);return c(`[TeammateMailbox] readMailbox: read ${a.length} message(s)`),a}catch(t){return"ENOENT"===p(t)?(c("[TeammateMailbox] readMailbox: file does not exist"),[]):(c(`Failed to read inbox for ${e}: ${t}`),g(t),[])}}export async function readUnreadMessages(e,t){const a=await readMailbox(e,t),s=a.filter(e=>!e.read);return c(`[TeammateMailbox] readUnreadMessages: ${s.length} unread of ${a.length} total`),s}export async function writeToMailbox(t,o,r){await async function(t){const a=t||w()||"default",o=h(a),r=s(l(),o,"inboxes");await e(r,{recursive:!0}),c(`[TeammateMailbox] Ensured inbox directory: ${r}`)}(r);const n=getInboxPath(t,r),i=`${n}.lock`;c(`[TeammateMailbox] writeToMailbox: recipient=${t}, from=${o.from}, path=${n}`);try{await a(n,"[]",{encoding:"utf-8",flag:"wx"}),c("[TeammateMailbox] writeToMailbox: created new inbox file")}catch(e){if("EEXIST"!==p(e))return c(`[TeammateMailbox] writeToMailbox: failed to create inbox file: ${e}`),void g(e)}let m;try{m=await f.lock(n,{lockfilePath:i,...k});const e=await readMailbox(t,r),s={...o,read:!1};e.push(s),await a(n,M(e,null,2),"utf-8"),c(`[TeammateMailbox] Wrote message to ${t}'s inbox from ${o.from}`)}catch(e){c(`Failed to write to inbox for ${t}: ${e}`),g(e)}finally{m&&await m()}}export async function markMessageAsReadByIndex(e,t,s){const o=getInboxPath(e,t);c(`[TeammateMailbox] markMessageAsReadByIndex called: agentName=${e}, teamName=${t}, index=${s}, path=${o}`);const r=`${o}.lock`;let n;try{c("[TeammateMailbox] markMessageAsReadByIndex: acquiring lock..."),n=await f.lock(o,{lockfilePath:r,...k}),c("[TeammateMailbox] markMessageAsReadByIndex: lock acquired");const i=await readMailbox(e,t);if(c(`[TeammateMailbox] markMessageAsReadByIndex: read ${i.length} messages after lock`),s<0||s>=i.length)return void c(`[TeammateMailbox] markMessageAsReadByIndex: index ${s} out of bounds (${i.length} messages)`);const m=i[s];if(!m||m.read)return void c("[TeammateMailbox] markMessageAsReadByIndex: message already read or missing");i[s]={...m,read:!0},await a(o,M(i,null,2),"utf-8"),c(`[TeammateMailbox] markMessageAsReadByIndex: marked message at index ${s} as read`)}catch(t){if("ENOENT"===p(t))return void c(`[TeammateMailbox] markMessageAsReadByIndex: file does not exist at ${o}`);c(`[TeammateMailbox] markMessageAsReadByIndex FAILED for ${e}: ${t}`),g(t)}finally{n&&(await n(),c("[TeammateMailbox] markMessageAsReadByIndex: lock released"))}}export async function markMessagesAsRead(e,t){const s=getInboxPath(e,t);c(`[TeammateMailbox] markMessagesAsRead called: agentName=${e}, teamName=${t}, path=${s}`);const o=`${s}.lock`;let r;try{c("[TeammateMailbox] markMessagesAsRead: acquiring lock..."),r=await f.lock(s,{lockfilePath:o,...k}),c("[TeammateMailbox] markMessagesAsRead: lock acquired");const n=await readMailbox(e,t);if(c(`[TeammateMailbox] markMessagesAsRead: read ${n.length} messages after lock`),0===n.length)return void c("[TeammateMailbox] markMessagesAsRead: no messages to mark");const i=u(n,e=>!e.read);c(`[TeammateMailbox] markMessagesAsRead: ${i} unread of ${n.length} total`);for(const e of n)e.read=!0;await a(s,M(n,null,2),"utf-8"),c(`[TeammateMailbox] markMessagesAsRead: WROTE ${i} message(s) as read to ${s}`)}catch(t){if("ENOENT"===p(t))return void c(`[TeammateMailbox] markMessagesAsRead: file does not exist at ${s}`);c(`[TeammateMailbox] markMessagesAsRead FAILED for ${e}: ${t}`),g(t)}finally{r&&(await r(),c("[TeammateMailbox] markMessagesAsRead: lock released"))}}export async function clearMailbox(e,t){const s=getInboxPath(e,t);try{await a(s,"[]",{encoding:"utf-8",flag:"r+"}),c(`[TeammateMailbox] Cleared inbox for ${e}`)}catch(t){if("ENOENT"===p(t))return;c(`Failed to clear inbox for ${e}: ${t}`),g(t)}}export function formatTeammateMessages(e){return e.map(e=>{const t=e.color?` color="${e.color}"`:"",a=e.summary?` summary="${e.summary}"`:"";return`<${r} teammate_id="${e.from}"${t}${a}>\n${e.text}\n</${r}>`}).join("\n\n")}export function createIdleNotification(e,t){return{type:"idle_notification",from:e,timestamp:(new Date).toISOString(),idleReason:t?.idleReason,summary:t?.summary,completedTaskId:t?.completedTaskId,completedStatus:t?.completedStatus,failureReason:t?.failureReason}}export function isIdleNotification(e){try{const t=x(e);if(t&&"idle_notification"===t.type)return t}catch{}return null}export function createPermissionRequestMessage(e){return{type:"permission_request",request_id:e.request_id,agent_id:e.agent_id,tool_name:e.tool_name,tool_use_id:e.tool_use_id,description:e.description,input:e.input,permission_suggestions:e.permission_suggestions||[]}}export function createPermissionResponseMessage(e){return"error"===e.subtype?{type:"permission_response",request_id:e.request_id,subtype:"error",error:e.error||"Permission denied"}:{type:"permission_response",request_id:e.request_id,subtype:"success",response:{updated_input:e.updated_input,permission_updates:e.permission_updates}}}export function isPermissionRequest(e){try{const t=x(e);if(t&&"permission_request"===t.type)return t}catch{}return null}export function isPermissionResponse(e){try{const t=x(e);if(t&&"permission_response"===t.type)return t}catch{}return null}export function createSandboxPermissionRequestMessage(e){return{type:"sandbox_permission_request",requestId:e.requestId,workerId:e.workerId,workerName:e.workerName,workerColor:e.workerColor,hostPattern:{host:e.host},createdAt:Date.now()}}export function createSandboxPermissionResponseMessage(e){return{type:"sandbox_permission_response",requestId:e.requestId,host:e.host,allow:e.allow,timestamp:(new Date).toISOString()}}export function isSandboxPermissionRequest(e){try{const t=x(e);if(t&&"sandbox_permission_request"===t.type)return t}catch{}return null}export function isSandboxPermissionResponse(e){try{const t=x(e);if(t&&"sandbox_permission_response"===t.type)return t}catch{}return null}export const PlanApprovalRequestMessageSchema=d(()=>o.object({type:o.literal("plan_approval_request"),from:o.string(),timestamp:o.string(),planFilePath:o.string(),planContent:o.string(),requestId:o.string()}));export const PlanApprovalResponseMessageSchema=d(()=>o.object({type:o.literal("plan_approval_response"),requestId:o.string(),approved:o.boolean(),feedback:o.string().optional(),timestamp:o.string(),permissionMode:n().optional()}));export const ShutdownRequestMessageSchema=d(()=>o.object({type:o.literal("shutdown_request"),requestId:o.string(),from:o.string(),reason:o.string().optional(),timestamp:o.string()}));export const ShutdownApprovedMessageSchema=d(()=>o.object({type:o.literal("shutdown_approved"),requestId:o.string(),from:o.string(),timestamp:o.string(),paneId:o.string().optional(),backendType:o.string().optional()}));export const ShutdownRejectedMessageSchema=d(()=>o.object({type:o.literal("shutdown_rejected"),requestId:o.string(),from:o.string(),reason:o.string(),timestamp:o.string()}));export function createShutdownRequestMessage(e){return{type:"shutdown_request",requestId:e.requestId,from:e.from,reason:e.reason,timestamp:(new Date).toISOString()}}export function createShutdownApprovedMessage(e){return{type:"shutdown_approved",requestId:e.requestId,from:e.from,timestamp:(new Date).toISOString(),paneId:e.paneId,backendType:e.backendType}}export function createShutdownRejectedMessage(e){return{type:"shutdown_rejected",requestId:e.requestId,from:e.from,reason:e.reason,timestamp:(new Date).toISOString()}}export async function sendShutdownRequestToMailbox(e,t,a){const s=t||w(),o=b()||y,r=m("shutdown",e),n=createShutdownRequestMessage({requestId:r,from:o,reason:a});return await writeToMailbox(e,{from:o,text:M(n),timestamp:(new Date).toISOString(),color:_()},s),{requestId:r,target:e}}export function isShutdownRequest(e){try{const t=ShutdownRequestMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isPlanApprovalRequest(e){try{const t=PlanApprovalRequestMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isShutdownApproved(e){try{const t=ShutdownApprovedMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isShutdownRejected(e){try{const t=ShutdownRejectedMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isPlanApprovalResponse(e){try{const t=PlanApprovalResponseMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isTaskAssignment(e){try{const t=x(e);if(t&&"task_assignment"===t.type)return t}catch{}return null}export function isTeamPermissionUpdate(e){try{const t=x(e);if(t&&"team_permission_update"===t.type)return t}catch{}return null}export const ModeSetRequestMessageSchema=d(()=>o.object({type:o.literal("mode_set_request"),mode:n(),from:o.string()}));export function createModeSetRequestMessage(e){return{type:"mode_set_request",mode:e.mode,from:e.from}}export function isModeSetRequest(e){try{const t=ModeSetRequestMessageSchema().safeParse(x(e));if(t.success)return t.data}catch{}return null}export function isStructuredProtocolMessage(e){try{const t=x(e);if(!t||"object"!=typeof t||!("type"in t))return!1;const a=t.type;return"permission_request"===a||"permission_response"===a||"sandbox_permission_request"===a||"sandbox_permission_response"===a||"shutdown_request"===a||"shutdown_approved"===a||"team_permission_update"===a||"mode_set_request"===a||"plan_approval_request"===a||"plan_approval_response"===a}catch{return!1}}export async function markMessagesAsReadByPredicate(e,t,s){const o=getInboxPath(e,s),r=`${o}.lock`;let n;try{n=await f.lock(o,{lockfilePath:r,...k});const i=await readMailbox(e,s);if(0===i.length)return;const m=i.map(e=>!e.read&&t(e)?{...e,read:!0}:e);await a(o,M(m,null,2),"utf-8")}catch(e){if("ENOENT"===p(e))return;g(e)}finally{if(n)try{await n()}catch{}}}export function getLastPeerDmSummary(e){for(let t=e.length-1;t>=0;t--){const a=e[t];if(a){if("user"===a.type&&"string"==typeof a.message.content)break;if("assistant"===a.type)for(const e of a.message.content)if("tool_use"===e.type&&e.name===i&&"object"==typeof e.input&&null!==e.input&&"to"in e.input&&"string"==typeof e.input.to&&"*"!==e.input.to&&e.input.to.toLowerCase()!==y.toLowerCase()&&"message"in e.input&&"string"==typeof e.input.message)return`[to ${e.input.to}] ${"summary"in e.input&&"string"==typeof e.input.summary?e.input.summary:e.input.message.slice(0,80)}`}}}
|
|
@@ -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
|
|
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 +1 @@
|
|
|
1
|
-
import{ExportResultCode as
|
|
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 +1 @@
|
|
|
1
|
-
import{getEventLogger as e,getPromptId as t}from"
|
|
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 +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 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
|
+
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 +1 @@
|
|
|
1
|
-
import{logForDebugging as r}from"../debug.js";import{logError as e}from"../log.js";export class ClaudeCodeDiagLogger{error(o,...
|
|
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){}}
|