File size: 13,145 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | /**
* Pure permission type definitions extracted to break import cycles.
*
* This file contains only type definitions and constants with no runtime dependencies.
* Implementation files remain in src/utils/permissions/ but can now import from here
* to avoid circular dependencies.
*/
import { feature } from 'bun:bundle'
import type { ContentBlockParam } from '@anthropic-ai/sdk/resources/messages.mjs'
// ============================================================================
// Permission Modes
// ============================================================================
export const EXTERNAL_PERMISSION_MODES = [
'acceptEdits',
'bypassPermissions',
'default',
'dontAsk',
'plan',
] as const
export type ExternalPermissionMode = (typeof EXTERNAL_PERMISSION_MODES)[number]
// Exhaustive mode union for typechecking. The user-addressable runtime set
// is INTERNAL_PERMISSION_MODES below.
export type InternalPermissionMode = ExternalPermissionMode | 'auto' | 'bubble'
export type PermissionMode = InternalPermissionMode
// Runtime validation set: modes that are user-addressable (settings.json
// defaultMode, --permission-mode CLI flag, conversation recovery).
export const INTERNAL_PERMISSION_MODES = [
...EXTERNAL_PERMISSION_MODES,
...(feature('TRANSCRIPT_CLASSIFIER') ? (['auto'] as const) : ([] as const)),
] as const satisfies readonly PermissionMode[]
export const PERMISSION_MODES = INTERNAL_PERMISSION_MODES
// ============================================================================
// Permission Behaviors
// ============================================================================
export type PermissionBehavior = 'allow' | 'deny' | 'ask'
// ============================================================================
// Permission Rules
// ============================================================================
/**
* Where a permission rule originated from.
* Includes all SettingSource values plus additional rule-specific sources.
*/
export type PermissionRuleSource =
| 'userSettings'
| 'projectSettings'
| 'localSettings'
| 'flagSettings'
| 'policySettings'
| 'cliArg'
| 'command'
| 'session'
/**
* The value of a permission rule - specifies which tool and optional content
*/
export type PermissionRuleValue = {
toolName: string
ruleContent?: string
}
/**
* A permission rule with its source and behavior
*/
export type PermissionRule = {
source: PermissionRuleSource
ruleBehavior: PermissionBehavior
ruleValue: PermissionRuleValue
}
// ============================================================================
// Permission Updates
// ============================================================================
/**
* Where a permission update should be persisted
*/
export type PermissionUpdateDestination =
| 'userSettings'
| 'projectSettings'
| 'localSettings'
| 'session'
| 'cliArg'
/**
* Update operations for permission configuration
*/
export type PermissionUpdate =
| {
type: 'addRules'
destination: PermissionUpdateDestination
rules: PermissionRuleValue[]
behavior: PermissionBehavior
}
| {
type: 'replaceRules'
destination: PermissionUpdateDestination
rules: PermissionRuleValue[]
behavior: PermissionBehavior
}
| {
type: 'removeRules'
destination: PermissionUpdateDestination
rules: PermissionRuleValue[]
behavior: PermissionBehavior
}
| {
type: 'setMode'
destination: PermissionUpdateDestination
mode: ExternalPermissionMode
}
| {
type: 'addDirectories'
destination: PermissionUpdateDestination
directories: string[]
}
| {
type: 'removeDirectories'
destination: PermissionUpdateDestination
directories: string[]
}
/**
* Source of an additional working directory permission.
* Note: This is currently the same as PermissionRuleSource but kept as a
* separate type for semantic clarity and potential future divergence.
*/
export type WorkingDirectorySource = PermissionRuleSource
/**
* An additional directory included in permission scope
*/
export type AdditionalWorkingDirectory = {
path: string
source: WorkingDirectorySource
}
// ============================================================================
// Permission Decisions & Results
// ============================================================================
/**
* Minimal command shape for permission metadata.
* This is intentionally a subset of the full Command type to avoid import cycles.
* Only includes properties needed by permission-related components.
*/
export type PermissionCommandMetadata = {
name: string
description?: string
// Allow additional properties for forward compatibility
[key: string]: unknown
}
/**
* Metadata attached to permission decisions
*/
export type PermissionMetadata =
| { command: PermissionCommandMetadata }
| undefined
/**
* Result when permission is granted
*/
export type PermissionAllowDecision<
Input extends { [key: string]: unknown } = { [key: string]: unknown },
> = {
behavior: 'allow'
updatedInput?: Input
userModified?: boolean
decisionReason?: PermissionDecisionReason
toolUseID?: string
acceptFeedback?: string
contentBlocks?: ContentBlockParam[]
}
/**
* Metadata for a pending classifier check that will run asynchronously.
* Used to enable non-blocking allow classifier evaluation.
*/
export type PendingClassifierCheck = {
command: string
cwd: string
descriptions: string[]
}
/**
* Result when user should be prompted
*/
export type PermissionAskDecision<
Input extends { [key: string]: unknown } = { [key: string]: unknown },
> = {
behavior: 'ask'
message: string
updatedInput?: Input
decisionReason?: PermissionDecisionReason
suggestions?: PermissionUpdate[]
blockedPath?: string
metadata?: PermissionMetadata
/**
* If true, this ask decision was triggered by a bashCommandIsSafe_DEPRECATED security check
* for patterns that splitCommand_DEPRECATED could misparse (e.g. line continuations, shell-quote
* transformations). Used by bashToolHasPermission to block early before splitCommand_DEPRECATED
* transforms the command. Not set for simple newline compound commands.
*/
isBashSecurityCheckForMisparsing?: boolean
/**
* If set, an allow classifier check should be run asynchronously.
* The classifier may auto-approve the permission before the user responds.
*/
pendingClassifierCheck?: PendingClassifierCheck
/**
* Optional content blocks (e.g., images) to include alongside the rejection
* message in the tool result. Used when users paste images as feedback.
*/
contentBlocks?: ContentBlockParam[]
}
/**
* Result when permission is denied
*/
export type PermissionDenyDecision = {
behavior: 'deny'
message: string
decisionReason: PermissionDecisionReason
toolUseID?: string
}
/**
* A permission decision - allow, ask, or deny
*/
export type PermissionDecision<
Input extends { [key: string]: unknown } = { [key: string]: unknown },
> =
| PermissionAllowDecision<Input>
| PermissionAskDecision<Input>
| PermissionDenyDecision
/**
* Permission result with additional passthrough option
*/
export type PermissionResult<
Input extends { [key: string]: unknown } = { [key: string]: unknown },
> =
| PermissionDecision<Input>
| {
behavior: 'passthrough'
message: string
decisionReason?: PermissionDecision<Input>['decisionReason']
suggestions?: PermissionUpdate[]
blockedPath?: string
/**
* If set, an allow classifier check should be run asynchronously.
* The classifier may auto-approve the permission before the user responds.
*/
pendingClassifierCheck?: PendingClassifierCheck
}
/**
* Explanation of why a permission decision was made
*/
export type PermissionDecisionReason =
| {
type: 'rule'
rule: PermissionRule
}
| {
type: 'mode'
mode: PermissionMode
}
| {
type: 'subcommandResults'
reasons: Map<string, PermissionResult>
}
| {
type: 'permissionPromptTool'
permissionPromptToolName: string
toolResult: unknown
}
| {
type: 'hook'
hookName: string
hookSource?: string
reason?: string
}
| {
type: 'asyncAgent'
reason: string
}
| {
type: 'sandboxOverride'
reason: 'excludedCommand' | 'dangerouslyDisableSandbox'
}
| {
type: 'classifier'
classifier: string
reason: string
}
| {
type: 'workingDir'
reason: string
}
| {
type: 'safetyCheck'
reason: string
// When true, auto mode lets the classifier evaluate this instead of
// forcing a prompt. True for sensitive-file paths (.claude/, .git/,
// shell configs) — the classifier can see context and decide. False
// for Windows path bypass attempts and cross-machine bridge messages.
classifierApprovable: boolean
}
| {
type: 'other'
reason: string
}
// ============================================================================
// Bash Classifier Types
// ============================================================================
export type ClassifierResult = {
matches: boolean
matchedDescription?: string
confidence: 'high' | 'medium' | 'low'
reason: string
}
export type ClassifierBehavior = 'deny' | 'ask' | 'allow'
export type ClassifierUsage = {
inputTokens: number
outputTokens: number
cacheReadInputTokens: number
cacheCreationInputTokens: number
}
export type YoloClassifierResult = {
thinking?: string
shouldBlock: boolean
reason: string
unavailable?: boolean
/**
* API returned "prompt is too long" — the classifier transcript exceeded
* the context window. Deterministic (same transcript → same error), so
* callers should fall back to normal prompting rather than retry/fail-closed.
*/
transcriptTooLong?: boolean
/** The model used for this classifier call */
model: string
/** Token usage from the classifier API call (for overhead telemetry) */
usage?: ClassifierUsage
/** Duration of the classifier API call in ms */
durationMs?: number
/** Character lengths of the prompt components sent to the classifier */
promptLengths?: {
systemPrompt: number
toolCalls: number
userPrompts: number
}
/** Path where error prompts were dumped (only set when unavailable due to API error) */
errorDumpPath?: string
/** Which classifier stage produced the final decision (2-stage XML only) */
stage?: 'fast' | 'thinking'
/** Token usage from stage 1 (fast) when stage 2 was also run */
stage1Usage?: ClassifierUsage
/** Duration of stage 1 in ms when stage 2 was also run */
stage1DurationMs?: number
/**
* API request_id (req_xxx) for stage 1. Enables joining to server-side
* api_usage logs for cache-miss / routing attribution. Also used for the
* legacy 1-stage (tool_use) classifier — the single request goes here.
*/
stage1RequestId?: string
/**
* API message id (msg_xxx) for stage 1. Enables joining the
* tengu_auto_mode_decision analytics event to the classifier's actual
* prompt/completion in post-analysis.
*/
stage1MsgId?: string
/** Token usage from stage 2 (thinking) when stage 2 was run */
stage2Usage?: ClassifierUsage
/** Duration of stage 2 in ms when stage 2 was run */
stage2DurationMs?: number
/** API request_id for stage 2 (set whenever stage 2 ran) */
stage2RequestId?: string
/** API message id (msg_xxx) for stage 2 (set whenever stage 2 ran) */
stage2MsgId?: string
}
// ============================================================================
// Permission Explainer Types
// ============================================================================
export type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH'
export type PermissionExplanation = {
riskLevel: RiskLevel
explanation: string
reasoning: string
risk: string
}
// ============================================================================
// Tool Permission Context
// ============================================================================
/**
* Mapping of permission rules by their source
*/
export type ToolPermissionRulesBySource = {
[T in PermissionRuleSource]?: string[]
}
/**
* Context needed for permission checking in tools
* Note: Uses a simplified DeepImmutable approximation for this types-only file
*/
export type ToolPermissionContext = {
readonly mode: PermissionMode
readonly additionalWorkingDirectories: ReadonlyMap<
string,
AdditionalWorkingDirectory
>
readonly alwaysAllowRules: ToolPermissionRulesBySource
readonly alwaysDenyRules: ToolPermissionRulesBySource
readonly alwaysAskRules: ToolPermissionRulesBySource
readonly isBypassPermissionsModeAvailable: boolean
readonly strippedDangerousRules?: ToolPermissionRulesBySource
readonly shouldAvoidPermissionPrompts?: boolean
readonly awaitAutomatedChecksBeforeDialog?: boolean
readonly prePlanMode?: PermissionMode
}
|