clew-code 0.3.1 → 0.3.2
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/generated/version.json +1 -1
- package/dist/main.js +2 -2
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"BUILD_VERSION":"0.3.
|
|
1
|
+
{"BUILD_VERSION":"0.3.2","PACKAGE_URL":"clew-code","FEEDBACK_CHANNEL":"https://github.com/ClewCode/ClewCode/issues","ISSUES_EXPLAINER":"visit https://github.com/ClewCode/ClewCode/issues"}
|
package/dist/main.js
CHANGED
|
@@ -333,7 +333,7 @@ ${Y}
|
|
|
333
333
|
`);return K===-1?$:$.slice(0,K)}function L2($,K,Y=0){let J=0,q=$.indexOf(K,Y);while(q!==-1)J++,q=$.indexOf(K,q+1);return J}function lq6($){return $.replace(/[\uFF10-\uFF19]/g,(K)=>String.fromCharCode(K.charCodeAt(0)-65248))}function nM8($){return $.replace(/\u3000/g," ")}function aM8($,K=",",Y=df4){let q="";for(let X of $){let z=q?K:"",A=z+X;if(q.length+A.length<=Y)q+=A;else{let Z=Y-q.length-z.length-14;if(Z>0)q+=z+X.slice(0,Z)+"...[truncated]";else q+="...[truncated]";return q}}return q}class Gl6{maxSize;content="";isTruncated=!1;totalBytesReceived=0;constructor($=df4){this.maxSize=$}append($){let K=typeof $==="string"?$:$.toString();if(this.totalBytesReceived+=K.length,this.isTruncated&&this.content.length>=this.maxSize)return;if(this.content.length+K.length>this.maxSize){let Y=this.maxSize-this.content.length;if(Y>0)this.content+=K.slice(0,Y);this.isTruncated=!0}else this.content+=K}toString(){if(!this.isTruncated)return this.content;let $=Math.max(0,this.totalBytesReceived-this.maxSize),K=Math.round($/1024);return`${this.content}
|
|
334
334
|
... [output truncated - ${K}KB removed]`}clear(){this.content="",this.isTruncated=!1,this.totalBytesReceived=0}get length(){return this.content.length}get truncated(){return this.isTruncated}get totalBytes(){return this.totalBytesReceived}}function lf4($,K){let Y=$.split(`
|
|
335
335
|
`);if(Y.length<=K)return $;return`${Y.slice(0,K).join(`
|
|
336
|
-
`)}\u2026`}var df4=33554432;function if4($){return OU$.filePatternTools.includes($)}function nf4($){return OU$.bashPrefixTools.includes($)}function af4($){return OU$.customValidation[$]}var OU$;var rf4=B(()=>{OU$={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit"],bashPrefixTools:["Bash"],customValidation:{WebSearch:($)=>{if($.includes("*")||$.includes("?"))return{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]};return{valid:!0}},WebFetch:($)=>{if($.includes("://")||$.startsWith("http"))return{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]};if(!$.startsWith("domain:"))return{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]};return{valid:!0}}}}});function of4($,K){let Y=0,J=K-1;while(J>=0&&$[J]==="\\")Y++,J--;return Y%2!==0}function QU$($,K){let Y=0;for(let J=0;J<$.length;J++)if($[J]===K&&!of4($,J))Y++;return Y}function Vp3($){for(let K=0;K<$.length-1;K++)if($[K]==="("&&$[K+1]===")"){if(!of4($,K))return!0}return!1}function wU$($){if(!$||$.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let K=QU$($,"("),Y=QU$($,")");if(K!==Y)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(Vp3($)){let z=$.substring(0,$.indexOf("("));if(!z)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${z}" without parentheses`,examples:[`${z}`,`${z}(some-pattern)`]}}let J=GA($),q=AL(J.toolName);if(q){if(J.ruleContent!==void 0||QU$($,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${J.toolName}" without parentheses, or use "mcp__${q.serverName}__*" for all tools`,examples:[`mcp__${q.serverName}`,`mcp__${q.serverName}__*`,q.toolName&&q.toolName!=="*"?`mcp__${q.serverName}__${q.toolName}`:void 0].filter(Boolean)};return{valid:!0}}if(!J.toolName||J.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(J.toolName[0]!==J.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${ZL(String(J.toolName))}"`};let X=af4(J.toolName);if(X&&J.ruleContent!==void 0){let z=X(J.ruleContent);if(!z.valid)return z}if(nf4(J.toolName)&&J.ruleContent!==void 0){let z=J.ruleContent;if(z.includes(":*")&&!z.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(z===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm:*)","Bash(git:*)"]}}if(if4(J.toolName)&&J.ruleContent!==void 0){let z=J.ruleContent;if(z.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${J.toolName}(*.ts) - matches .ts files`,`${J.toolName}(src/**) - matches all files in src`,`${J.toolName}(**/*.test.ts) - matches test files`]};if(z.includes("*")&&!z.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/)&&!z.includes("**"))return{valid:!1,error:"Wildcard placement might be incorrect",suggestion:"Wildcards are typically used at path boundaries",examples:[`${J.toolName}(*.js) - all .js files`,`${J.toolName}(src/*) - all files directly in src`,`${J.toolName}(src/**) - all files recursively in src`]}}return{valid:!0}}var rM8;var DU$=B(()=>{g7();kj();pw();rf4();rM8=I6(()=>U.string().superRefine(($,K)=>{let Y=wU$($);if(!Y.valid){let J=Y.error;if(Y.suggestion)J+=`. ${Y.suggestion}`;if(Y.examples&&Y.examples.length>0)J+=`. Examples: ${Y.examples.join(", ")}`;K.addIssue({code:U.ZodIssueCode.custom,message:J,params:{received:$}})}}))});function WB6($){return"serverName"in $&&$.serverName!==void 0}function oM8($){return"serverCommand"in $&&$.serverCommand!==void 0}function sM8($){return"serverUrl"in $&&$.serverUrl!==void 0}var _p3,Op3,Qp3,wp3,Dp3,GB6,b_;var QI=B(()=>{g7();Lf4();t8();YQ();JN();B2();DU$();uM8();uM8();_p3=I6(()=>U.record(U.string(),U.coerce.string())),Op3=I6(()=>U.object({allow:U.array(rM8()).optional().describe("List of permission rules for allowed operations"),deny:U.array(rM8()).optional().describe("List of permission rules for denied operations"),ask:U.array(rM8()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:U.preprocess(($)=>$==="yoloGod"?"bypassPermissions":$,U.enum(uq6).catch(void 0)).optional().describe("Default permission mode when Clew Code needs access"),disableBypassPermissionsMode:U.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),disableSkillShellExecution:U.enum(["disable"]).optional().describe("Disable shell command execution from skills (!`cmd` and ```! blocks)"),...{},additionalDirectories:U.array(U.string()).optional().describe("Additional directories to include in the permission scope")}).loose()),Qp3=I6(()=>U.object({source:zl6().describe("Where to fetch the marketplace from"),installLocation:U.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:U.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),wp3=I6(()=>U.object({serverName:U.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:U.array(U.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:U.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(($)=>{return e7([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),Dp3=I6(()=>U.object({serverName:U.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:U.array(U.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:U.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(($)=>{return e7([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),GB6=["skills","agents","hooks","mcp"],b_=I6(()=>U.object({$schema:U.literal(Df4).optional().describe("JSON Schema reference for Clew Code settings"),apiKeyHelper:U.string().optional().describe("Path to a script that outputs authentication values"),awsCredentialExport:U.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:U.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:U.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),...u6(process.env.CLAUDE_CODE_ENABLE_XAA)?{xaaIdp:U.object({issuer:U.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:U.string().describe("Clew Code's client_id registered at the IdP"),callbackPort:U.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")}:{},fileSuggestion:U.object({type:U.literal("command"),command:U.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:U.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),cleanupPeriodDays:U.number().nonnegative().int().optional().describe("Number of days to retain chat transcripts (default: 30). Setting to 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."),env:_p3().optional().describe("Environment variables to set for Clew Code sessions"),attribution:U.object({commit:U.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:U.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Clew Code attribution if not set."),includeCoAuthoredBy:U.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:U.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:Op3().optional().describe("Tool usage permissions configuration"),model:U.string().optional().describe("Override the default model used by Clew Code"),availableModels:U.array(U.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),modelOverrides:U.record(U.string(),U.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:U.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:U.array(U.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:U.array(U.string()).optional().describe("List of rejected MCP servers from .mcp.json"),allowedMcpServers:U.array(wp3()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:U.array(Dp3()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),hooks:_I().optional().describe("Custom commands to run before/after tool executions"),worktree:U.object({symlinkDirectories:U.array(U.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:U.array(U.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos \xE2\u20AC\u201D only the listed paths are written to disk."),baseRef:U.enum(["fresh","head"]).optional().describe("Controls which git ref new worktrees are based on. 'fresh' (default) uses origin/<default-branch> (remote tracking branch). 'head' uses the local HEAD. Use 'head' when you want worktrees to include local commits not yet pushed."),bgIsolation:U.enum(["worktree","none"]).optional().describe("Controls isolation mode for background sessions. 'worktree' (default) creates a git worktree to isolate changes. 'none' lets background sessions edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:U.boolean().optional().describe("Disable all hooks and statusLine execution"),defaultShell:U.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:U.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:U.array(U.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:U.array(U.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:U.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:U.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),strictPluginOnlyCustomization:U.preprocess(($)=>Array.isArray($)?$.filter((K)=>GB6.includes(K)):$,U.union([U.boolean(),U.array(U.enum(GB6))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. '+"Composes with strictKnownMarketplaces for end-to-end admin control \xE2\u20AC\u201D plugins gated by "+"marketplace allowlist, everything else blocked here."),statusLine:U.object({enabled:U.boolean().optional().default(!0),type:U.literal("command"),command:U.string(),padding:U.number().optional()}).optional().describe("Custom status line display configuration"),enabledPlugins:U.record(U.string(),U.union([U.array(U.string()),U.boolean(),U.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints.'),extraKnownMarketplaces:U.record(U.string(),Qp3()).check(($)=>{for(let[K,Y]of Object.entries($.value))if(Y.source.source==="settings"&&Y.source.name!==K)$.issues.push({code:"custom",input:Y.source.name,path:[K,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${K}" but source.name "${Y.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:U.array(zl6()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. "+"Note: this is a policy gate only \xE2\u20AC\u201D it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:U.array(zl6()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),pluginSuggestionMarketplaces:U.array(U.string()).optional().describe("Enterprise allowlist of allowed marketplaces for plugin recommendations/suggestions."),forceLoginMethod:U.enum(["claudeai","console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),forceLoginOrgUUID:U.string().optional().describe("Organization UUID to use for OAuth login"),otelHeadersHelper:U.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:U.string().optional().describe("Controls the output style for assistant responses"),prUrlTemplate:U.string().optional().describe("Custom PR URL template for linked sessions. Supports {{repo}}, {{repoOwner}}, {{repoName}}, and {{prNumber}}."),language:U.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:U.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:Bf4().optional(),disableAgentView:U.boolean().optional().describe("Disable background agents and agent view (claude agents command). Set to true to turn off agent view entirely."),feedbackSurveyRate:U.number().min(0).max(1).optional().describe("Probability (0\xE2\u20AC\u201C1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:U.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:U.object({mode:U.enum(["append","replace"]),verbs:U.array(U.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:U.object({excludeDefault:U.boolean().optional(),tips:U.array(U.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:U.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:U.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:U.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:U.enum(process.env.USER_TYPE==="ant"?["low","medium","high","max"]:["low","medium","high"]).optional().catch(void 0).describe("Persisted effort level for supported models."),advisorModel:U.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:U.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:U.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),antBetas:U.object({cliInternal:U.boolean().optional().describe("Enable cli-internal-2026-02-09 beta (ant internal features)"),connectorText:U.boolean().optional().describe("Enable summarize-connector-text-2026-03-13 beta (anti-distillation)"),tokenEfficientTools:U.boolean().optional().describe("Enable token-efficient-tools-2026-03-28 beta (~4.5% output token reduction)"),numericEffort:U.boolean().optional().describe("Enable numeric effort override in thinking config")}).optional().describe("Enable ant-only beta features. Requires backend support from Anthropic API."),promptSuggestionEnabled:U.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),showClearContextOnPlanAccept:U.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:U.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),maxWorkers:U.number().int().positive().max(20).optional().describe("Maximum number of concurrent sub-agent workers (default: 5). Limits parallel agent/teammate execution. Higher values may increase memory usage."),recentModels:U.array(U.string()).max(5).optional().describe("Recently used models shown at the top of the /model picker for quick access"),companyAnnouncements:U.array(U.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:U.record(U.string(),U.object({mcpServers:U.record(U.string(),U.record(U.string(),U.union([U.string(),U.number(),U.boolean(),U.array(U.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:U.record(U.string(),U.union([U.string(),U.number(),U.boolean(),U.array(U.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")})).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:U.object({defaultEnvironmentId:U.string().optional().describe("Default environment ID to use for remote sessions")}).optional().describe("Remote session configuration"),autoUpdatesChannel:U.enum(["latest","stable"]).optional().describe("Release channel for auto-updates (latest or stable)"),...{},minimumVersion:U.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),plansDirectory:U.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),...process.env.USER_TYPE==="ant"?{classifierPermissionsEnabled:U.boolean().optional().describe("Enable AI-based classification for Bash(prompt:...) permission rules")}:{},...{},...{},...{},channelsEnabled:U.boolean().optional().describe("Teams/Enterprise opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). Default off. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:U.array(U.object({marketplace:U.string(),plugin:U.string()})).optional().describe("Teams/Enterprise allowlist of channel plugins. When set, "+"replaces the default Anthropic allowlist \xE2\u20AC\u201D admins decide which "+"plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),...{},prefersReducedMotion:U.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),autoMemoryEnabled:U.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:U.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:U.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:U.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),skipDangerousModePermissionPrompt:U.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),ultracode:U.object({enabled:U.boolean().optional().describe("When true, auto-trigger a dynamic workflow for complex tasks."),confirmedOnce:U.boolean().optional().describe("Whether the user has accepted the first-run cost warning."),workflowsStarted:U.number().int().optional().describe("Number of dynamic workflows started."),maxParallel:U.number().int().min(2).max(10).optional().describe("Override default parallel subtask cap (2-10)."),estimatedTokenCostCeiling:U.enum(["low","medium","high","very-high"]).optional().describe("Skip auto-trigger for plans above this cost tier.")}).optional().describe("Dynamic-workflow / ultracode settings."),...{},disableAutoMode:U.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:U.array(U.object({id:U.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:U.string().describe("Display name for the SSH connection"),sshHost:U.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:U.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:U.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:U.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMdExcludes:U.array(U.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:U.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),explorerMode:U.enum(["none","fullscreen","sidebar"]).optional().describe("Preferred file explorer mode. sidebar: shows a tree on the side, fullscreen: interactive explorer.")}).loose())});function MU$(){let $=Hm(b_(),{unrepresentable:"any"});return c6($,null,2)}var sf4=B(()=>{g7();M$();QI()});function tf4($){let K=Mp3.find((J)=>J.matches($));if(!K)return null;let Y={...K.tip};if($.code==="invalid_value"&&$.enumValues&&!Y.suggestion)Y.suggestion=`Valid values: ${$.enumValues.map((J)=>`"${J}"`).join(", ")}`;if(!Y.docLink&&$.path){let J=$.path.split(".")[0];if(J)Y.docLink=Np3[J]}return Y}var Mp3,Np3;var ef4=B(()=>{Mp3=[{matches:($)=>$.path==="permissions.defaultMode"&&$.code==="invalid_value",tip:{suggestion:'Valid modes: "default", "plan", "acceptEdits", "bypassPermissions", or "auto"',docLink:"https://code.claude.com/docs/en/iam#permission-modes"}},{matches:($)=>$.path==="apiKeyHelper"&&$.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:($)=>$.path==="cleanupPeriodDays"&&$.code==="too_small"&&$.expected==="0",tip:{suggestion:"Must be 0 or greater. Set a positive number for days to retain transcripts (default is 30). Setting 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."}},{matches:($)=>$.path.startsWith("env.")&&$.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:"https://code.claude.com/docs/en/settings#environment-variables"}},{matches:($)=>($.path==="permissions.allow"||$.path==="permissions.deny")&&$.code==="invalid_type"&&$.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:($)=>$.path.includes("hooks")&&$.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:($)=>$.path.includes("hooks")&&$.path.endsWith("command")&&$.code==="invalid_type"&&$.expected==="string",tip:{suggestion:'The "command" field must be a string. For the exec form (no shell), use "command" with an executable path and "args" as an array. Example: {"type": "command", "command": "/usr/bin/node", "args": ["script.js"]}'}},{matches:($)=>$.code==="invalid_type"&&$.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:($)=>$.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:"https://code.claude.com/docs/en/settings"}},{matches:($)=>$.code==="invalid_value"&&$.enumValues!==void 0,tip:{suggestion:void 0}},{matches:($)=>$.code==="invalid_type"&&$.expected==="object"&&$.received===null&&$.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:($)=>$.path==="permissions.additionalDirectories"&&$.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:"https://code.claude.com/docs/en/iam#working-directories"}}],Np3={permissions:"https://code.claude.com/docs/en/iam#configuring-permissions",env:"https://code.claude.com/docs/en/settings#environment-variables",hooks:"https://code.claude.com/docs/en/hooks"}});function $k4($){return $.code==="invalid_type"}function Kk4($){return $.code==="invalid_value"}function Bp3($){return $.code==="unrecognized_keys"}function Yk4($){return $.code==="too_small"}function NU$($){if($===null)return"null";if($===void 0)return"undefined";if(Array.isArray($))return"array";return typeof $}function Jk4($){let K=$.match(/received (\w+)/);return K?K[1]:void 0}function VB6($,K){return $.issues.map((Y)=>{let J=Y.path.map(String).join("."),q=Y.message,X,z,A,Z,H;if(Kk4(Y))z=Y.values.map((W)=>String(W)),A=z.join(" | "),Z=void 0,H=void 0;else if($k4(Y)){A=Y.expected;let W=Jk4(Y.message);Z=W??NU$(Y.input),H=W??NU$(Y.input)}else if(Yk4(Y))A=String(Y.minimum);else if(Y.code==="custom"&&"params"in Y)Z=Y.params.received,H=Z;let G=tf4({path:J,code:Y.code,expected:A,received:Z,enumValues:z,message:Y.message,value:Z});if(Kk4(Y))X=z?.map((W)=>`"${W}"`).join(", "),q=`Invalid value. Expected one of: ${X}`;else if($k4(Y)){let W=Jk4(Y.message)??NU$(Y.input);if(Y.expected==="object"&&W==="null"&&J==="")q="Invalid or malformed JSON";else q=`Expected ${Y.expected}, but received ${W}`}else if(Bp3(Y)){let W=Y.keys.join(", ");q=`Unrecognized ${Y4(Y.keys.length,"field")}: ${W}`}else if(Yk4(Y))q=`Number must be greater than or equal to ${Y.minimum}`,X=String(Y.minimum);return{file:K,path:J,message:q,expected:X,invalidValue:H,suggestion:G?.suggestion,docLink:G?.docLink}})}function BU$($){try{let K=Q$($),Y=b_().strict().safeParse(K);if(Y.success)return{isValid:!0};return{isValid:!1,error:`Settings validation failed:
|
|
336
|
+
`)}\u2026`}var df4=33554432;function if4($){return OU$.filePatternTools.includes($)}function nf4($){return OU$.bashPrefixTools.includes($)}function af4($){return OU$.customValidation[$]}var OU$;var rf4=B(()=>{OU$={filePatternTools:["Read","Write","Edit","Glob","NotebookRead","NotebookEdit"],bashPrefixTools:["Bash"],customValidation:{WebSearch:($)=>{if($.includes("*")||$.includes("?"))return{valid:!1,error:"WebSearch does not support wildcards",suggestion:"Use exact search terms without * or ?",examples:["WebSearch(claude ai)","WebSearch(typescript tutorial)"]};return{valid:!0}},WebFetch:($)=>{if($.includes("://")||$.startsWith("http"))return{valid:!1,error:"WebFetch permissions use domain format, not URLs",suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:github.com)"]};if(!$.startsWith("domain:"))return{valid:!1,error:'WebFetch permissions must use "domain:" prefix',suggestion:'Use "domain:hostname" format',examples:["WebFetch(domain:example.com)","WebFetch(domain:*.google.com)"]};return{valid:!0}}}}});function of4($,K){let Y=0,J=K-1;while(J>=0&&$[J]==="\\")Y++,J--;return Y%2!==0}function QU$($,K){let Y=0;for(let J=0;J<$.length;J++)if($[J]===K&&!of4($,J))Y++;return Y}function Vp3($){for(let K=0;K<$.length-1;K++)if($[K]==="("&&$[K+1]===")"){if(!of4($,K))return!0}return!1}function wU$($){if(!$||$.trim()==="")return{valid:!1,error:"Permission rule cannot be empty"};let K=QU$($,"("),Y=QU$($,")");if(K!==Y)return{valid:!1,error:"Mismatched parentheses",suggestion:"Ensure all opening parentheses have matching closing parentheses"};if(Vp3($)){let z=$.substring(0,$.indexOf("("));if(!z)return{valid:!1,error:"Empty parentheses with no tool name",suggestion:"Specify a tool name before the parentheses"};return{valid:!1,error:"Empty parentheses",suggestion:`Either specify a pattern or use just "${z}" without parentheses`,examples:[`${z}`,`${z}(some-pattern)`]}}let J=GA($),q=AL(J.toolName);if(q){if(J.ruleContent!==void 0||QU$($,"(")>0)return{valid:!1,error:"MCP rules do not support patterns in parentheses",suggestion:`Use "${J.toolName}" without parentheses, or use "mcp__${q.serverName}__*" for all tools`,examples:[`mcp__${q.serverName}`,`mcp__${q.serverName}__*`,q.toolName&&q.toolName!=="*"?`mcp__${q.serverName}__${q.toolName}`:void 0].filter(Boolean)};return{valid:!0}}if(!J.toolName||J.toolName.length===0)return{valid:!1,error:"Tool name cannot be empty"};if(J.toolName[0]!==J.toolName[0]?.toUpperCase())return{valid:!1,error:"Tool names must start with uppercase",suggestion:`Use "${ZL(String(J.toolName))}"`};let X=af4(J.toolName);if(X&&J.ruleContent!==void 0){let z=X(J.ruleContent);if(!z.valid)return z}if(nf4(J.toolName)&&J.ruleContent!==void 0){let z=J.ruleContent;if(z.includes(":*")&&!z.endsWith(":*"))return{valid:!1,error:"The :* pattern must be at the end",suggestion:"Move :* to the end for prefix matching, or use * for wildcard matching",examples:["Bash(npm run:*) - prefix matching (legacy)","Bash(npm run *) - wildcard matching"]};if(z===":*")return{valid:!1,error:"Prefix cannot be empty before :*",suggestion:"Specify a command prefix before :*",examples:["Bash(npm:*)","Bash(git:*)"]}}if(if4(J.toolName)&&J.ruleContent!==void 0){let z=J.ruleContent;if(z.includes(":*"))return{valid:!1,error:'The ":*" syntax is only for Bash prefix rules',suggestion:'Use glob patterns like "*" or "**" for file matching',examples:[`${J.toolName}(*.ts) - matches .ts files`,`${J.toolName}(src/**) - matches all files in src`,`${J.toolName}(**/*.test.ts) - matches test files`]};if(z.includes("*")&&!z.match(/^\*|\*$|\*\*|\/\*|\*\.|\*\)/)&&!z.includes("**"))return{valid:!1,error:"Wildcard placement might be incorrect",suggestion:"Wildcards are typically used at path boundaries",examples:[`${J.toolName}(*.js) - all .js files`,`${J.toolName}(src/*) - all files directly in src`,`${J.toolName}(src/**) - all files recursively in src`]}}return{valid:!0}}var rM8;var DU$=B(()=>{g7();kj();pw();rf4();rM8=I6(()=>U.string().superRefine(($,K)=>{let Y=wU$($);if(!Y.valid){let J=Y.error;if(Y.suggestion)J+=`. ${Y.suggestion}`;if(Y.examples&&Y.examples.length>0)J+=`. Examples: ${Y.examples.join(", ")}`;K.addIssue({code:U.ZodIssueCode.custom,message:J,params:{received:$}})}}))});function WB6($){return"serverName"in $&&$.serverName!==void 0}function oM8($){return"serverCommand"in $&&$.serverCommand!==void 0}function sM8($){return"serverUrl"in $&&$.serverUrl!==void 0}var _p3,Op3,Qp3,wp3,Dp3,GB6,b_;var QI=B(()=>{g7();Lf4();t8();YQ();JN();B2();DU$();uM8();uM8();_p3=I6(()=>U.record(U.string(),U.coerce.string())),Op3=I6(()=>U.object({allow:U.array(rM8()).optional().describe("List of permission rules for allowed operations"),deny:U.array(rM8()).optional().describe("List of permission rules for denied operations"),ask:U.array(rM8()).optional().describe("List of permission rules that should always prompt for confirmation"),defaultMode:U.preprocess(($)=>$==="yoloGod"?"bypassPermissions":$,U.enum(uq6).catch(void 0)).optional().describe("Default permission mode when Clew Code needs access"),disableBypassPermissionsMode:U.enum(["disable"]).optional().describe("Disable the ability to bypass permission prompts"),disableSkillShellExecution:U.enum(["disable"]).optional().describe("Disable shell command execution from skills (!`cmd` and ```! blocks)"),...{},additionalDirectories:U.array(U.string()).optional().describe("Additional directories to include in the permission scope")}).loose()),Qp3=I6(()=>U.object({source:zl6().describe("Where to fetch the marketplace from"),installLocation:U.string().optional().describe("Local cache path where marketplace manifest is stored (auto-generated if not provided)"),autoUpdate:U.boolean().optional().describe("Whether to automatically update this marketplace and its installed plugins on startup")})),wp3=I6(()=>U.object({serverName:U.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that users are allowed to configure"),serverCommand:U.array(U.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for allowed stdio servers"),serverUrl:U.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for allowed remote MCP servers')}).refine(($)=>{return e7([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),Dp3=I6(()=>U.object({serverName:U.string().regex(/^[a-zA-Z0-9_-]+$/,"Server name can only contain letters, numbers, hyphens, and underscores").optional().describe("Name of the MCP server that is explicitly blocked"),serverCommand:U.array(U.string()).min(1,"Server command must have at least one element (the command)").optional().describe("Command array [command, ...args] to match exactly for blocked stdio servers"),serverUrl:U.string().optional().describe('URL pattern with wildcard support (e.g., "https://*.example.com/*") for blocked remote MCP servers')}).refine(($)=>{return e7([$.serverName!==void 0,$.serverCommand!==void 0,$.serverUrl!==void 0],Boolean)===1},{message:'Entry must have exactly one of "serverName", "serverCommand", or "serverUrl"'})),GB6=["skills","agents","hooks","mcp"],b_=I6(()=>U.object({$schema:U.literal(Df4).optional().describe("JSON Schema reference for Clew Code settings"),apiKeyHelper:U.string().optional().describe("Path to a script that outputs authentication values"),awsCredentialExport:U.string().optional().describe("Path to a script that exports AWS credentials"),awsAuthRefresh:U.string().optional().describe("Path to a script that refreshes AWS authentication"),gcpAuthRefresh:U.string().optional().describe("Command to refresh GCP authentication (e.g., gcloud auth application-default login)"),...u6(process.env.CLAUDE_CODE_ENABLE_XAA)?{xaaIdp:U.object({issuer:U.string().url().describe("IdP issuer URL for OIDC discovery"),clientId:U.string().describe("Clew Code's client_id registered at the IdP"),callbackPort:U.number().int().positive().optional().describe("Fixed loopback callback port for the IdP OIDC login. Only needed if the IdP does not honor RFC 8252 port-any matching.")}).optional().describe("XAA (SEP-990) IdP connection. Configure once; all XAA-enabled MCP servers reuse this.")}:{},fileSuggestion:U.object({type:U.literal("command"),command:U.string()}).optional().describe("Custom file suggestion configuration for @ mentions"),respectGitignore:U.boolean().optional().describe("Whether file picker should respect .gitignore files (default: true). Note: .ignore files are always respected."),cleanupPeriodDays:U.number().nonnegative().int().optional().describe("Number of days to retain chat transcripts (default: 30). Setting to 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."),env:_p3().optional().describe("Environment variables to set for Clew Code sessions"),attribution:U.object({commit:U.string().optional().describe("Attribution text for git commits, including any trailers. Empty string hides attribution."),pr:U.string().optional().describe("Attribution text for pull request descriptions. Empty string hides attribution.")}).optional().describe("Customize attribution text for commits and PRs. Each field defaults to the standard Clew Code attribution if not set."),includeCoAuthoredBy:U.boolean().optional().describe("Deprecated: Use attribution instead. Whether to include Claude's co-authored by attribution in commits and PRs (defaults to true)"),includeGitInstructions:U.boolean().optional().describe("Include built-in commit and PR workflow instructions in Claude's system prompt (default: true)"),permissions:Op3().optional().describe("Tool usage permissions configuration"),model:U.string().optional().describe("Override the default model used by Clew Code"),availableModels:U.array(U.string()).optional().describe('Allowlist of models that users can select. Accepts family aliases ("opus" allows any opus version), version prefixes ("opus-4-5" allows only that version), and full model IDs. If undefined, all models are available. If empty array, only the default model is available. Typically set in managed settings by enterprise administrators.'),modelOverrides:U.record(U.string(),U.string()).optional().describe('Override mapping from Anthropic model ID (e.g. "claude-opus-4-6") to provider-specific model ID (e.g. a Bedrock inference profile ARN). Typically set in managed settings by enterprise administrators.'),enableAllProjectMcpServers:U.boolean().optional().describe("Whether to automatically approve all MCP servers in the project"),enabledMcpjsonServers:U.array(U.string()).optional().describe("List of approved MCP servers from .mcp.json"),disabledMcpjsonServers:U.array(U.string()).optional().describe("List of rejected MCP servers from .mcp.json"),allowedMcpServers:U.array(wp3()).optional().describe("Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied."),deniedMcpServers:U.array(Dp3()).optional().describe("Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied."),hooks:_I().optional().describe("Custom commands to run before/after tool executions"),worktree:U.object({symlinkDirectories:U.array(U.string()).optional().describe('Directories to symlink from main repository to worktrees to avoid disk bloat. Must be explicitly configured - no directories are symlinked by default. Common examples: "node_modules", ".cache", ".bin"'),sparsePaths:U.array(U.string()).optional().describe("Directories to include when creating worktrees, via git sparse-checkout (cone mode). "+"Dramatically faster in large monorepos \xE2\u20AC\u201D only the listed paths are written to disk."),baseRef:U.enum(["fresh","head"]).optional().describe("Controls which git ref new worktrees are based on. 'fresh' (default) uses origin/<default-branch> (remote tracking branch). 'head' uses the local HEAD. Use 'head' when you want worktrees to include local commits not yet pushed."),bgIsolation:U.enum(["worktree","none"]).optional().describe("Controls isolation mode for background sessions. 'worktree' (default) creates a git worktree to isolate changes. 'none' lets background sessions edit the working copy directly.")}).optional().describe("Git worktree configuration for --worktree flag."),disableAllHooks:U.boolean().optional().describe("Disable all hooks and statusLine execution"),defaultShell:U.enum(["bash","powershell"]).optional().describe("Default shell for input-box ! commands. Defaults to 'bash' on all platforms (no Windows auto-flip)."),allowManagedHooksOnly:U.boolean().optional().describe("When true (and set in managed settings), only hooks from managed settings run. User, project, and local hooks are ignored."),allowedHttpHookUrls:U.array(U.string()).optional().describe('Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard (e.g. "https://hooks.example.com/*"). When set, HTTP hooks with non-matching URLs are blocked. If undefined, all URLs are allowed. If empty array, no HTTP hooks are allowed. Arrays merge across settings sources (same semantics as allowedMcpServers).'),httpHookAllowedEnvVars:U.array(U.string()).optional().describe("Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. If undefined, no restriction is applied. Arrays merge across settings sources (same semantics as allowedMcpServers)."),allowManagedPermissionRulesOnly:U.boolean().optional().describe("When true (and set in managed settings), only permission rules (allow/deny/ask) from managed settings are respected. User, project, local, and CLI argument permission rules are ignored."),allowManagedMcpServersOnly:U.boolean().optional().describe("When true (and set in managed settings), allowedMcpServers is only read from managed settings. deniedMcpServers still merges from all sources, so users can deny servers for themselves. Users can still add their own MCP servers, but only the admin-defined allowlist applies."),strictPluginOnlyCustomization:U.preprocess(($)=>Array.isArray($)?$.filter((K)=>GB6.includes(K)):$,U.union([U.boolean(),U.array(U.enum(GB6))])).optional().catch(void 0).describe('When set in managed settings, blocks non-plugin customization sources for the listed surfaces. Array form locks specific surfaces (e.g. ["skills", "hooks"]); `true` locks all four; `false` is an explicit no-op. Blocked: ~/.claude/{surface}/, .claude/{surface}/ (project), settings.json hooks, .mcp.json. NOT blocked: managed (policySettings) sources, plugin-provided customizations. '+"Composes with strictKnownMarketplaces for end-to-end admin control \xE2\u20AC\u201D plugins gated by "+"marketplace allowlist, everything else blocked here."),statusLine:U.object({enabled:U.boolean().optional().default(!0),type:U.literal("command"),command:U.string(),padding:U.number().optional()}).optional().describe("Custom status line display configuration"),enabledPlugins:U.record(U.string(),U.union([U.array(U.string()),U.boolean(),U.undefined()])).optional().describe('Enabled plugins using plugin-id@marketplace-id format. Example: { "formatter@anthropic-tools": true }. Also supports extended format with version constraints.'),extraKnownMarketplaces:U.record(U.string(),Qp3()).check(($)=>{for(let[K,Y]of Object.entries($.value))if(Y.source.source==="settings"&&Y.source.name!==K)$.issues.push({code:"custom",input:Y.source.name,path:[K,"source","name"],message:`Settings-sourced marketplace name must match its extraKnownMarketplaces key (got key "${K}" but source.name "${Y.source.name}")`})}).optional().describe("Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources."),strictKnownMarketplaces:U.array(zl6()).optional().describe("Enterprise strict list of allowed marketplace sources. When set in managed settings, ONLY these exact sources can be added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem. "+"Note: this is a policy gate only \xE2\u20AC\u201D it does NOT register marketplaces. "+"To pre-register allowed marketplaces for users, also set extraKnownMarketplaces."),blockedMarketplaces:U.array(zl6()).optional().describe("Enterprise blocklist of marketplace sources. When set in managed settings, these exact sources are blocked from being added as marketplaces. The check happens BEFORE downloading, so blocked sources never touch the filesystem."),pluginSuggestionMarketplaces:U.array(U.string()).optional().describe("Enterprise allowlist of allowed marketplaces for plugin recommendations/suggestions."),forceLoginMethod:U.enum(["claudeai","console"]).optional().describe('Force a specific login method: "claudeai" for Claude Pro/Max, "console" for Console billing'),forceLoginOrgUUID:U.string().optional().describe("Organization UUID to use for OAuth login"),otelHeadersHelper:U.string().optional().describe("Path to a script that outputs OpenTelemetry headers"),outputStyle:U.string().optional().describe("Controls the output style for assistant responses"),prUrlTemplate:U.string().optional().describe("Custom PR URL template for linked sessions. Supports {{repo}}, {{repoOwner}}, {{repoName}}, and {{prNumber}}."),language:U.string().optional().describe('Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'),skipWebFetchPreflight:U.boolean().optional().describe("Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"),sandbox:Bf4().optional(),disableAgentView:U.boolean().optional().describe("Disable background agents and agent view (claude agents command). Set to true to turn off agent view entirely."),feedbackSurveyRate:U.number().min(0).max(1).optional().describe("Probability (0\xE2\u20AC\u201C1) that the session quality survey appears when eligible. 0.05 is a reasonable starting point."),spinnerTipsEnabled:U.boolean().optional().describe("Whether to show tips in the spinner"),spinnerVerbs:U.object({mode:U.enum(["append","replace"]),verbs:U.array(U.string())}).optional().describe('Customize spinner verbs. mode: "append" adds verbs to defaults, "replace" uses only your verbs.'),spinnerTipsOverride:U.object({excludeDefault:U.boolean().optional(),tips:U.array(U.string())}).optional().describe("Override spinner tips. tips: array of tip strings. excludeDefault: if true, only show custom tips (default: false)."),syntaxHighlightingDisabled:U.boolean().optional().describe("Whether to disable syntax highlighting in diffs"),terminalTitleFromRename:U.boolean().optional().describe("Whether /rename updates the terminal tab title (defaults to true). Set to false to keep auto-generated topic titles."),alwaysThinkingEnabled:U.boolean().optional().describe("When false, thinking is disabled. When absent or true, thinking is enabled automatically for supported models."),effortLevel:U.enum(process.env.USER_TYPE==="ant"?["low","medium","high","max"]:["low","medium","high"]).optional().catch(void 0).describe("Persisted effort level for supported models."),advisorModel:U.string().optional().describe("Advisor model for the server-side advisor tool."),fastMode:U.boolean().optional().describe("When true, fast mode is enabled. When absent or false, fast mode is off."),fastModePerSessionOptIn:U.boolean().optional().describe("When true, fast mode does not persist across sessions. Each session starts with fast mode off."),antBetas:U.object({cliInternal:U.boolean().optional().describe("Enable cli-internal-2026-02-09 beta (ant internal features)"),connectorText:U.boolean().optional().describe("Enable summarize-connector-text-2026-03-13 beta (anti-distillation)"),tokenEfficientTools:U.boolean().optional().describe("Enable token-efficient-tools-2026-03-28 beta (~4.5% output token reduction)"),numericEffort:U.boolean().optional().describe("Enable numeric effort override in thinking config")}).optional().describe("Enable ant-only beta features. Requires backend support from Anthropic API."),promptSuggestionEnabled:U.boolean().optional().describe("When false, prompt suggestions are disabled. When absent or true, prompt suggestions are enabled."),showClearContextOnPlanAccept:U.boolean().optional().describe('When true, the plan-approval dialog offers a "clear context" option. Defaults to false.'),agent:U.string().optional().describe("Name of an agent (built-in or custom) to use for the main thread. Applies the agent's system prompt, tool restrictions, and model."),maxWorkers:U.number().int().positive().max(20).optional().describe("Maximum number of concurrent sub-agent workers (default: 5). Limits parallel agent/teammate execution. Higher values may increase memory usage."),recentModels:U.array(U.string()).max(5).optional().describe("Recently used models shown at the top of the /model picker for quick access"),companyAnnouncements:U.array(U.string()).optional().describe("Company announcements to display at startup (one will be randomly selected if multiple are provided)"),pluginConfigs:U.record(U.string(),U.object({mcpServers:U.record(U.string(),U.record(U.string(),U.union([U.string(),U.number(),U.boolean(),U.array(U.string())]))).optional().describe("User configuration values for MCP servers keyed by server name"),options:U.record(U.string(),U.union([U.string(),U.number(),U.boolean(),U.array(U.string())])).optional().describe("Non-sensitive option values from plugin manifest userConfig, keyed by option name. Sensitive values go to secure storage instead.")})).optional().describe("Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format)"),remote:U.object({defaultEnvironmentId:U.string().optional().describe("Default environment ID to use for remote sessions")}).optional().describe("Remote session configuration"),autoUpdatesChannel:U.enum(["latest","stable"]).optional().describe("Release channel for auto-updates (latest or stable)"),...{},minimumVersion:U.string().optional().describe("Minimum version to stay on - prevents downgrades when switching to stable channel"),plansDirectory:U.string().optional().describe("Custom directory for plan files, relative to project root. If not set, defaults to ~/.claude/plans/"),...process.env.USER_TYPE==="ant"?{classifierPermissionsEnabled:U.boolean().optional().describe("Enable AI-based classification for Bash(prompt:...) permission rules")}:{},...{},...{},...{},channelsEnabled:U.boolean().optional().describe("Teams/Enterprise opt-in for channel notifications (MCP servers with the claude/channel capability pushing inbound messages). Default off. Set true to allow; users then select servers via --channels."),allowedChannelPlugins:U.array(U.object({marketplace:U.string(),plugin:U.string()})).optional().describe("Teams/Enterprise allowlist of channel plugins. When set, "+"replaces the default Anthropic allowlist \xE2\u20AC\u201D admins decide which "+"plugins may push inbound messages. Undefined falls back to the default. Requires channelsEnabled: true."),...{},prefersReducedMotion:U.boolean().optional().describe("Reduce or disable animations for accessibility (spinner shimmer, flash effects, etc.)"),autoMemoryEnabled:U.boolean().optional().describe("Enable auto-memory for this project. When false, Claude will not read from or write to the auto-memory directory."),autoMemoryDirectory:U.string().optional().describe("Custom directory path for auto-memory storage. Supports ~/ prefix for home directory expansion. Ignored if set in projectSettings (checked-in .claude/settings.json) for security. When unset, defaults to ~/.claude/projects/<sanitized-cwd>/memory/."),autoDreamEnabled:U.boolean().optional().describe("Enable background memory consolidation (auto-dream). When set, overrides the server-side default."),showThinkingSummaries:U.boolean().optional().describe("Show thinking summaries in the transcript view (ctrl+o). Default: false."),skipDangerousModePermissionPrompt:U.boolean().optional().describe("Whether the user has accepted the bypass permissions mode dialog"),ultracode:U.object({enabled:U.boolean().optional().describe("When true, auto-trigger a dynamic workflow for complex tasks."),confirmedOnce:U.boolean().optional().describe("Whether the user has accepted the first-run cost warning."),workflowsStarted:U.number().int().optional().describe("Number of dynamic workflows started."),maxParallel:U.number().int().min(2).max(10).optional().describe("Override default parallel subtask cap (2-10)."),estimatedTokenCostCeiling:U.enum(["low","medium","high","very-high"]).optional().describe("Skip auto-trigger for plans above this cost tier.")}).optional().describe("Dynamic-workflow / ultracode settings."),...{},disableAutoMode:U.enum(["disable"]).optional().describe("Disable auto mode"),sshConfigs:U.array(U.object({id:U.string().describe("Unique identifier for this SSH config. Used to match configs across settings sources."),name:U.string().describe("Display name for the SSH connection"),sshHost:U.string().describe('SSH host in format "user@hostname" or "hostname", or a host alias from ~/.ssh/config'),sshPort:U.number().int().optional().describe("SSH port (default: 22)"),sshIdentityFile:U.string().optional().describe("Path to SSH identity file (private key)"),startDirectory:U.string().optional().describe("Default working directory on the remote host. Supports tilde expansion (e.g. ~/projects). If not specified, defaults to the remote user home directory. Can be overridden by the [dir] positional argument in `claude ssh <config> [dir]`.")})).optional().describe("SSH connection configurations for remote environments. Typically set in managed settings by enterprise administrators to pre-configure SSH connections for team members."),claudeMdExcludes:U.array(U.string()).optional().describe('Glob patterns or absolute paths of CLAUDE.md files to exclude from loading. Patterns are matched against absolute file paths using picomatch. Only applies to User, Project, and Local memory types (Managed/policy files cannot be excluded). Examples: "/home/user/monorepo/CLAUDE.md", "**/code/CLAUDE.md", "**/some-dir/.claude/rules/**"'),pluginTrustMessage:U.string().optional().describe('Custom message to append to the plugin trust warning shown before installation. Only read from policy settings (managed-settings.json / MDM). Useful for enterprise administrators to add organization-specific context (e.g., "All plugins from our internal marketplace are vetted and approved.").'),explorerMode:U.enum(["none","fullscreen","sidebar"]).optional().describe("Preferred file explorer mode. sidebar: shows a tree on the side, fullscreen: interactive explorer.")}).loose())});function MU$(){try{let $=Hm(b_(),{unrepresentable:"any"});return c6($,null,2)}catch{return c6({type:"object",description:"Settings schema unavailable"},null,2)}}var sf4=B(()=>{g7();M$();QI()});function tf4($){let K=Mp3.find((J)=>J.matches($));if(!K)return null;let Y={...K.tip};if($.code==="invalid_value"&&$.enumValues&&!Y.suggestion)Y.suggestion=`Valid values: ${$.enumValues.map((J)=>`"${J}"`).join(", ")}`;if(!Y.docLink&&$.path){let J=$.path.split(".")[0];if(J)Y.docLink=Np3[J]}return Y}var Mp3,Np3;var ef4=B(()=>{Mp3=[{matches:($)=>$.path==="permissions.defaultMode"&&$.code==="invalid_value",tip:{suggestion:'Valid modes: "default", "plan", "acceptEdits", "bypassPermissions", or "auto"',docLink:"https://code.claude.com/docs/en/iam#permission-modes"}},{matches:($)=>$.path==="apiKeyHelper"&&$.code==="invalid_type",tip:{suggestion:'Provide a shell command that outputs your API key to stdout. The script should output only the API key. Example: "/bin/generate_temp_api_key.sh"'}},{matches:($)=>$.path==="cleanupPeriodDays"&&$.code==="too_small"&&$.expected==="0",tip:{suggestion:"Must be 0 or greater. Set a positive number for days to retain transcripts (default is 30). Setting 0 disables session persistence entirely: no transcripts are written and existing transcripts are deleted at startup."}},{matches:($)=>$.path.startsWith("env.")&&$.code==="invalid_type",tip:{suggestion:'Environment variables must be strings. Wrap numbers and booleans in quotes. Example: "DEBUG": "true", "PORT": "3000"',docLink:"https://code.claude.com/docs/en/settings#environment-variables"}},{matches:($)=>($.path==="permissions.allow"||$.path==="permissions.deny")&&$.code==="invalid_type"&&$.expected==="array",tip:{suggestion:'Permission rules must be in an array. Format: ["Tool(specifier)"]. Examples: ["Bash(npm run build)", "Edit(docs/**)", "Read(~/.zshrc)"]. Use * for wildcards.'}},{matches:($)=>$.path.includes("hooks")&&$.code==="invalid_type",tip:{suggestion:'Hooks use a matcher + hooks array. The matcher is a string: a tool name ("Bash"), pipe-separated list ("Edit|Write"), or empty to match all. Example: {"PostToolUse": [{"matcher": "Edit|Write", "hooks": [{"type": "command", "command": "echo Done"}]}]}'}},{matches:($)=>$.path.includes("hooks")&&$.path.endsWith("command")&&$.code==="invalid_type"&&$.expected==="string",tip:{suggestion:'The "command" field must be a string. For the exec form (no shell), use "command" with an executable path and "args" as an array. Example: {"type": "command", "command": "/usr/bin/node", "args": ["script.js"]}'}},{matches:($)=>$.code==="invalid_type"&&$.expected==="boolean",tip:{suggestion:'Use true or false without quotes. Example: "includeCoAuthoredBy": true'}},{matches:($)=>$.code==="unrecognized_keys",tip:{suggestion:"Check for typos or refer to the documentation for valid fields",docLink:"https://code.claude.com/docs/en/settings"}},{matches:($)=>$.code==="invalid_value"&&$.enumValues!==void 0,tip:{suggestion:void 0}},{matches:($)=>$.code==="invalid_type"&&$.expected==="object"&&$.received===null&&$.path==="",tip:{suggestion:"Check for missing commas, unmatched brackets, or trailing commas. Use a JSON validator to identify the exact syntax error."}},{matches:($)=>$.path==="permissions.additionalDirectories"&&$.code==="invalid_type",tip:{suggestion:'Must be an array of directory paths. Example: ["~/projects", "/tmp/workspace"]. You can also use --add-dir flag or /add-dir command',docLink:"https://code.claude.com/docs/en/iam#working-directories"}}],Np3={permissions:"https://code.claude.com/docs/en/iam#configuring-permissions",env:"https://code.claude.com/docs/en/settings#environment-variables",hooks:"https://code.claude.com/docs/en/hooks"}});function $k4($){return $.code==="invalid_type"}function Kk4($){return $.code==="invalid_value"}function Bp3($){return $.code==="unrecognized_keys"}function Yk4($){return $.code==="too_small"}function NU$($){if($===null)return"null";if($===void 0)return"undefined";if(Array.isArray($))return"array";return typeof $}function Jk4($){let K=$.match(/received (\w+)/);return K?K[1]:void 0}function VB6($,K){return $.issues.map((Y)=>{let J=Y.path.map(String).join("."),q=Y.message,X,z,A,Z,H;if(Kk4(Y))z=Y.values.map((W)=>String(W)),A=z.join(" | "),Z=void 0,H=void 0;else if($k4(Y)){A=Y.expected;let W=Jk4(Y.message);Z=W??NU$(Y.input),H=W??NU$(Y.input)}else if(Yk4(Y))A=String(Y.minimum);else if(Y.code==="custom"&&"params"in Y)Z=Y.params.received,H=Z;let G=tf4({path:J,code:Y.code,expected:A,received:Z,enumValues:z,message:Y.message,value:Z});if(Kk4(Y))X=z?.map((W)=>`"${W}"`).join(", "),q=`Invalid value. Expected one of: ${X}`;else if($k4(Y)){let W=Jk4(Y.message)??NU$(Y.input);if(Y.expected==="object"&&W==="null"&&J==="")q="Invalid or malformed JSON";else q=`Expected ${Y.expected}, but received ${W}`}else if(Bp3(Y)){let W=Y.keys.join(", ");q=`Unrecognized ${Y4(Y.keys.length,"field")}: ${W}`}else if(Yk4(Y))q=`Number must be greater than or equal to ${Y.minimum}`,X=String(Y.minimum);return{file:K,path:J,message:q,expected:X,invalidValue:H,suggestion:G?.suggestion,docLink:G?.docLink}})}function BU$($){try{let K=Q$($),Y=b_().strict().safeParse(K);if(Y.success)return{isValid:!0};return{isValid:!1,error:`Settings validation failed:
|
|
337
337
|
${VB6(Y.error,"settings").map((X)=>`- ${X.path}: ${X.message}`).join(`
|
|
338
338
|
`)}`,fullSchema:MU$()}}catch(K){return{isValid:!1,error:`Invalid JSON: ${K instanceof Error?K.message:"Unknown parsing error"}`,fullSchema:MU$()}}}function tM8($,K){if(!$||typeof $!=="object")return[];let Y=$;if(!Y.permissions||typeof Y.permissions!=="object")return[];let J=Y.permissions,q=[];for(let X of["allow","deny","ask"]){let z=J[X];if(!Array.isArray(z))continue;J[X]=z.filter((A)=>{if(typeof A!=="string")return q.push({file:K,path:`permissions.${X}`,message:`Non-string value in ${X} array was removed`,invalidValue:A}),!1;let Z=wU$(A);if(!Z.valid){let H=`Invalid permission rule "${A}" was skipped`;if(Z.error)H+=`: ${Z.error}`;if(Z.suggestion)H+=`. ${Z.suggestion}`;return q.push({file:K,path:`permissions.${X}`,message:H,invalidValue:A}),!1}return!0})}return q}var eM8=B(()=>{M$();DU$();sf4();QI();ef4()});import{join as qk4}from"path";function Lp3(){if($N8)return;$N8=(async()=>{i5("mdm_load_start");let $=Date.now(),K=ob7()??gA8(),{mdm:Y,hkcu:J}=Hk4(await K);EU$=Y,jU$=J,i5("mdm_load_end");let q=Date.now()-$;if(R(`MDM settings load completed in ${q}ms`),Object.keys(Y.settings).length>0){R(`MDM settings found: ${Object.keys(Y.settings).join(", ")}`);try{E$("info","mdm_settings_loaded",{duration_ms:q,key_count:Object.keys(Y.settings).length,error_count:Y.errors.length})}catch{}}})()}async function zk4(){if(!$N8)Lp3();await $N8}function _B6(){return EU$??ri}function OB6(){return jU$??ri}function Ak4($,K){EU$=$,jU$=K}async function Zk4(){let $=await gA8();return Hk4($)}function LU$($,K){let Y=k3($,!1);if(!Y||typeof Y!=="object")return{settings:{},errors:[]};let J=tM8(Y,K),q=b_().safeParse(Y);if(!q.success){let X=VB6(q.error,K);return{settings:{},errors:[...J,...X]}}return{settings:q.data,errors:J}}function Xk4($,K="Settings"){let Y=$.split(/\r?\n/),J=K.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),q=new RegExp(`^\\s+${J}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`,"i");for(let X of Y){let z=X.match(q);if(z?.[1])return z[1].trimEnd()}return null}function Hk4($){if($.plistStdouts&&$.plistStdouts.length>0){let{stdout:K,label:Y}=$.plistStdouts[0],J=LU$(K,Y);if(Object.keys(J.settings).length>0)return{mdm:J,hkcu:ri}}if($.hklmStdout){let K=Xk4($.hklmStdout);if(K){let Y=LU$(K,`Registry: ${xA8}\\${kQ6}`);if(Object.keys(Y.settings).length>0)return{mdm:Y,hkcu:ri}}}if(Ep3())return{mdm:ri,hkcu:ri};if($.hkcuStdout){let K=Xk4($.hkcuStdout);if(K){let Y=LU$(K,`Registry: ${hA8}\\${kQ6}`);return{mdm:ri,hkcu:Y}}}return{mdm:ri,hkcu:ri}}function Ep3(){try{let $=qk4(S_(),"managed-settings.json"),K=oM($),Y=k3(K,!1);if(Y&&typeof Y==="object"&&Object.keys(Y).length>0)return!0}catch{}try{let $=tg(),K=G8().readdirSync($);for(let Y of K){if(!(Y.isFile()||Y.isSymbolicLink())||!Y.name.endsWith(".json")||Y.name.startsWith("."))continue;try{let J=oM(qk4($,Y.name)),q=k3(J,!1);if(q&&typeof q==="object"&&Object.keys(q).length>0)return!0}catch{}}}catch{}return!1}var ri,EU$=null,jU$=null,$N8=null;var KN8=B(()=>{A8();Hq();gF();q4();eX();Kg();xk();QI();eM8();_Y$();wY$();ri=Object.freeze({settings:{},errors:[]})});var _l6={};j8(_l6,{updateSettingsForSource:()=>$4,settingsMergeCustomizer:()=>T86,rawSettingsContainsKey:()=>vU$,parseSettingsFile:()=>oi,loadManagedFileSettings:()=>YN8,hasSkipDangerousModePermissionPrompt:()=>iq6,hasAutoModeOptIn:()=>Vl6,getUseAutoModeDuringPlan:()=>Pp3,getSettings_DEPRECATED:()=>v7,getSettingsWithSources:()=>IU$,getSettingsWithErrors:()=>v86,getSettingsRootPathForSource:()=>C86,getSettingsForSource:()=>o$,getSettingsFilePathForSource:()=>WA,getRelativeSettingsFilePathForSource:()=>I86,getPolicySettingsOrigin:()=>TU$,getManagedSettingsKeysForLogging:()=>CU$,getManagedFileSettingsPresence:()=>PU$,getInitialSettings:()=>_4,getAutoModeConfig:()=>_k4});import{dirname as Gk4,join as QB6,resolve as Wl6}from"path";function FU$(){return QB6(S_(),"managed-settings.json")}function YN8(){let $=[],K={},Y=!1,{settings:J,errors:q}=oi(FU$());if($.push(...q),J&&Object.keys(J).length>0)K=pi(K,J,T86),Y=!0;let X=tg();try{let z=G8().readdirSync(X).filter((A)=>(A.isFile()||A.isSymbolicLink())&&A.name.endsWith(".json")&&!A.name.startsWith(".")).map((A)=>A.name).sort();for(let A of z){let{settings:Z,errors:H}=oi(QB6(X,A));if($.push(...H),Z&&Object.keys(Z).length>0)K=pi(K,Z,T86),Y=!0}}catch(z){let A=c7(z);if(A!=="ENOENT"&&A!=="ENOTDIR")Y6(z)}return{settings:Y?K:null,errors:$}}function PU$(){let{settings:$}=oi(FU$()),K=!!$&&Object.keys($).length>0,Y=!1,J=tg();try{Y=G8().readdirSync(J).some((q)=>(q.isFile()||q.isSymbolicLink())&&q.name.endsWith(".json")&&!q.name.startsWith("."))}catch{}return{hasBase:K,hasDropIns:Y}}function Wk4($,K){if(typeof $==="object"&&$&&"code"in $&&$.code==="ENOENT")R(`Broken symlink or missing file encountered for settings.json at path: ${K}`);else Y6($)}function oi($){let K=Vy7($);if(K)return{settings:K.settings?sK$(K.settings):null,errors:K.errors};let Y=jp3($);return _y7($,Y),{settings:Y.settings?sK$(Y.settings):null,errors:Y.errors}}function jp3($){try{let{resolvedPath:K}=nq(G8(),$),Y=oM(K);if(Y.trim()==="")return{settings:{},errors:[]};let J=k3(Y,!1),q=tM8(J,$),X=b_().safeParse(J);if(!X.success){let z=VB6(X.error,$);return{settings:null,errors:[...q,...z]}}return{settings:X.data,errors:q}}catch(K){return Wk4(K,$),{settings:null,errors:[]}}}function C86($){switch($){case"userSettings":return Wl6(c$());case"policySettings":case"projectSettings":case"localSettings":return Wl6(V7());case"flagSettings":{let K=Ee();return K?Gk4(Wl6(K)):Wl6(V7())}}}function Up3(){if(Zh6()||u6(process.env.CLAUDE_CODE_USE_COWORK_PLUGINS))return"cowork_settings.json";return"settings.json"}function WA($){switch($){case"userSettings":return QB6(C86($),Up3());case"projectSettings":case"localSettings":return QB6(C86($),I86($));case"policySettings":return FU$();case"flagSettings":return Ee()}}function I86($){switch($){case"projectSettings":return QB6(d7,"settings.json");case"localSettings":return QB6(d7,"settings.local.json")}}function o$($){let K=Gy7($);if(K!==void 0)return K;let Y=Vk4($);return Wy7($,Y),Y}function Vk4($){if($==="policySettings"){let J=gk();if(J&&Object.keys(J).length>0)return J;let q=_B6();if(Object.keys(q.settings).length>0)return q.settings;let{settings:X}=YN8();if(X)return X;let z=OB6();if(Object.keys(z.settings).length>0)return z.settings;return null}let K=WA($),{settings:Y}=K?oi(K):{settings:null};if($==="flagSettings"){let J=rO6();if(J){let q=b_().safeParse(J);if(q.success)return pi(Y||{},q.data,T86)}}return Y}function TU$(){let $=gk();if($&&Object.keys($).length>0)return"remote";let K=_B6();if(Object.keys(K.settings).length>0)return C$()==="macos"?"plist":"hklm";let{settings:Y}=YN8();if(Y)return"file";let J=OB6();if(Object.keys(J.settings).length>0)return"hkcu";return null}function $4($,K){if($==="policySettings"||$==="flagSettings")return{error:null};let Y=WA($);if(!Y)return{error:null};try{G8().mkdirSync(Gk4(Y));let J=Vk4($);if(!J){let X=null;try{X=oM(Y)}catch(z){if(!b7(z))throw z}if(X!==null){let z=k3(X);if(z===null)return{error:Error(`Invalid JSON syntax in settings file at ${Y}`)};if(z&&typeof z==="object")J=z,R(`Using raw settings from ${Y} due to validation failure`)}}let q=pi(J||{},K,(X,z,A,Z)=>{if(z===void 0&&Z&&typeof A==="string"){delete Z[A];return}if(Array.isArray(z))return z;return});if(JU$(Y),VN6(Y,`${c6(q,null,2)}
|
|
339
339
|
`),iW(),$==="localSettings")Of4(I86("localSettings"),V7())}catch(J){let q=Error(`Failed to read raw settings from ${Y}: ${J}`);return Y6(q),{error:q}}return{error:null}}function Rp3($,K){return uG([...$,...K])}function T86($,K){if(Array.isArray($)&&Array.isArray(K))return Rp3($,K);return}function CU$($){let K=b_().strip().parse($),Y=["permissions","sandbox","hooks"],J=[],q={permissions:new Set(["allow","deny","ask","defaultMode","disableBypassPermissionsMode",...[],"additionalDirectories"]),sandbox:new Set(["enabled","failIfUnavailable","allowUnsandboxedCommands","network","filesystem","ignoreViolations","excludedCommands","autoAllowBashIfSandboxed","enableWeakerNestedSandbox","enableWeakerNetworkIsolation","ripgrep"]),hooks:new Set(["PreToolUse","PostToolUse","Notification","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","PreCompact","PostCompact","TeammateIdle","TaskCreated","TaskCompleted"])};for(let X of Object.keys(K))if(Y.includes(X)&&K[X]&&typeof K[X]==="object"){let z=K[X],A=q[X];if(A){for(let Z of Object.keys(z))if(A.has(Z))J.push(`${X}.${Z}`)}}else J.push(X);return J.sort()}function Fp3(){if(UU$)return{settings:{},errors:[]};let $=Date.now();i5("loadSettingsFromDisk_start"),E$("info","settings_load_started"),UU$=!0;try{let K=x28(),Y={};if(K)Y=pi(Y,K,T86);let J=[],q=new Set,X=new Set;for(let z of ii()){if(z==="policySettings"){let Z=null,H=[],G=gk();if(G&&Object.keys(G).length>0){let W=b_().safeParse(G);if(W.success)Z=W.data;else H.push(...VB6(W.error,"remote managed settings"))}if(!Z){let W=_B6();if(Object.keys(W.settings).length>0)Z=W.settings;H.push(...W.errors)}if(!Z){let{settings:W,errors:V}=YN8();if(W)Z=W;H.push(...V)}if(!Z){let W=OB6();if(Object.keys(W.settings).length>0)Z=W.settings;H.push(...W.errors)}if(Z)Y=pi(Y,Z,T86);for(let W of H){let V=`${W.file}:${W.path}:${W.message}`;if(!q.has(V))q.add(V),J.push(W)}continue}let A=WA(z);if(A){let Z=Wl6(A);if(!X.has(Z)){X.add(Z);let{settings:H,errors:G}=oi(A);for(let W of G){let V=`${W.file}:${W.path}:${W.message}`;if(!q.has(V))q.add(V),J.push(W)}if(H)Y=pi(Y,H,T86)}}if(z==="flagSettings"){let Z=rO6();if(Z){let H=b_().safeParse(Z);if(H.success)Y=pi(Y,H.data,T86)}}}return E$("info","settings_load_completed",{duration_ms:Date.now()-$,source_count:X.size,error_count:J.length}),{settings:Y,errors:J}}finally{UU$=!1}}function _4(){let{settings:$}=v86();return $||{}}function IU$(){iW();let $=[];for(let K of ii()){let Y=o$(K);if(Y&&Object.keys(Y).length>0)$.push({source:K,settings:Y})}return{effective:_4(),sources:$}}function v86(){let $=Zy7();if($!==null)return $;let K=Fp3();return i5("loadSettingsFromDisk_end"),Hy7(K),K}function iq6(){return!!(o$("userSettings")?.skipDangerousModePermissionPrompt||o$("localSettings")?.skipDangerousModePermissionPrompt||o$("flagSettings")?.skipDangerousModePermissionPrompt||o$("policySettings")?.skipDangerousModePermissionPrompt)}function Vl6(){return!1}function Pp3(){return!0}function _k4(){return}function vU$($){for(let K of ii()){if(K==="policySettings")continue;let Y=WA(K);if(!Y)continue;try{let{resolvedPath:J}=nq(G8(),Y),q=oM(J);if(!q.trim())continue;let X=k3(q,!1);if(X&&typeof X==="object"&&$ in X)return!0}catch(J){Wk4(J,Y)}}return!1}var UU$=!1,v7;var H7=B(()=>{zI4();u8();kM8();A8();Hq();t8();l8();Z9();gF();q4();YU$();eX();i8();n5();M$();Kg();B2();xM8();xk();KN8();gh();QI();eM8();v7=_4});var Ok4=()=>{};import*as Qk4 from"net";import*as wk4 from"http";import{Agent as Tp3}from"https";var _m,yU$;var Dk4=B(()=>{Ok4();_m=Symbol("AgentBaseInternalState");yU$=class yU$ extends wk4.Agent{constructor($){super($);this[_m]={}}isSecureEndpoint($){if($){if(typeof $.secureEndpoint==="boolean")return $.secureEndpoint;if(typeof $.protocol==="string")return $.protocol==="https:"}let{stack:K}=Error();if(typeof K!=="string")return!1;return K.split(`
|
|
@@ -3992,7 +3992,7 @@ Important:
|
|
|
3992
3992
|
- Do not use this tool for built-in CLI commands (like /help, /clear, etc.)
|
|
3993
3993
|
- If you see a <${bM}> tag in the current conversation turn, the skill has ALREADY been loaded - follow the instructions directly instead of calling this tool again
|
|
3994
3994
|
`})});async function F38($,K){try{let Y=await S$8($,K);if(Y!==null)return Y;R(`countTokensWithFallback: API returned null, trying haiku fallback (${K.length} tools)`)}catch(Y){R(`countTokensWithFallback: API failed: ${d6(Y)}`),Y6(Y)}try{let Y=await qy5($,K);if(Y===null)R(`countTokensWithFallback: haiku fallback also returned null (${K.length} tools)`);return Y}catch(Y){return R(`countTokensWithFallback: haiku fallback failed: ${d6(Y)}`),Y6(Y),null}}async function x96($,K,Y,J){let q=await Promise.all($.map((A)=>Hr8(A,{getToolPermissionContext:K,tools:$,agents:Y?.activeAgents??[],model:J}))),X=await F38([],q);if(X!==null)return X;let z=$.map((A)=>A.name).join(", ");return R(`countToolDefinitionTokens returned null/0 for ${$.length} tools: ${z.slice(0,100)}${z.length>100?"...":""}. Falling back to local estimation.`),N3(c6(q),2)}function AXY($){let K=$.match(/^#+\s+(.+)$/m);if(K)return K[1].trim();let Y=$.split(`
|
|
3995
|
-
`).find((J)=>J.trim().length>0)??"";return Y.length>40?`${Y.slice(0,40)}\u2026`:Y}async function ZXY($){let K=await H2(),Y=[...$.filter((z)=>z.length>0&&z!==MW6).map((z)=>({name:AXY(z),content:z})),...Object.entries(K).filter(([,z])=>z.length>0).map(([z,A])=>({name:z,content:A}))];if(Y.length<1)return{systemPromptTokens:0,systemPromptSections:[]};let J=await Promise.all(Y.map(async({content:z})=>{return await F38([{role:"user",content:z}],[])??N3(z)})),q=Y.map((z,A)=>({name:z.name,tokens:J[A]||0,preview:z.content.length>0?z.content.slice(0,500):void 0}));return{systemPromptTokens:J.reduce((z,A)=>z+(A||0),0),systemPromptSections:q}}async function HXY(){if(u6(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],claudeMdTokens:0};let $=Gr8(await ZG()),K=[],Y=0;if($.length<1)return{memoryFileDetails:[],claudeMdTokens:0};let J=await Promise.all($.map(async(q)=>{let X=await F38([{role:"user",content:q.content}],[]);return{file:q,tokens:X??N3(q.content)}}));for(let{file:q,tokens:X}of J)Y+=X,K.push({path:q.path,type:q.type,tokens:X});return{claudeMdTokens:Y,memoryFileDetails:K}}async function GXY($,K,Y,J,q){let X=$.filter((D)=>!D.isMcp);if(X.length<1)return{builtInToolTokens:0,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:[]};let{isToolSearchEnabled:z}=await Promise.resolve().then(() => (kv(),BG7)),{isDeferredTool:A}=await Promise.resolve().then(() => (oa(),lt$)),Z=await z(J??"",$,K,Y?.activeAgents??[],"analyzeBuiltIn"),H=X.filter((D)=>!A(D)),G=X.filter((D)=>A(D)),W=H.length>0?await x96(H,K,Y,J):0,V=[];if(process.env.USER_TYPE==="ant"){let D=H.filter((N)=>!bK(N,XG));if(D.length>0){let N=D.map((F)=>N3(c6(F.inputSchema??{}))),L=N.reduce((F,P)=>F+P,0)||1,E=Math.max(0,W-R38);V=D.map((F,P)=>({name:F.name,tokens:Math.round(N[P]/L*E)})).sort((F,P)=>P.tokens-F.tokens)}}let _=[],O=0,w=0;if(G.length>0&&Z){let D=new Set;if(q){let L=new Set(G.map((E)=>E.name));for(let E of q)if(E.type==="assistant"){for(let F of E.message.content)if("type"in F&&F.type==="tool_use"&&"name"in F&&typeof F.name==="string"&&L.has(F.name))D.add(F.name)}}let N=await Promise.all(G.map((L)=>x96([L],K,Y,J)));for(let[L,E]of G.entries()){let F=Math.max(0,(N[L]||0)-R38),P=D.has(E.name);if(_.push({name:E.name,tokens:F,isLoaded:P}),w+=F,P)O+=F}}else if(G.length>0){let D=await x96(G,K,Y,J);return{builtInToolTokens:W+D,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:V}}return{builtInToolTokens:W+O,deferredBuiltinDetails:_,deferredBuiltinTokens:w-O,systemToolDetails:V}}function Yy5($){return M3($,XG)}async function WXY($,K,Y){let J=await OG7(P8()),q=Yy5($);if(!q)return{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}};return{slashCommandTokens:await x96([q],K,Y),commandInfo:{totalCommands:J.totalCommands,includedCommands:J.includedCommands}}}async function VXY($,K,Y,J){try{let q=await QG7(P8()),X=Yy5($);if(!X)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let z=await x96([X],K,Y,J),A=q.map((Z)=>{let G=Z.type==="plugin"||Z.source==="plugin"?Z.pluginInfo?.pluginManifest?.name:void 0;return{name:G?`${t0(Z)} (${G})`:t0(Z),source:Z.type==="prompt"?Z.source:"plugin",pluginName:G,tokens:pa8(Z)}});return{skillTokens:z,skillInfo:{totalSkills:q.length,includedSkills:q.length,skillFrontmatter:A}}}catch(q){return Y6($7(q)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function NG7($,K,Y,J,q){let X=$.filter((L)=>L.isMcp),z=[],A=await x96(X,K,Y,J),Z=Math.max(0,(A||0)-R38),H=await Promise.all(X.map(async(L)=>N3(c6({name:L.name,description:await L.prompt({getToolPermissionContext:K,tools:$,agents:Y?.activeAgents??[]}),input_schema:L.inputJSONSchema??{}})))),G=H.reduce((L,E)=>L+E,0)||1,W=H.map((L)=>Math.round(L/G*Z)),{isToolSearchEnabled:V}=await Promise.resolve().then(() => (kv(),BG7)),{isDeferredTool:_}=await Promise.resolve().then(() => (oa(),lt$)),O=await V(J,$,K,Y?.activeAgents??[],"analyzeMcp"),w=new Set;if(O&&q){let L=new Set(X.map((E)=>E.name));for(let E of q)if(E.type==="assistant"){for(let F of E.message.content)if("type"in F&&F.type==="tool_use"&&"name"in F&&typeof F.name==="string"&&L.has(F.name))w.add(F.name)}}for(let[L,E]of X.entries())z.push({name:E.name,serverName:E.name.split("__")[1]||"unknown",tokens:W[L],isLoaded:w.has(E.name)||!_(E)});let D=0,N=0;for(let L of z)if(L.isLoaded)D+=L.tokens;else if(O)N+=L.tokens;return{mcpToolTokens:O?D:Z,mcpToolDetails:z,deferredToolTokens:N,loadedMcpToolNames:w}}async function _XY($){let K=$.activeAgents.filter((X)=>X.source!=="built-in"),Y=[],J=0,q=await Promise.all(K.map(async(X)=>{let z=[X.agentType,X.whenToUse].join(" ");return await F38([{role:"user",content:z}],[])??N3(z)}));for(let[X,z]of K.entries()){let A=q[X]||0;J+=A||0,Y.push({agentType:z.agentType,source:z.source,tokens:A||0})}return{agentTokens:J,agentDetails:Y}}function OXY($,K){for(let Y of $.message.content){let J=c6(Y),q=N3(J);if("type"in Y&&Y.type==="tool_use"){K.toolCallTokens+=q;let X=("name"in Y?Y.name:void 0)||"unknown";K.toolCallsByType.set(X,(K.toolCallsByType.get(X)||0)+q)}else K.assistantMessageTokens+=q}}function QXY($,K,Y){if(typeof $.message.content==="string"){let J=N3($.message.content);K.userMessageTokens+=J;return}for(let J of $.message.content){let q=c6(J),X=N3(q);if("type"in J&&J.type==="tool_result"){K.toolResultTokens+=X;let z="tool_use_id"in J?J.tool_use_id:void 0,A=(z?Y.get(z):void 0)||"unknown";K.toolResultsByType.set(A,(K.toolResultsByType.get(A)||0)+X)}else K.userMessageTokens+=X}}function wXY($,K){let Y=c6($.attachment),J=N3(Y);K.attachmentTokens+=J;let q=$.attachment.type||"unknown";K.attachmentsByType.set(q,(K.attachmentsByType.get(q)||0)+J)}async function DXY($){let K=await p46($),Y={totalTokens:0,toolCallTokens:0,toolResultTokens:0,attachmentTokens:0,assistantMessageTokens:0,userMessageTokens:0,toolCallsByType:new Map,toolResultsByType:new Map,attachmentsByType:new Map},J=new Map;for(let X of K.messages)if(X.type==="assistant"){for(let z of X.message.content)if("type"in z&&z.type==="tool_use"){let A="id"in z?z.id:void 0,Z=("name"in z?z.name:void 0)||"unknown";if(A)J.set(A,Z)}}for(let X of K.messages)if(X.type==="assistant")OXY(X,Y);else if(X.type==="user")QXY(X,Y,J);else if(X.type==="attachment")wXY(X,Y);let q=await F38(AW(K.messages).map((X)=>{if(X.type==="assistant")return{role:"assistant",content:X.message.content};return X.message}),[]);return Y.totalTokens=q??uP(K.messages),Y}async function Jy5($,K,Y,J,q,X,z,A,Z){let H=oj({permissionMode:(await Y()).mode,mainLoopModel:K}),G=tG(H,CG()),W=await jW(J,H),V=zR({mainThreadAgentDefinition:A,toolUseContext:z??{options:{}},customSystemPrompt:z?.options.customSystemPrompt,defaultSystemPrompt:W,appendSystemPrompt:z?.options.appendSystemPrompt}),[{systemPromptTokens:_,systemPromptSections:O},{claudeMdTokens:w,memoryFileDetails:D},{builtInToolTokens:N,deferredBuiltinDetails:L,deferredBuiltinTokens:E,systemToolDetails:F},{mcpToolTokens:P,mcpToolDetails:C,deferredToolTokens:k},{agentTokens:f,agentDetails:y},{slashCommandTokens:x,commandInfo:S},m]=await Promise.all([ZXY(V),HXY(),GXY(J,Y,q,H,$),NG7(J,Y,q,H,$),_XY(q),WXY(J,Y,q),DXY($)]),b=(await VXY(J,Y,q,H)).skillInfo,i=b.skillFrontmatter.reduce((J8,f6)=>J8+f6.tokens,0),n=m.totalTokens,p=iy(),o=p?bc(K)-HG7:void 0,G6=[];if(_>0)G6.push({name:"System prompt",tokens:_,color:"promptBorder"});let Z6=N-i;if(Z6>0)G6.push({name:process.env.USER_TYPE==="ant"?"[ANT-ONLY] System tools":"System tools",tokens:Z6,color:"inactive"});if(P>0)G6.push({name:"MCP tools",tokens:P,color:"cyan_FOR_SUBAGENTS_ONLY"});if(k>0)G6.push({name:"MCP tools (deferred)",tokens:k,color:"inactive",isDeferred:!0});if(E>0)G6.push({name:"System tools (deferred)",tokens:E,color:"inactive",isDeferred:!0});if(f>0)G6.push({name:"Custom agents",tokens:f,color:"permission"});if(w>0)G6.push({name:"Memory files",tokens:w,color:"claude"});if(i>0)G6.push({name:"Skills",tokens:i,color:"warning"});if(n!==null&&n>0)G6.push({name:"Messages",tokens:n,color:"purple_FOR_SUBAGENTS_ONLY"});let N6=G6.reduce((J8,f6)=>J8+(f6.isDeferred?0:f6.tokens),0),D6=0;if(!1);else if(p&&o!==void 0)D6=G-o,G6.push({name:DG7,tokens:D6,color:"inactive"});else if(!p)D6=GG7,G6.push({name:MG7,tokens:D6,color:"inactive"});let $6=Math.max(0,G-N6-D6);G6.push({name:"Free space",tokens:$6,color:"promptBorder"});let X6=N6,V6=H68(Z??$),q6=(V6?V6.input_tokens+V6.cache_creation_input_tokens+V6.cache_read_input_tokens:null)??X6,_6=X&&X<80,B6=G>=1e6?_6?5:20:_6?5:10,M6=G>=1e6?10:_6?5:10,A6=B6*M6,W6=G6.filter((J8)=>!J8.isDeferred).map((J8)=>({...J8,squares:J8.name==="Free space"?Math.round(J8.tokens/G*A6):Math.max(1,Math.round(J8.tokens/G*A6)),percentageOfTotal:Math.round(J8.tokens/G*100)}));function k6(J8){let f6=[],L8=J8.tokens/G*A6,J6=Math.floor(L8),U6=L8-J6;for(let w6=0;w6<J8.squares;w6++){let y6=1;if(w6===J6&&U6>0)y6=U6;f6.push({color:J8.color,isFilled:!0,categoryName:J8.name,tokens:J8.tokens,percentage:J8.percentageOfTotal,squareFullness:y6})}return f6}let L6=[],m6=W6.find((J8)=>J8.name===DG7||J8.name===MG7),T6=W6.filter((J8)=>J8.name!==DG7&&J8.name!==MG7&&J8.name!=="Free space");for(let J8 of T6){let f6=k6(J8);for(let L8 of f6)if(L6.length<A6)L6.push(L8)}let n6=m6?m6.squares:0,F8=G6.find((J8)=>J8.name==="Free space"),_8=A6-n6;while(L6.length<_8)L6.push({color:"promptBorder",isFilled:!0,categoryName:"Free space",tokens:F8?.tokens||0,percentage:F8?Math.round(F8.tokens/G*100):0,squareFullness:1});if(m6){let J8=k6(m6);for(let f6 of J8)if(L6.length<A6)L6.push(f6)}let Z8=[];for(let J8=0;J8<M6;J8++)Z8.push(L6.slice(J8*B6,(J8+1)*B6));let h6=new Map;for(let[J8,f6]of m.toolCallsByType.entries()){let L8=h6.get(J8)||{callTokens:0,resultTokens:0};h6.set(J8,{...L8,callTokens:f6})}for(let[J8,f6]of m.toolResultsByType.entries()){let L8=h6.get(J8)||{callTokens:0,resultTokens:0};h6.set(J8,{...L8,resultTokens:f6})}let M8=Array.from(h6.entries()).map(([J8,{callTokens:f6,resultTokens:L8}])=>({name:J8,callTokens:f6,resultTokens:L8})).sort((J8,f6)=>f6.callTokens+f6.resultTokens-(J8.callTokens+J8.resultTokens)),S6=Array.from(m.attachmentsByType.entries()).map(([J8,f6])=>({name:J8,tokens:f6})).sort((J8,f6)=>f6.tokens-J8.tokens),w8={toolCallTokens:m.toolCallTokens,toolResultTokens:m.toolResultTokens,attachmentTokens:m.attachmentTokens,assistantMessageTokens:m.assistantMessageTokens,userMessageTokens:m.userMessageTokens,toolCallsByType:M8,attachmentsByType:S6};return{categories:G6,totalTokens:q6,maxTokens:G,rawMaxTokens:G,percentage:Math.round(q6/G*100),gridRows:Z8,model:H,memoryFiles:D,mcpTools:C,deferredBuiltinTools:process.env.USER_TYPE==="ant"?L:void 0,systemTools:process.env.USER_TYPE==="ant"?F:void 0,systemPromptSections:process.env.USER_TYPE==="ant"?O:void 0,agents:y,slashCommands:x>0?{totalCommands:S.totalCommands,includedCommands:S.includedCommands,tokens:x}:void 0,skills:i>0?{totalSkills:b.totalSkills,includedSkills:b.includedSkills,tokens:i,skillFrontmatter:b.skillFrontmatter}:void 0,autoCompactThreshold:o,isAutoCompactEnabled:p,messageBreakdown:w8,apiUsage:V6}}var DG7="Autocompact buffer",MG7="Compact buffer",R38=500;var Zr8=B(()=>{KR();eS();u8();bX();lN();a7();po();gL();Ic();V4();DW6();NW6();SV();c_();R7();A8();t8();l8();i8();Q7();P1();M$();iG6();TN()});function MXY($){return $.replace(/\(\?[=!<][^)]*\)/g,"")}function zy5($){for(let K of Object.keys($)){let Y=$[K];if(K==="pattern"&&typeof Y==="string")$[K]=MXY(Y);else if(Y!==null&&typeof Y==="object")zy5(Y)}return $}function Vs($){let K=Xy5.get($);if(K)return K;let Y=zy5(Hm($));return Xy5.set($,Y),Y}var Xy5;var Wr8=B(()=>{g7();Xy5=new WeakMap});var BG7={};j8(BG7,{modelSupportsToolReference:()=>P38,isToolSearchToolAvailable:()=>iZ6,isToolSearchEnabledOptimistic:()=>cP,isToolSearchEnabled:()=>N38,isToolReferenceBlock:()=>Fx,isDeferredToolsDeltaEnabled:()=>T38,getToolSearchMode:()=>jG7,getDeferredToolsDelta:()=>UG7,getAutoToolSearchCharThreshold:()=>Hy5,extractDiscoveredToolNames:()=>yb});function Ay5($){if(!$.startsWith("auto:"))return null;let K=$.slice(5),Y=parseInt(K,10);if(Number.isNaN(Y))return R(`Invalid ENABLE_TOOL_SEARCH value "${$}": expected auto:N where N is a number.`),null;return Math.max(0,Math.min(100,Y))}function NXY($){if(!$)return!1;return $==="auto"||$.startsWith("auto:")}function EG7(){let $=process.env.ENABLE_TOOL_SEARCH;if(!$)return LG7;if($==="auto")return LG7;let K=Ay5($);if(K!==null)return K;return LG7}function Zy5($){let K=gT8($),Y=tG($,K),J=EG7()/100;return Math.floor(Y*J)}function Hy5($){return Math.floor(Zy5($)*BXY)}function jG7(){if(u6(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return"standard";let $=process.env.ENABLE_TOOL_SEARCH,K=$?Ay5($):null;if(K===0)return"tst";if(K===100)return"standard";if(NXY($))return"tst-auto";if(u6($))return"tst";if(z0(process.env.ENABLE_TOOL_SEARCH))return"standard";return"tst"}function jXY(){try{let $=u$("tengu_tool_search_unsupported_models",null);if($&&Array.isArray($)&&$.length>0)return $}catch{}return EXY}function P38($){let K=$.toLowerCase(),Y=jXY();for(let J of Y)if(K.includes(J.toLowerCase()))return!1;return!0}function cP(){let $=jG7();if($==="standard"){if(!dy6)dy6=!0,R(`[ToolSearch:optimistic] mode=${$}, ENABLE_TOOL_SEARCH=${process.env.ENABLE_TOOL_SEARCH}, result=false`);return!1}if(!process.env.ENABLE_TOOL_SEARCH&&r7()==="firstParty"&&!m_()){if(!dy6)dy6=!0,R(`[ToolSearch:optimistic] disabled: ANTHROPIC_BASE_URL=${process.env.ANTHROPIC_BASE_URL} is not a first-party Anthropic host. Set ENABLE_TOOL_SEARCH=true (or auto / auto:N) if your proxy forwards tool_reference blocks.`);return!1}if(!dy6)dy6=!0,R(`[ToolSearch:optimistic] mode=${$}, ENABLE_TOOL_SEARCH=${process.env.ENABLE_TOOL_SEARCH}, result=true`);return!0}function iZ6($){return $.some((K)=>bK(K,ND))}async function UXY($,K,Y){let J=$.filter((X)=>yv(X));if(J.length===0)return 0;return(await Promise.all(J.map(async(X)=>{let z=await X.prompt({getToolPermissionContext:K,tools:$,agents:Y}),A=X.inputJSONSchema?c6(X.inputJSONSchema):X.inputSchema?c6(Vs(X.inputSchema)):"";return X.name.length+z.length+A.length}))).reduce((X,z)=>X+z,0)}async function N38($,K,Y,J,q){let X=e7(K,(Z)=>Z.isMcp);function z(Z,H,G,W){d("tengu_tool_search_mode_decision",{enabled:Z,mode:H,reason:G,checkedModel:$,mcpToolCount:X,userType:process.env.USER_TYPE??"external",...W})}if(!P38($))return R(`Tool search disabled for model '${$}': model does not support tool_reference blocks. This feature is only available on Claude Sonnet 4+, Opus 4+, and newer models.`),z(!1,"standard","model_unsupported"),!1;if(!iZ6(K))return R("Tool search disabled: ToolSearchTool is not available (may have been disallowed via disallowedTools)."),z(!1,"standard","mcp_search_unavailable"),!1;let A=jG7();switch(A){case"tst":return z(!0,A,"tst_enabled"),!0;case"tst-auto":{let{enabled:Z,debugDescription:H,metrics:G}=await PXY(K,Y,J,$);if(Z)return R(`Auto tool search enabled: ${H}${q?` [source: ${q}]`:""}`),z(!0,A,"auto_above_threshold",G),!0;return R(`Auto tool search disabled: ${H}${q?` [source: ${q}]`:""}`),z(!1,A,"auto_below_threshold",G),!1}case"standard":return z(!1,A,"standard_mode"),!1}}function Fx($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="tool_reference"}function RXY($){return Fx($)&&"tool_name"in $&&typeof $.tool_name==="string"}function FXY($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="tool_result"&&"content"in $&&Array.isArray($.content)}function yb($){let K=new Set,Y=0;for(let J of $){if(J.type==="system"&&J.subtype==="compact_boundary"){let X=J.compactMetadata?.preCompactDiscoveredTools;if(X){for(let z of X)K.add(z);Y+=X.length}continue}if(J.type!=="user")continue;let q=J.message?.content;if(!Array.isArray(q))continue;for(let X of q)if(FXY(X)){for(let z of X.content)if(RXY(z))K.add(z.tool_name)}}if(K.size>0)R(`Dynamic tool loading: found ${K.size} discovered tools in message history`+(Y>0?` (${Y} carried from compact boundary)`:""));return K}function T38(){return process.env.USER_TYPE==="ant"||u$("tengu_glacier_2xr",!1)}function UG7($,K,Y){let J=new Set,q=0,X=0,z=new Set;for(let V of K){if(V.type!=="attachment")continue;if(q++,z.add(V.attachment.type),V.attachment.type!=="deferred_tools_delta")continue;X++;for(let _ of V.attachment.addedNames)J.add(_);for(let _ of V.attachment.removedNames)J.delete(_)}let A=$.filter(yv),Z=new Set(A.map((V)=>V.name)),H=new Set($.map((V)=>V.name)),G=A.filter((V)=>!J.has(V.name)),W=[];for(let V of J){if(Z.has(V))continue;if(!H.has(V))W.push(V)}if(G.length===0&&W.length===0)return null;return d("tengu_deferred_tools_pool_change",{addedCount:G.length,removedCount:W.length,priorAnnouncedCount:J.size,messagesLength:K.length,attachmentCount:q,dtdCount:X,callSite:Y?.callSite??"unknown",querySource:Y?.querySource??"unknown",attachmentTypesSeen:[...z].sort().join(",")}),{addedNames:G.map((V)=>V.name).sort(),addedLines:G.map(X68).sort(),removedNames:W.sort()}}async function PXY($,K,Y,J){let q=await LXY($,K,Y,J);if(q!==null){let A=Zy5(J);return{enabled:q>=A,debugDescription:`${q} tokens (threshold: ${A}, ${EG7()}% of context)`,metrics:{deferredToolTokens:q,threshold:A}}}let X=await UXY($,K,Y),z=Hy5(J);return{enabled:X>=z,debugDescription:`${X} chars (threshold: ${z}, ${EG7()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:X,charThreshold:z}}}var LG7=10,BXY=2.5,LXY,EXY,dy6=!1;var kv=B(()=>{S5();a7();d8();V4();oa();Zr8();zD();c_();A8();t8();lK();M$();Wr8();LXY=F$(async($,K,Y,J)=>{let q=$.filter((X)=>yv(X));if(q.length===0)return 0;try{let X=await x96(q,K,{activeAgents:Y,allAgents:Y},J);if(X===0)return null;return Math.max(0,X-R38)}catch{return null}},($)=>$.filter((K)=>yv(K)).map((K)=>K.name).join(","));EXY=["haiku"]});import{createHash as Wy5,randomUUID as TXY}from"crypto";import{mkdir as Vy5,readFile as _y5,writeFile as Oy5}from"fs/promises";import{dirname as Qy5,join as wy5}from"path";function FG7(){if(process.env.USER_TYPE==="ant"&&u6(process.env.FORCE_VCR))return!0;return!1}async function CXY($,K,Y){if(!FG7())return await Y();let J=Wy5("sha1").update(c6($)).digest("hex").slice(0,12),q=wy5(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??P8(),`fixtures/${K}-${J}.json`);try{return Q$(await _y5(q,{encoding:"utf8"}))}catch(z){if(c7(z)!=="ENOENT")throw z}if((F7.isCI||process.env.CI)&&!u6(process.env.VCR_RECORD))throw Error(`Fixture missing: ${q}. Re-run tests with VCR_RECORD=1, then commit the result.`);let X=await Y();return await Vy5(Qy5(q),{recursive:!0}),await Oy5(q,c6(X,null,2),{encoding:"utf8"}),X}async function _r8($,K){if(!FG7())return await K();let Y=AW($.filter((z)=>{if(z.type!=="user")return!0;if(z.isMeta)return!1;return!0})),J=vXY(Y.map((z)=>z.message.content),RG7),q=wy5(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??P8(),`fixtures/${J.map((z)=>Wy5("sha1").update(c6(z)).digest("hex").slice(0,6)).join("-")}.json`);try{let z=Q$(await _y5(q,{encoding:"utf8"}));return z.output.forEach(IXY),z.output.map((A,Z)=>Gy5(A,fXY,Z,TXY()))}catch(z){if(c7(z)!=="ENOENT")throw z}if(F7.isCI&&!u6(process.env.VCR_RECORD))throw Error(`Anthropic API fixture missing: ${q}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:
|
|
3995
|
+
`).find((J)=>J.trim().length>0)??"";return Y.length>40?`${Y.slice(0,40)}\u2026`:Y}async function ZXY($){let K=await H2(),Y=[...$.filter((z)=>z.length>0&&z!==MW6).map((z)=>({name:AXY(z),content:z})),...Object.entries(K).filter(([,z])=>z.length>0).map(([z,A])=>({name:z,content:A}))];if(Y.length<1)return{systemPromptTokens:0,systemPromptSections:[]};let J=await Promise.all(Y.map(async({content:z})=>{return await F38([{role:"user",content:z}],[])??N3(z)})),q=Y.map((z,A)=>({name:z.name,tokens:J[A]||0,preview:z.content.length>0?z.content.slice(0,500):void 0}));return{systemPromptTokens:J.reduce((z,A)=>z+(A||0),0),systemPromptSections:q}}async function HXY(){if(u6(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],claudeMdTokens:0};let $=Gr8(await ZG()),K=[],Y=0;if($.length<1)return{memoryFileDetails:[],claudeMdTokens:0};let J=await Promise.all($.map(async(q)=>{let X=await F38([{role:"user",content:q.content}],[]);return{file:q,tokens:X??N3(q.content)}}));for(let{file:q,tokens:X}of J)Y+=X,K.push({path:q.path,type:q.type,tokens:X});return{claudeMdTokens:Y,memoryFileDetails:K}}async function GXY($,K,Y,J,q){let X=$.filter((D)=>!D.isMcp);if(X.length<1)return{builtInToolTokens:0,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:[]};let{isToolSearchEnabled:z}=await Promise.resolve().then(() => (kv(),BG7)),{isDeferredTool:A}=await Promise.resolve().then(() => (oa(),lt$)),Z=await z(J??"",$,K,Y?.activeAgents??[],"analyzeBuiltIn"),H=X.filter((D)=>!A(D)),G=X.filter((D)=>A(D)),W=H.length>0?await x96(H,K,Y,J):0,V=[];if(process.env.USER_TYPE==="ant"){let D=H.filter((N)=>!bK(N,XG));if(D.length>0){let N=D.map((F)=>N3(c6(F.inputSchema??{}))),L=N.reduce((F,P)=>F+P,0)||1,E=Math.max(0,W-R38);V=D.map((F,P)=>({name:F.name,tokens:Math.round(N[P]/L*E)})).sort((F,P)=>P.tokens-F.tokens)}}let _=[],O=0,w=0;if(G.length>0&&Z){let D=new Set;if(q){let L=new Set(G.map((E)=>E.name));for(let E of q)if(E.type==="assistant"){for(let F of E.message.content)if("type"in F&&F.type==="tool_use"&&"name"in F&&typeof F.name==="string"&&L.has(F.name))D.add(F.name)}}let N=await Promise.all(G.map((L)=>x96([L],K,Y,J)));for(let[L,E]of G.entries()){let F=Math.max(0,(N[L]||0)-R38),P=D.has(E.name);if(_.push({name:E.name,tokens:F,isLoaded:P}),w+=F,P)O+=F}}else if(G.length>0){let D=await x96(G,K,Y,J);return{builtInToolTokens:W+D,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:V}}return{builtInToolTokens:W+O,deferredBuiltinDetails:_,deferredBuiltinTokens:w-O,systemToolDetails:V}}function Yy5($){return M3($,XG)}async function WXY($,K,Y){let J=await OG7(P8()),q=Yy5($);if(!q)return{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}};return{slashCommandTokens:await x96([q],K,Y),commandInfo:{totalCommands:J.totalCommands,includedCommands:J.includedCommands}}}async function VXY($,K,Y,J){try{let q=await QG7(P8()),X=Yy5($);if(!X)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let z=await x96([X],K,Y,J),A=q.map((Z)=>{let G=Z.type==="plugin"||Z.source==="plugin"?Z.pluginInfo?.pluginManifest?.name:void 0;return{name:G?`${t0(Z)} (${G})`:t0(Z),source:Z.type==="prompt"?Z.source:"plugin",pluginName:G,tokens:pa8(Z)}});return{skillTokens:z,skillInfo:{totalSkills:q.length,includedSkills:q.length,skillFrontmatter:A}}}catch(q){return Y6($7(q)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function NG7($,K,Y,J,q){let X=$.filter((L)=>L.isMcp),z=[],A=await x96(X,K,Y,J),Z=Math.max(0,(A||0)-R38),H=await Promise.all(X.map(async(L)=>N3(c6({name:L.name,description:await L.prompt({getToolPermissionContext:K,tools:$,agents:Y?.activeAgents??[]}),input_schema:L.inputJSONSchema??{}})))),G=H.reduce((L,E)=>L+E,0)||1,W=H.map((L)=>Math.round(L/G*Z)),{isToolSearchEnabled:V}=await Promise.resolve().then(() => (kv(),BG7)),{isDeferredTool:_}=await Promise.resolve().then(() => (oa(),lt$)),O=await V(J,$,K,Y?.activeAgents??[],"analyzeMcp"),w=new Set;if(O&&q){let L=new Set(X.map((E)=>E.name));for(let E of q)if(E.type==="assistant"){for(let F of E.message.content)if("type"in F&&F.type==="tool_use"&&"name"in F&&typeof F.name==="string"&&L.has(F.name))w.add(F.name)}}for(let[L,E]of X.entries())z.push({name:E.name,serverName:E.name.split("__")[1]||"unknown",tokens:W[L],isLoaded:w.has(E.name)||!_(E)});let D=0,N=0;for(let L of z)if(L.isLoaded)D+=L.tokens;else if(O)N+=L.tokens;return{mcpToolTokens:O?D:Z,mcpToolDetails:z,deferredToolTokens:N,loadedMcpToolNames:w}}async function _XY($){let K=$.activeAgents.filter((X)=>X.source!=="built-in"),Y=[],J=0,q=await Promise.all(K.map(async(X)=>{let z=[X.agentType,X.whenToUse].join(" ");return await F38([{role:"user",content:z}],[])??N3(z)}));for(let[X,z]of K.entries()){let A=q[X]||0;J+=A||0,Y.push({agentType:z.agentType,source:z.source,tokens:A||0})}return{agentTokens:J,agentDetails:Y}}function OXY($,K){for(let Y of $.message.content){let J=c6(Y),q=N3(J);if("type"in Y&&Y.type==="tool_use"){K.toolCallTokens+=q;let X=("name"in Y?Y.name:void 0)||"unknown";K.toolCallsByType.set(X,(K.toolCallsByType.get(X)||0)+q)}else K.assistantMessageTokens+=q}}function QXY($,K,Y){if(typeof $.message.content==="string"){let J=N3($.message.content);K.userMessageTokens+=J;return}for(let J of $.message.content){let q=c6(J),X=N3(q);if("type"in J&&J.type==="tool_result"){K.toolResultTokens+=X;let z="tool_use_id"in J?J.tool_use_id:void 0,A=(z?Y.get(z):void 0)||"unknown";K.toolResultsByType.set(A,(K.toolResultsByType.get(A)||0)+X)}else K.userMessageTokens+=X}}function wXY($,K){let Y=c6($.attachment),J=N3(Y);K.attachmentTokens+=J;let q=$.attachment.type||"unknown";K.attachmentsByType.set(q,(K.attachmentsByType.get(q)||0)+J)}async function DXY($){let K=await p46($),Y={totalTokens:0,toolCallTokens:0,toolResultTokens:0,attachmentTokens:0,assistantMessageTokens:0,userMessageTokens:0,toolCallsByType:new Map,toolResultsByType:new Map,attachmentsByType:new Map},J=new Map;for(let X of K.messages)if(X.type==="assistant"){for(let z of X.message.content)if("type"in z&&z.type==="tool_use"){let A="id"in z?z.id:void 0,Z=("name"in z?z.name:void 0)||"unknown";if(A)J.set(A,Z)}}for(let X of K.messages)if(X.type==="assistant")OXY(X,Y);else if(X.type==="user")QXY(X,Y,J);else if(X.type==="attachment")wXY(X,Y);let q=await F38(AW(K.messages).map((X)=>{if(X.type==="assistant")return{role:"assistant",content:X.message.content};return X.message}),[]);return Y.totalTokens=q??uP(K.messages),Y}async function Jy5($,K,Y,J,q,X,z,A,Z){let H=oj({permissionMode:(await Y()).mode,mainLoopModel:K}),G=tG(H,CG()),W=await jW(J,H),V=zR({mainThreadAgentDefinition:A,toolUseContext:z??{options:{}},customSystemPrompt:z?.options.customSystemPrompt,defaultSystemPrompt:W,appendSystemPrompt:z?.options.appendSystemPrompt}),[{systemPromptTokens:_,systemPromptSections:O},{claudeMdTokens:w,memoryFileDetails:D},{builtInToolTokens:N,deferredBuiltinDetails:L,deferredBuiltinTokens:E,systemToolDetails:F},{mcpToolTokens:P,mcpToolDetails:C,deferredToolTokens:k},{agentTokens:f,agentDetails:y},{slashCommandTokens:x,commandInfo:S},m]=await Promise.all([ZXY(V),HXY(),GXY(J,Y,q,H,$),NG7(J,Y,q,H,$),_XY(q),WXY(J,Y,q),DXY($)]),b=(await VXY(J,Y,q,H)).skillInfo,i=b.skillFrontmatter.reduce((J8,f6)=>J8+f6.tokens,0),n=m.totalTokens,p=iy(),o=p?bc(K)-HG7:void 0,G6=[];if(_>0)G6.push({name:"System prompt",tokens:_,color:"promptBorder"});let Z6=N-i;if(Z6>0)G6.push({name:process.env.USER_TYPE==="ant"?"[ANT-ONLY] System tools":"System tools",tokens:Z6,color:"inactive"});if(P>0)G6.push({name:"MCP tools",tokens:P,color:"cyan_FOR_SUBAGENTS_ONLY"});if(k>0)G6.push({name:"MCP tools (deferred)",tokens:k,color:"inactive",isDeferred:!0});if(E>0)G6.push({name:"System tools (deferred)",tokens:E,color:"inactive",isDeferred:!0});if(f>0)G6.push({name:"Custom agents",tokens:f,color:"permission"});if(w>0)G6.push({name:"Memory files",tokens:w,color:"claude"});if(i>0)G6.push({name:"Skills",tokens:i,color:"warning"});if(n!==null&&n>0)G6.push({name:"Messages",tokens:n,color:"purple_FOR_SUBAGENTS_ONLY"});let N6=G6.reduce((J8,f6)=>J8+(f6.isDeferred?0:f6.tokens),0),D6=0;if(!1);else if(p&&o!==void 0)D6=G-o,G6.push({name:DG7,tokens:D6,color:"inactive"});else if(!p)D6=GG7,G6.push({name:MG7,tokens:D6,color:"inactive"});let $6=Math.max(0,G-N6-D6);G6.push({name:"Free space",tokens:$6,color:"promptBorder"});let X6=N6,V6=H68(Z??$),q6=(V6?V6.input_tokens+V6.cache_creation_input_tokens+V6.cache_read_input_tokens:null)??X6,_6=X&&X<80,B6=G>=1e6?_6?5:20:_6?5:10,M6=G>=1e6?10:_6?5:10,A6=B6*M6,W6=G6.filter((J8)=>!J8.isDeferred).map((J8)=>({...J8,squares:J8.name==="Free space"?Math.round(J8.tokens/G*A6):Math.max(1,Math.round(J8.tokens/G*A6)),percentageOfTotal:Math.round(J8.tokens/G*100)}));function k6(J8){let f6=[],L8=J8.tokens/G*A6,J6=Math.floor(L8),U6=L8-J6;for(let w6=0;w6<J8.squares;w6++){let y6=1;if(w6===J6&&U6>0)y6=U6;f6.push({color:J8.color,isFilled:!0,categoryName:J8.name,tokens:J8.tokens,percentage:J8.percentageOfTotal,squareFullness:y6})}return f6}let L6=[],m6=W6.find((J8)=>J8.name===DG7||J8.name===MG7),T6=W6.filter((J8)=>J8.name!==DG7&&J8.name!==MG7&&J8.name!=="Free space");for(let J8 of T6){let f6=k6(J8);for(let L8 of f6)if(L6.length<A6)L6.push(L8)}let n6=m6?m6.squares:0,F8=G6.find((J8)=>J8.name==="Free space"),_8=A6-n6;while(L6.length<_8)L6.push({color:"promptBorder",isFilled:!0,categoryName:"Free space",tokens:F8?.tokens||0,percentage:F8?Math.round(F8.tokens/G*100):0,squareFullness:1});if(m6){let J8=k6(m6);for(let f6 of J8)if(L6.length<A6)L6.push(f6)}let Z8=[];for(let J8=0;J8<M6;J8++)Z8.push(L6.slice(J8*B6,(J8+1)*B6));let h6=new Map;for(let[J8,f6]of m.toolCallsByType.entries()){let L8=h6.get(J8)||{callTokens:0,resultTokens:0};h6.set(J8,{...L8,callTokens:f6})}for(let[J8,f6]of m.toolResultsByType.entries()){let L8=h6.get(J8)||{callTokens:0,resultTokens:0};h6.set(J8,{...L8,resultTokens:f6})}let M8=Array.from(h6.entries()).map(([J8,{callTokens:f6,resultTokens:L8}])=>({name:J8,callTokens:f6,resultTokens:L8})).sort((J8,f6)=>f6.callTokens+f6.resultTokens-(J8.callTokens+J8.resultTokens)),S6=Array.from(m.attachmentsByType.entries()).map(([J8,f6])=>({name:J8,tokens:f6})).sort((J8,f6)=>f6.tokens-J8.tokens),w8={toolCallTokens:m.toolCallTokens,toolResultTokens:m.toolResultTokens,attachmentTokens:m.attachmentTokens,assistantMessageTokens:m.assistantMessageTokens,userMessageTokens:m.userMessageTokens,toolCallsByType:M8,attachmentsByType:S6};return{categories:G6,totalTokens:q6,maxTokens:G,rawMaxTokens:G,percentage:Math.round(q6/G*100),gridRows:Z8,model:H,memoryFiles:D,mcpTools:C,deferredBuiltinTools:process.env.USER_TYPE==="ant"?L:void 0,systemTools:process.env.USER_TYPE==="ant"?F:void 0,systemPromptSections:process.env.USER_TYPE==="ant"?O:void 0,agents:y,slashCommands:x>0?{totalCommands:S.totalCommands,includedCommands:S.includedCommands,tokens:x}:void 0,skills:i>0?{totalSkills:b.totalSkills,includedSkills:b.includedSkills,tokens:i,skillFrontmatter:b.skillFrontmatter}:void 0,autoCompactThreshold:o,isAutoCompactEnabled:p,messageBreakdown:w8,apiUsage:V6}}var DG7="Autocompact buffer",MG7="Compact buffer",R38=500;var Zr8=B(()=>{KR();eS();u8();bX();lN();a7();po();gL();Ic();V4();DW6();NW6();SV();c_();R7();A8();t8();l8();i8();Q7();P1();M$();iG6();TN()});function MXY($){return $.replace(/\(\?[=!<][^)]*\)/g,"")}function zy5($){for(let K of Object.keys($)){let Y=$[K];if(K==="pattern"&&typeof Y==="string")$[K]=MXY(Y);else if(Y!==null&&typeof Y==="object")zy5(Y)}return $}function Vs($){if(!$||!$._zod){if($)console.warn(`[zodToJsonSchema] Non-Zod schema received (type: ${typeof $}, constructor: ${$?.constructor?.name})`);return{type:"object",properties:{}}}let K=Xy5.get($);if(K)return K;let Y=zy5(Hm($));return Xy5.set($,Y),Y}var Xy5;var Wr8=B(()=>{g7();Xy5=new WeakMap});var BG7={};j8(BG7,{modelSupportsToolReference:()=>P38,isToolSearchToolAvailable:()=>iZ6,isToolSearchEnabledOptimistic:()=>cP,isToolSearchEnabled:()=>N38,isToolReferenceBlock:()=>Fx,isDeferredToolsDeltaEnabled:()=>T38,getToolSearchMode:()=>jG7,getDeferredToolsDelta:()=>UG7,getAutoToolSearchCharThreshold:()=>Hy5,extractDiscoveredToolNames:()=>yb});function Ay5($){if(!$.startsWith("auto:"))return null;let K=$.slice(5),Y=parseInt(K,10);if(Number.isNaN(Y))return R(`Invalid ENABLE_TOOL_SEARCH value "${$}": expected auto:N where N is a number.`),null;return Math.max(0,Math.min(100,Y))}function NXY($){if(!$)return!1;return $==="auto"||$.startsWith("auto:")}function EG7(){let $=process.env.ENABLE_TOOL_SEARCH;if(!$)return LG7;if($==="auto")return LG7;let K=Ay5($);if(K!==null)return K;return LG7}function Zy5($){let K=gT8($),Y=tG($,K),J=EG7()/100;return Math.floor(Y*J)}function Hy5($){return Math.floor(Zy5($)*BXY)}function jG7(){if(u6(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return"standard";let $=process.env.ENABLE_TOOL_SEARCH,K=$?Ay5($):null;if(K===0)return"tst";if(K===100)return"standard";if(NXY($))return"tst-auto";if(u6($))return"tst";if(z0(process.env.ENABLE_TOOL_SEARCH))return"standard";return"tst"}function jXY(){try{let $=u$("tengu_tool_search_unsupported_models",null);if($&&Array.isArray($)&&$.length>0)return $}catch{}return EXY}function P38($){let K=$.toLowerCase(),Y=jXY();for(let J of Y)if(K.includes(J.toLowerCase()))return!1;return!0}function cP(){let $=jG7();if($==="standard"){if(!dy6)dy6=!0,R(`[ToolSearch:optimistic] mode=${$}, ENABLE_TOOL_SEARCH=${process.env.ENABLE_TOOL_SEARCH}, result=false`);return!1}if(!process.env.ENABLE_TOOL_SEARCH&&r7()==="firstParty"&&!m_()){if(!dy6)dy6=!0,R(`[ToolSearch:optimistic] disabled: ANTHROPIC_BASE_URL=${process.env.ANTHROPIC_BASE_URL} is not a first-party Anthropic host. Set ENABLE_TOOL_SEARCH=true (or auto / auto:N) if your proxy forwards tool_reference blocks.`);return!1}if(!dy6)dy6=!0,R(`[ToolSearch:optimistic] mode=${$}, ENABLE_TOOL_SEARCH=${process.env.ENABLE_TOOL_SEARCH}, result=true`);return!0}function iZ6($){return $.some((K)=>bK(K,ND))}async function UXY($,K,Y){let J=$.filter((X)=>yv(X));if(J.length===0)return 0;return(await Promise.all(J.map(async(X)=>{let z=await X.prompt({getToolPermissionContext:K,tools:$,agents:Y}),A=X.inputJSONSchema?c6(X.inputJSONSchema):X.inputSchema?c6(Vs(X.inputSchema)):"";return X.name.length+z.length+A.length}))).reduce((X,z)=>X+z,0)}async function N38($,K,Y,J,q){let X=e7(K,(Z)=>Z.isMcp);function z(Z,H,G,W){d("tengu_tool_search_mode_decision",{enabled:Z,mode:H,reason:G,checkedModel:$,mcpToolCount:X,userType:process.env.USER_TYPE??"external",...W})}if(!P38($))return R(`Tool search disabled for model '${$}': model does not support tool_reference blocks. This feature is only available on Claude Sonnet 4+, Opus 4+, and newer models.`),z(!1,"standard","model_unsupported"),!1;if(!iZ6(K))return R("Tool search disabled: ToolSearchTool is not available (may have been disallowed via disallowedTools)."),z(!1,"standard","mcp_search_unavailable"),!1;let A=jG7();switch(A){case"tst":return z(!0,A,"tst_enabled"),!0;case"tst-auto":{let{enabled:Z,debugDescription:H,metrics:G}=await PXY(K,Y,J,$);if(Z)return R(`Auto tool search enabled: ${H}${q?` [source: ${q}]`:""}`),z(!0,A,"auto_above_threshold",G),!0;return R(`Auto tool search disabled: ${H}${q?` [source: ${q}]`:""}`),z(!1,A,"auto_below_threshold",G),!1}case"standard":return z(!1,A,"standard_mode"),!1}}function Fx($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="tool_reference"}function RXY($){return Fx($)&&"tool_name"in $&&typeof $.tool_name==="string"}function FXY($){return typeof $==="object"&&$!==null&&"type"in $&&$.type==="tool_result"&&"content"in $&&Array.isArray($.content)}function yb($){let K=new Set,Y=0;for(let J of $){if(J.type==="system"&&J.subtype==="compact_boundary"){let X=J.compactMetadata?.preCompactDiscoveredTools;if(X){for(let z of X)K.add(z);Y+=X.length}continue}if(J.type!=="user")continue;let q=J.message?.content;if(!Array.isArray(q))continue;for(let X of q)if(FXY(X)){for(let z of X.content)if(RXY(z))K.add(z.tool_name)}}if(K.size>0)R(`Dynamic tool loading: found ${K.size} discovered tools in message history`+(Y>0?` (${Y} carried from compact boundary)`:""));return K}function T38(){return process.env.USER_TYPE==="ant"||u$("tengu_glacier_2xr",!1)}function UG7($,K,Y){let J=new Set,q=0,X=0,z=new Set;for(let V of K){if(V.type!=="attachment")continue;if(q++,z.add(V.attachment.type),V.attachment.type!=="deferred_tools_delta")continue;X++;for(let _ of V.attachment.addedNames)J.add(_);for(let _ of V.attachment.removedNames)J.delete(_)}let A=$.filter(yv),Z=new Set(A.map((V)=>V.name)),H=new Set($.map((V)=>V.name)),G=A.filter((V)=>!J.has(V.name)),W=[];for(let V of J){if(Z.has(V))continue;if(!H.has(V))W.push(V)}if(G.length===0&&W.length===0)return null;return d("tengu_deferred_tools_pool_change",{addedCount:G.length,removedCount:W.length,priorAnnouncedCount:J.size,messagesLength:K.length,attachmentCount:q,dtdCount:X,callSite:Y?.callSite??"unknown",querySource:Y?.querySource??"unknown",attachmentTypesSeen:[...z].sort().join(",")}),{addedNames:G.map((V)=>V.name).sort(),addedLines:G.map(X68).sort(),removedNames:W.sort()}}async function PXY($,K,Y,J){let q=await LXY($,K,Y,J);if(q!==null){let A=Zy5(J);return{enabled:q>=A,debugDescription:`${q} tokens (threshold: ${A}, ${EG7()}% of context)`,metrics:{deferredToolTokens:q,threshold:A}}}let X=await UXY($,K,Y),z=Hy5(J);return{enabled:X>=z,debugDescription:`${X} chars (threshold: ${z}, ${EG7()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:X,charThreshold:z}}}var LG7=10,BXY=2.5,LXY,EXY,dy6=!1;var kv=B(()=>{S5();a7();d8();V4();oa();Zr8();zD();c_();A8();t8();lK();M$();Wr8();LXY=F$(async($,K,Y,J)=>{let q=$.filter((X)=>yv(X));if(q.length===0)return 0;try{let X=await x96(q,K,{activeAgents:Y,allAgents:Y},J);if(X===0)return null;return Math.max(0,X-R38)}catch{return null}},($)=>$.filter((K)=>yv(K)).map((K)=>K.name).join(","));EXY=["haiku"]});import{createHash as Wy5,randomUUID as TXY}from"crypto";import{mkdir as Vy5,readFile as _y5,writeFile as Oy5}from"fs/promises";import{dirname as Qy5,join as wy5}from"path";function FG7(){if(process.env.USER_TYPE==="ant"&&u6(process.env.FORCE_VCR))return!0;return!1}async function CXY($,K,Y){if(!FG7())return await Y();let J=Wy5("sha1").update(c6($)).digest("hex").slice(0,12),q=wy5(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??P8(),`fixtures/${K}-${J}.json`);try{return Q$(await _y5(q,{encoding:"utf8"}))}catch(z){if(c7(z)!=="ENOENT")throw z}if((F7.isCI||process.env.CI)&&!u6(process.env.VCR_RECORD))throw Error(`Fixture missing: ${q}. Re-run tests with VCR_RECORD=1, then commit the result.`);let X=await Y();return await Vy5(Qy5(q),{recursive:!0}),await Oy5(q,c6(X,null,2),{encoding:"utf8"}),X}async function _r8($,K){if(!FG7())return await K();let Y=AW($.filter((z)=>{if(z.type!=="user")return!0;if(z.isMeta)return!1;return!0})),J=vXY(Y.map((z)=>z.message.content),RG7),q=wy5(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??P8(),`fixtures/${J.map((z)=>Wy5("sha1").update(c6(z)).digest("hex").slice(0,6)).join("-")}.json`);try{let z=Q$(await _y5(q,{encoding:"utf8"}));return z.output.forEach(IXY),z.output.map((A,Z)=>Gy5(A,fXY,Z,TXY()))}catch(z){if(c7(z)!=="ENOENT")throw z}if(F7.isCI&&!u6(process.env.VCR_RECORD))throw Error(`Anthropic API fixture missing: ${q}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:
|
|
3996
3996
|
${c6(J,null,2)}`);let X=await K();if(F7.isCI&&!u6(process.env.VCR_RECORD))return X;return await Vy5(Qy5(q),{recursive:!0}),await Oy5(q,c6({input:J,output:X.map((z,A)=>Gy5(z,RG7,A))},null,2),{encoding:"utf8"}),X}function IXY($){if($.type==="stream_event")return;let K=$.message.model,Y=$.message.usage,J=nX6(K,Y);s16(J,Y,K)}function vXY($,K){return $.map((Y)=>{if(typeof Y==="string")return K(Y);return Y.map((J)=>{switch(J.type){case"tool_result":if(typeof J.content==="string")return{...J,content:K(J.content)};if(Array.isArray(J.content))return{...J,content:J.content.map((q)=>{switch(q.type){case"text":return{...q,text:K(q.text)};case"image":return q;default:return}})};return J;case"text":return{...J,text:K(J.text)};case"tool_use":return{...J,input:Vr8(J.input,K)};case"image":return J;default:return}})})}function Vr8($,K){return Jg($,(Y,J)=>{if(Array.isArray(Y))return Y.map((q)=>Vr8(q,K));if(UN6(Y))return Vr8(Y,K);return K(Y,J,$)})}function yXY($,K,Y,J){return{uuid:J??`UUID-${Y}`,requestId:"REQUEST_ID",timestamp:$.timestamp,message:{...$.message,content:$.message.content.map((q)=>{switch(q.type){case"text":return{...q,text:K(q.text),citations:q.citations||[]};case"tool_use":return{...q,input:Vr8(q.input,K)};default:return q}}).filter(Boolean)},type:"assistant"}}function Gy5($,K,Y,J){if($.type==="assistant")return yXY($,K,Y,J);else return $}function RG7($){if(typeof $!=="string")return $;let K=P8(),Y=c$(),J=$.replace(/num_files="\d+"/g,'num_files="[NUM]"').replace(/duration_ms="\d+"/g,'duration_ms="[DURATION]"').replace(/cost_usd="\d+"/g,'cost_usd="[COST]"').replaceAll(Y,"[CONFIG_HOME]").replaceAll(K,"[CWD]").replace(/Available commands:.+/,"Available commands: [COMMANDS]");if(process.platform==="win32"){let q=K.replaceAll("\\","/"),X=Y.replaceAll("\\","/"),z=c6(K).slice(1,-1),A=c6(Y).slice(1,-1);J=J.replaceAll(z,"[CWD]").replaceAll(A,"[CONFIG_HOME]").replaceAll(q,"[CWD]").replaceAll(X,"[CONFIG_HOME]")}if(J=J.replace(/\[CWD\][^\s"'<>]*/g,(q)=>q.replaceAll("\\\\","/").replaceAll("\\","/")).replace(/\[CONFIG_HOME\][^\s"'<>]*/g,(q)=>q.replaceAll("\\\\","/").replaceAll("\\","/")),J.includes("Files modified by user:"))return"Files modified by user: [FILES]";return J}function fXY($){if(typeof $!=="string")return $;return $.replaceAll("[NUM]","1").replaceAll("[DURATION]","100").replaceAll("[CONFIG_HOME]",c$()).replaceAll("[CWD]",P8())}async function*PG7($,K){if(!FG7())return yield*K();let Y=[],J=await _r8($,async()=>{for await(let q of K())Y.push(q);return Y});if(J.length>0){yield*J;return}yield*Y}async function Dy5($,K,Y){let J=P8().replace(/[^a-zA-Z0-9]/g,"-"),q=RG7(c6({messages:$,tools:K})).replaceAll(J,"[CWD_SLUG]").replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"[UUID]").replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z?/g,"[TIMESTAMP]");return(await CXY(q,"token-count",async()=>({tokenCount:await Y()}))).tokenCount}var TG7=B(()=>{sw8();pg6();bU();mm();R7();qY();t8();l8();Q7();M$()});function Ny5($){for(let K of $)if(K.role==="assistant"&&Array.isArray(K.content)){for(let Y of K.content)if(typeof Y==="object"&&Y!==null&&"type"in Y&&(Y.type==="thinking"||Y.type==="redacted_thinking"))return!0}return!1}function kXY($){return $.map((K)=>{if(!Array.isArray(K.content))return K;let Y=K.content.map((J)=>{if(J.type==="tool_use"){let q=J;return{type:"tool_use",id:q.id,name:q.name,input:q.input}}if(J.type==="tool_result"){let q=J;if(Array.isArray(q.content)){let X=q.content.filter((z)=>!Fx(z));if(X.length===0)return{...q,content:[{type:"text",text:"[tool references]"}]};if(X.length!==q.content.length)return{...q,content:X}}}return J});return{...K,content:Y}})}async function By5($){if(!$)return 0;return S$8([{role:"user",content:$}],[])}async function S$8($,K){return Dy5($,K,async()=>{try{let Y=D3(),J=LP(Y),q=Ny5($);if(r7()==="bedrock")return hXY({model:KD(Y),messages:$,tools:K,betas:J,containsThinking:q});if(r7()==="vertex")return null;let z=await(await QS({maxRetries:1,model:Y,source:"count_tokens"})).beta.messages.countTokens({model:KD(Y),messages:$.length>0?$:[{role:"user",content:"foo"}],tools:K,...J.length>0&&{betas:J},...q&&{thinking:{type:"enabled",budget_tokens:IG7}}});if(typeof z.input_tokens!=="number")return null;return z.input_tokens}catch(Y){return Y6(Y),null}})}function N3($,K=4){return Math.round($.length/K)}function SXY($){switch($){case"json":case"jsonl":case"jsonc":return 2;default:return 4}}function Ly5($,K){return N3($,SXY(K))}async function qy5($,K){let Y=Ny5($),J=u6(process.env.CLAUDE_CODE_USE_VERTEX)&&Mh6(Fz())==="global",q=u6(process.env.CLAUDE_CODE_USE_BEDROCK)&&Y,X=u6(process.env.CLAUDE_CODE_USE_VERTEX)&&Y,z=J||q||X?$D():Fz(),A=await QS({maxRetries:1,model:z,source:"count_tokens"}),Z=kXY($),H=Z.length>0?Z:[{role:"user",content:"count"}],G=LP(z),W=r7()==="vertex"?G.filter((N)=>e01.has(N)):G;console.error(`[tokenEstimation] anthropic type: ${typeof A}, has beta: ${A?.beta!==void 0}, has messages: ${A?.beta?.messages!==void 0}`);let _=(await A.beta.messages.create({model:KD(z),max_tokens:Y?My5:1,messages:H,tools:K.length>0?K:void 0,...W.length>0&&{betas:W},metadata:k46(),...Qr8(),...Y&&{thinking:{type:"enabled",budget_tokens:IG7}}})).usage,O=_.input_tokens,w=_.cache_creation_input_tokens||0,D=_.cache_read_input_tokens||0;return O+w+D}function uP($){let K=0;for(let Y of $)K+=bXY(Y);return K}function bXY($){if(($.type==="assistant"||$.type==="user")&&$.message?.content)return CG7($.message?.content);if($.type==="attachment"&&$.attachment){let K=Or8($.attachment),Y=0;for(let J of K)Y+=CG7(J.message.content);return Y}return 0}function CG7($){if(!$)return 0;if(typeof $==="string")return N3($);let K=0;for(let Y of $)K+=xXY(Y);return K}function xXY($){if(typeof $==="string")return N3($);if($.type==="text")return N3($.text);if($.type==="image"||$.type==="document")return 2000;if($.type==="tool_result")return CG7($.content);if($.type==="tool_use")return N3($.name+c6($.input??{}));if($.type==="thinking")return N3($.thinking);if($.type==="redacted_thinking")return N3($.data);return N3(c6($))}async function hXY({model:$,messages:K,tools:Y,betas:J,containsThinking:q}){try{let X=await T11(),z=hf$($)?$:await HU8($);if(!z)return null;let A={anthropic_version:"bedrock-2023-05-31",messages:K.length>0?K:[{role:"user",content:"foo"}],max_tokens:q?My5:1,...Y.length>0&&{tools:Y},...J.length>0&&{anthropic_beta:J},...q&&{thinking:{type:"enabled",budget_tokens:IG7}}},{CountTokensCommand:Z}=await import("@aws-sdk/client-bedrock-runtime"),H={modelId:z,input:{invokeModel:{body:new TextEncoder().encode(c6(A))}}};return(await X.send(new Z(H))).inputTokens??null}catch(X){return Y6(X),null}}var IG7=1024,My5=2048;var gL=B(()=>{lK();I$6();zD();t8();i8();Q7();bi6();P1();M$();kv();Kz();Y76();TG7()});import{randomUUID as gXY}from"crypto";import{mkdir as mXY,readdir as uXY,readFile as pXY}from"fs/promises";import{join as Ey5}from"path";async function jy5($){try{let J=(await G8().stat($)).size;if(J===0)return{success:!1,error:{reason:"empty",message:`PDF file is empty: ${$}`}};if(J>OF6)return{success:!1,error:{reason:"too_large",message:`PDF file exceeds maximum allowed size of ${l5(OF6)}.`}};let q=await pXY($);if(!q.subarray(0,5).toString("ascii").startsWith("%PDF-"))return{success:!1,error:{reason:"corrupted",message:`File is not a valid PDF (missing %PDF- header): ${$}`}};let z=q.toString("base64");return{success:!0,data:{type:"pdf",file:{filePath:$,base64:z,originalSize:J}}}}catch(K){return{success:!1,error:{reason:"unknown",message:d6(K)}}}}async function Dr8($){let{code:K,stdout:Y}=await H$("pdfinfo",[$],{timeout:1e4,useCwd:!1});if(K!==0)return null;let J=/^Pages:\s+(\d+)/m.exec(Y);if(!J)return null;let q=parseInt(J[1],10);return Number.isNaN(q)?null:q}async function cXY(){if(wr8!==void 0)return wr8;let{code:$,stderr:K}=await H$("pdftoppm",["-v"],{timeout:5000,useCwd:!1});return wr8=$===0||K.length>0,wr8}async function vG7($,K){try{let q=(await G8().stat($)).size;if(q===0)return{success:!1,error:{reason:"empty",message:`PDF file is empty: ${$}`}};if(q>Lt$)return{success:!1,error:{reason:"too_large",message:`PDF file exceeds maximum allowed size for text extraction (${l5(Lt$)}).`}};if(!await cXY())return{success:!1,error:{reason:"unavailable",message:"pdftoppm is not installed. Install poppler-utils (e.g. `brew install poppler` or `apt-get install poppler-utils`) to enable PDF page rendering."}};let z=gXY(),A=Ey5(m76(),`pdf-${z}`);await mXY(A,{recursive:!0});let Z=Ey5(A,"page"),H=["-jpeg","-r","100"];if(K?.firstPage)H.push("-f",String(K.firstPage));if(K?.lastPage&&K.lastPage!==1/0)H.push("-l",String(K.lastPage));H.push($,Z);let{code:G,stderr:W}=await H$("pdftoppm",H,{timeout:120000,useCwd:!1});if(G!==0){if(/password/i.test(W))return{success:!1,error:{reason:"password_protected",message:"PDF is password-protected. Please provide an unprotected version."}};if(/damaged|corrupt|invalid/i.test(W))return{success:!1,error:{reason:"corrupted",message:"PDF file is corrupted or invalid."}};return{success:!1,error:{reason:"unknown",message:`pdftoppm failed: ${W}`}}}let _=(await uXY(A)).filter((D)=>D.endsWith(".jpg")).sort();if(_.length===0)return{success:!1,error:{reason:"corrupted",message:"pdftoppm produced no output pages. The PDF may be invalid."}};let w=_.length;return{success:!0,data:{type:"parts",file:{filePath:$,originalSize:q,outputDir:A,count:w}}}}catch(Y){return{success:!1,error:{reason:"unknown",message:d6(Y)}}}}var wr8;var yG7=B(()=>{l8();I5();L4();q4();UN()});import{createReadStream as dXY,fstat as lXY}from"fs";import{stat as iXY,readFile as nXY}from"fs/promises";async function _s($,K=0,Y,J,q,X){q?.throwIfAborted();let z=X?.truncateOnByteLimit??!1,A=await iXY($);if(A.isDirectory())throw Error(`EISDIR: illegal operation on a directory, read '${$}'`);if(A.isFile()&&A.size<aXY){if(!z&&J!==void 0&&A.size>J)throw new C38(A.size,J);let Z=await nXY($,{encoding:"utf8",signal:q});return rXY(Z,A.mtimeMs,K,Y,z?J:void 0)}return eXY($,K,Y,J,z,q)}function rXY($,K,Y,J,q){let X=J!==void 0?Y+J:1/0,z=$.charCodeAt(0)===65279?$.slice(1):$,A=[],Z=0,H=0,G,W=0,V=!1;function _(w){if(q!==void 0){let D=A.length>0?1:0,N=W+D+Buffer.byteLength(w);if(N>q)return V=!0,!1;W=N}return A.push(w),!0}while((G=z.indexOf(`
|
|
3997
3997
|
`,H))!==-1){if(Z>=Y&&Z<X&&!V){let w=z.slice(H,G);if(w.endsWith("\r"))w=w.slice(0,-1);_(w)}Z++,H=G+1}if(Z>=Y&&Z<X&&!V){let w=z.slice(H);if(w.endsWith("\r"))w=w.slice(0,-1);_(w)}Z++;let O=A.join(`
|
|
3998
3998
|
`);return{content:O,lineCount:A.length,totalLines:Z,totalBytes:Buffer.byteLength(z,"utf8"),readBytes:Buffer.byteLength(O,"utf8"),mtimeMs:K,...V?{truncatedByBytes:!0}:{}}}function oXY($){lXY($,(K,Y)=>{this.resolveMtime(K?0:Y.mtimeMs)})}function sXY($){if(this.isFirstChunk){if(this.isFirstChunk=!1,$.charCodeAt(0)===65279)$=$.slice(1)}if(this.totalBytesRead+=Buffer.byteLength($),!this.truncateOnByteLimit&&this.maxBytes!==void 0&&this.totalBytesRead>this.maxBytes){this.stream.destroy(new C38(this.totalBytesRead,this.maxBytes));return}let K=this.partial.length>0?this.partial+$:$;this.partial="";let Y=0,J;while((J=K.indexOf(`
|